# Function to make a sine wave cut off after one cycle?

``````for (in = 0; in < 6.283   ; in = in + .006283 )
{
out = sin(in * frequencyMultiple) * 127.5 + 127.5;
analogWrite(ledPin, out);
delay(1);
``````

this is only a small segment of my code. I want to be able to cut the graph off after once cycle when varying the speed from 1-4 Hz (frequencyMultiple = x Hz) The problem with doing this is that on 3Hz, the value gets to 255, then jumps to 127.5 brightness. ( 127.5 is starting brightness for graph) What I need is a function that allows the program to keep track of how many times 127.5 is passed, and on the third time restart the cycle to avoid these jumps in brightness. (Starts at 127.5 = 1 time, goes up to 255, goes down past 127.5 = 2 times going down to 0, then back up to 127.5 = 3 times and the graph should restart.)
Note: I am wondering if this is along the lines of being right; float endGraph = 6.283 / frequencyMultiple

Well, floating point is rarely this exact, you can easily get more or less iterations of the loop it is better to use an integer to loop to 100 and multiply the loop counter by .006283 (or whatever)

Better still, calculate a lookup table offline or in setup, and use a fixed-point phase accumulator.

Your endGraph idea is exactly correct. If you end the loop at 2*pi/Frequency, it will run for one entire cycle. It will start out at 127.5 and end up at just below 127.5.

However, I think there must be some other problem. That algorithm as written works perfectly. When I run it, out starts at 127.5, goes up to 254.997, down to 0.000, up to 254.998, down to 0.003, up to 255.000, down to 0.002, and back up to 127.429. The ending value is very close to 127.5. There are no sudden jumps.

The Arduino knows the value PI, this would make the loop more maintainable

``````unsigned int steps 1000;
float stepsize = 2 * PI/steps;

for (in = 0; in < steps; in++)
{
out = sin(in * stepsize * frequencyMultiple) * 127.5 + 127.5;
analogWrite(ledPin, out);
delay(10);   // <<<<<<<<<<<<<<<<<<<<<<<<<< slowed to make the effect more visible
}
``````

are the variables in and out variables of the type float?