What's wrong with this code?

I’m trying to making a dynamic duty cycle that depends on time.
The first if statement works properly and it determines when the duty cycle should change.
But the followed four if statements do not work properly.
When duty cycle reaches 1, It should be decreased it by subtracting 0.1
When duty cycle reaches 0, It should be increased by adding 0.1
The output is pin 13.
I don’t want to use PWM function. I want to use my own function such as the following code.

The code works but: when duty cycle reaches 0. Pin 13 becomes HIGH for long time then it goes to LOW again and process continue normally.

I’ve not bought an Arduino yet. so I simulated it on proteus and different screenshots of the waveform are attached.

I know that this code if (dutyCycle <= 0 ) brings duty cycle to negative values but I don’t understand why?
Here are the solutions but I would like to understand why this long HIGH happens??

First solution:
if (dutyCycle <= 0.1 )

Second solution:
It works well if I started the code like this:
float dutyCycle = 0.9;
unsigned long current_time =1;
boolean large_duty_cycle = true;

Third solution: is to use constrain(dutyCycle, 0, 1)

Would you tell me why duty cycle can be negative??

Thank you very much,

``````float dutyCycle;
unsigned long current_time =1; // if current_time = 0, "If statement" can never be true
boolean large_duty_cycle;

void setup() {

pinMode(13, OUTPUT);
}

void loop() {

digitalWrite(13, HIGH);
delayMicroseconds(2000 * dutyCycle);
digitalWrite(13, LOW);
delayMicroseconds(2000 * (1 - dutyCycle));

if (millis() >= 1 * current_time ) {

current_time ++;

if (dutyCycle >= 1 ) {large_duty_cycle = true ;}

if (dutyCycle <= 0 ) {large_duty_cycle = false ;}

if (large_duty_cycle) {dutyCycle = dutyCycle - 0.1 ; }

if (!large_duty_cycle) {dutyCycle = dutyCycle + 0.1 ;}

}

}
``````

Would you tell me why duty cycle can be negative??

Suppose that dutyCycle is 0.00000001. That's not less than or equal to 0, so you subtract 0.1 from it. Doesn't that result in a negative number?

What can make dutyCycle =0.00000001 ? What causes this error?

It might be not smart question but I'm a beginner and I really would like to know.

Anyway, Thank you very much for your answer and giving me part of your time, I appreciate that.

Floating point math has limited accuracy. Certain numbers don’t express well. For instance, you know how 1/3 is a repeating decimal in decimal notation. In binary you have that problem with 0.1. Float is only precise to 6 or maybe 7 decimal places.

Instead of scaling between 0 and 1 and then multiplying by 2000, why don’t you scale between 0 and 2000 with a step size of 20. That gives you the exact same effect but you can use integers for the math and avoid all this floating point mess.

Floats are only worth it when you have huge ranges of data.

Ohhh now I understand. Thank you very much. You'r answers are very helpful.