hi.I am new in Arduino.i write small dimming program.when I press button led brightness incresses from 0 to 255 and stays at 255 (pwm=255).when I press button again led brightness decreses from 255 to 0 and stays at 0 (pwm=0).I use delay function.but I want change DELAY function with something like this if(currentMillis - dimMillis > 25) .but programs stops working correctly.please help me
When your program starts dimMillis has value 0.
You never assign it anything else, so if(currentMillis - dimMillis > 25) after approximately 6 seconds of code running always returns true.
Try updating it here:
The code enters a for/loop which is going to iterate 255 times -- no matter what
Inside this loop you subtract dimMillis from currentMillis and test if the result is greater than 25.
The currentMillis was read at the top of the main Loop(), while dimMillis will be all over the place -- sometimes smaller, sometimes larger. Thevalue is never reset to zero anywhere and, being a global variable retains whatever value that it last had.
When dimMillis is smaller then it gets incremented and you write the for/loop index to the LED pin. When dimMillis is larger -- no writes to the LED.
I can't divine your intention from the code, but have to think that this is your problem.
When you replace blocking calls to delay() with non-blocking code that checks the value of millis(), you have to change the structure of your code fundamentally.
When you use delay(), you can write code that carries out a sequence of actions and your position within the code corresponds to your position within the sequence.
When remove the blocking calls to delay(), you need to provide a different way to know where you are within the sequence. Usually, this means creating a state variable.
For example:
{
for(int i = 0; i < 255; i++)
{
doSomething(i);
delay(INTERVAL);
}
}
You see that converting the loop to a non-blocking structure involved replacing the loop counter i with a global variable to remember where you have got up to. Similarly, if you had code that needed to carry out a sequence of actions then you could use a state machine to record which action was being performed.