Busy Waiting with the Arduino

For Friday Minis this week, we looked at the concept of Busy Waiting, which we explored using the Arduino, two LEDs an a switch!

If you are more interested in my Arduino code or setup, read on!

For code download, you can use this Google Drive link: https://drive.google.com/open?id=0B2Ia5aQpQ8CnM2Q3b3RvVVJkb1E.

The connections are extremely simple:

We start by using “#define” statements to create constants:

#define LED_BLINK 2
#define LED_PRESS 3
#define BTN 7

The yellow LED on Pin 2 is set up to blink, and the code is exactly as you would expect, at least to start off with:

digitalWrite(LED_BLINK, LOW);
delay(500);
digitalWrite(LED_BLINK, HIGH);
delay(500);

However, we also need to respond to the button press. Again, this is trivial to do on its own:

if (digitalRead(BTN) == HIGH) {
  digitalWrite(LED_PRESS, HIGH);
}
else {
  digitalWrite(LED_PRESS, LOW);
}

The difficulty comes about when we want to do both at the same time. Because the “delay” statements in the LED blink code will busy wait, the processor is all tied up, preventing us from checking the button state.

To work around this, we implement our own busy waiting code, which at its simplest, looks like this:

void busyWait(long duration) {
  long end_time = millis() + duration;
  while (millis() < end_time);
}

This code simply calculates an end time, then stays in a while loop until the end time is reached. While this is not yet any different from just using “delay()”, we can easily expand the loop to add some more logic:

void busyWait(long duration) {
  long end_time = millis() + duration;
  while (millis() < end_time) {
    if (digitalRead(BTN) == HIGH) {
      digitalWrite(LED_PRESS, HIGH);
    }
    else {
      digitalWrite(LED_PRESS, LOW);
    }
  }
}

With the LED handling code inside of the busy wait, we are guaranteed that button presses will be handled even while waiting! This is a good way to do “fake multi-threading”, without deviating too far from the busy waiting formula.

That’s as simple as it gets! You can download the code for this project here. If you like my work and wish to support me, I’ll greatly appreciate a one-time or recurring donation!