The “Blink” sketch is fine if you only ever want your Arduino just to blink a light. But odds are good you want it to do some other things as well, like read a button, or run some other outputs.
The trick is to get rid of any long delay() statement, because during delay() the Arduino generally can’t read inputs or change outputs. (There’s an exception: a special thing called an interrupt can run even during a delay, but it’s a bit tricky to implement and not recommended for a beginner.)
The full code is all in one file BlinkWithoutBlocking.ino.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | /*
* Blink Without Blocking
*
* Demonstrates how to use an event loop timer to avoid unnecessary delays in code.
* This sort of form allows you to juggle multiple inputs and outputs more easily.
*
* Robert Zacharias, 2/2017
* released to the public domain by the author
*/
// "global" variables in this section can be used by any function in the whole sketch
int wait = 250; // this variable, of type integer, is the number of milliseconds we'll wait between blinks
long timer = 0; // this variable, of type "long," will help keep track of passing time
bool light = LOW; // this varialbe, of type boolean, will keep track of the current LED state
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // LED_BUILTIN is a handy shortcut for the pin connected to the on-board LED
}
void loop(){
blink(); // just a shortcut to go to the blink() function
digitalWrite(LED_BUILTIN, light); // tells the LED to either go on or off, depending on the value of "light"
}
// here's where we define what the blink() function does
void blink(){
// if it has been more than "wait" amount of time since the light changed
if ( (millis() - timer) > wait ) { // (millis() is the number of milliseconds since the Arduino powered up)
light = !light; // this will "toggle" the value of "light" to its opposite
timer = millis(); // reset the timer
}
// if it has *not* been long enough, the control will just go past the if statement and exit the blink() function
}
|