int interval = 1000;
unsigned long previous = 0;
void setup() {
// put your setup code here, to run once:
pinMode(12, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
unsigned long current = millis();
if (current >= previous + interval) {
digitalWrite(12, HIGH);
previous = current;
// Serial.println(current);
}
else {
digitalWrite(12, LOW);
// Serial.println(current);
}
}
My code works, the LED Blinks for a very short period every second, but if there are no Serial.println statements as above, the code does not work. Why is that?
Your LED comes on for a very short time because immediately after it was turned on, the next iteration of loop turns it off. It's working but you can't see the flash as it is so short.
When you're printing, you're filling up the serial output buffer and the code blocks until there is space for the next characters you want to print. When the buffer is full (or nearly so) and you turn the LED on and then try to print, it blocks long enough for you to notice the light.
As mentioned above Serial.println can block.
See my detailed tutorial on Arduino Serial I/O for the Real World which shows you how to set a larger non-blocking buffer for you Serial output.
Also my tutorial on How to write Timers and Delays in Arduino which covers why you need to use subtraction and introduces a simple millisDelay class to use for timers and delays
Finally my detailed tutorial on Multi-tasking in Arduino on any board covers doing multiple tasks 'at the same time' and how to use a loopTimer to check tasks are being run of often enough
wildbill:
Your LED comes on for a very short time because immediately after it was turned on, the next iteration of loop turns it off. It's working but you can't see the flash as it is so short.
When you're printing, you're filling up the serial output buffer and the code blocks until there is space for the next characters you want to print. When the buffer is full (or nearly so) and you turn the LED on and then try to print, it blocks long enough for you to notice the light.
Thanks. This makes sense.
(Is this how I reply to a post? And how do I check the answers post by other members? I came to know that people replied to my post by trying to reply to myself and finding answers here)
drmpf:
As mentioned above Serial.println can block.
See my detailed tutorial on Arduino Serial I/O for the Real World which shows you how to set a larger non-blocking buffer for you Serial output.
Also my tutorial on How to write Timers and Delays in Arduino which covers why you need to use subtraction and introduces a simple millisDelay class to use for timers and delays
Finally my detailed tutorial on Multi-tasking in Arduino on any board covers doing multiple tasks 'at the same time' and how to use a loopTimer to check tasks are being run of often enough