Code snippets, anyone?

The arduino framework uses a loop() and setup() function. The setup() function is called only once, the loop() function is called repeatedly.

So what happens if the loop() exits? Then it is called again by the framework. There is an outer loop so to speak that takes care of that. But … that will also take some time. My friend CodeBeat mentioned this and I thought I’d run an experiment.

So I ran this code on an arduino nano (old bootloader):

#include <Arduino.h>


void setup() {
  pinMode(3, OUTPUT); 
}

void loop() {
    digitalWrite(3, !digitalRead(3));
}

This will make pin 3 alternate between a 0 and 1. I hooked up an oscilloscope to pin 3 and measured the frequency of the resulting square wave. The mean frequency of that was about: 61.43 kHz.

Next I ran this slightly altered code:

#include <Arduino.h>


void setup() {
  pinMode(3, OUTPUT); 
}

void loop() {
   while(true) {
      digitalWrite(3, !digitalRead(3));
   }
}

The loop() in the latter bit of code will never exit, thus there is no overhead caused by the outer loop. There is however the extra while statement.
Again I measured the frequency and this time the mean frequency of the square wave turned out to be 62.89 kHz, which is 1.46 kHz faster. So one cycle takes about 0.38 mS less time.

The outer loop does some processing of serial events, but if your sketch does not use that and you need some extra processing time on an already taxed mpu, you can try to speed it up a bit using this approach.

1 Like