I'm trying to blink an LED ~exactly~ every second, using the micros() command to keep track of time. In this example, I want to turn it on for 15ms per second.
So, why does this code work:
void loop() {
unsigned long lastblink;
if ((micros() - lastblink) >= 1000000) {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(15); // wait for 15ms
digitalWrite(LED_BUILTIN, LOW); //turn LED off
Serial.println("blink");
lastblink = micros();
}
Serial.println(micros() - lastblink);
}
...but not the exact same code with just the serial print moved before the if statement:
void loop() {
unsigned long lastblink;
Serial.println(micros() - lastblink);
if ((micros() - lastblink) >= 1000000) {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(15); // wait for 15ms
digitalWrite(LED_BUILTIN, LOW); //turn LED off
Serial.println("blink");
lastblink = micros();
}
}
The serial print shouldn't affect the program flow, right?
UKHeliBob:
What do you mean by works and doesn't work ?
No, but it does take time to execute which may be a factor in whatever you are seeing
Please post complete sketches that illustrate the problem
Thank you all for your help! To be more precise, I want to turn on the LED for 'x' ms (in this case, 10ms) out of every 33.33 (1/30th of a second) period. What I mean by 'breaks' is that the LED doesn't flicker like expected, the LED appears to be lit continuously. I know this because I'm recording it with a camera at 60fps and should be able to see it flicker if I go through the footage frame by frame, but with this code it stays on solid. Here's the complete program:
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
// the loop function runs over and over again forever
void loop() {
static unsigned long lastblink = 0;
Serial.println(micros() - lastblink);
if ((micros() - lastblink) >= 33333) {
lastblink = micros();
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(10); // wait for 10ms
digitalWrite(LED_BUILTIN, LOW); //turn LED off
Serial.println("blink");
}
//Serial.println(micros() - lastblink);
}
Creating the 'lastblink' as an static variable seems like a good idea (thank you for that suggestion) as well as moving when I assign the new value of 'lastblink' to the beginning of the if statement. However, that final serial print must be there for the program to work correctly which doesn't make sense.
Why must the final serial print must be uncommented for this program to work?