In the new book I’m writing I’ve implemented a dice game in multiple ways, starting with all the code in-line, with blocking routines and no interrupts. This is the typical Arduino approach. I’ve just completed an interrupt driven version. In this version, the function loop is:
void loop() {
}
Because everything happens in interrupts! Many people think that using interrupts complicates programs, but at least in this case the program has about 15% less code. It also turns out to be very efficient.
The initial version, which I call All In A Loop, basically uses 100% of the processor cycles playing the game or waiting in one of many polling loops waiting for something to happen. I decided to see how much of the available microcontroller cycles are used in the interrupt driven version.
First, I needed a baseline, so I wrote a program to see how long it took to increment a counter 1,000,000 times. The program is:
// Takes 2.200604 seconds to do the count (Arduino Uno)
void setup() {
Serial.begin(9600);
}
volatile long count;
void loop() {
unsigned long startTime = micros();
count = 0;
while (count < 1000000) {
count = count + 1;
}
Serial.println(micros()-startTime);
}
As stated in the comment, it takes 2.200604 seconds. Then I added the speed test into the interrupt driven game. This was easy to do since the loop function was empty. Then the count took 2.271592 seconds. Where N is the time in the empty program and M is the time with the executing game, the proportion of game utilized cycles is 1 – N/M, or roughly 3.1%. The implication here is that given enough hardware it would be possible to drive over 30 “game stations” from a single Arduino Uno.
I bet you didn’t think that the Arduino is that powerful!
I’m taking this game program one step further before moving on to other topics in the book. I’m going to run it under a RTOS. This will be “overkill” but otherwise an interesting experiment.