How to create pulsating value from 0..1..0..1..0 etc for a given duration?

pollux picture pollux · Jun 10, 2010 · Viewed 13.3k times · Source

I'm working on some code where I have a Time object with a member time. Time.time gives me the time since my application started in seconds (float value). Now I want to create a pulsating value between 0 and 1 and then from 1 to 0 again, which continues doing thins untill the application stops.

I was thinking to use sin() but don't know what to pass to it as paramters to create this pulsing value.

How would I create this pulsating value?

Kind regards, Pollux

Answer

Kleist picture Kleist · Jun 10, 2010

You mention using sin(), so I guess you want it to pulse continuously between 0 and 1.

Something like this will do:

float pulse(float time) {
    const float pi = 3.14;
    const float frequency = 10; // Frequency in Hz
    return 0.5*(1+sin(2 * pi * frequency * time));
}

1/frequency = 0.1 second is the period, which is the time between 1's.