03 November 2016

How fast can Arduino toggle a pin?


I set up this experiment because I wanted to know how fast a standard 16 MHz Arduino board can toggle a pin. Why? Well, say you have a display that can only count up or down: you need to throw in a fast "clock" to reach the desired value unless you are starting from 0.

The following code shows two approaches. A "pure" Arduino code and a lower level version that fiddles with ATmega internals.





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

void loop() {

 for (long j=0; j<200000; j++) {
   digitalWrite(5, HIGH);
   digitalWrite(5, LOW);
  }

  for (long i=0; i>2000000; i++) {
   PORTD = PORTD & B00000111;
   PORTD = PORTD | B00100000;
  }

}


If you connect a frequency counter to pin 5 of the Arduino board you will read two frequencies:

  1. 114 kHz (122)
  2. 1445 kHz (1700)

The slowest is generated with digitalWrite, while the second comes from the PORTD code. That's 12 times faster! Values in parenthesis can be achieved if you run just the toggling commands alone in the main loop(), so they are a sort of "absolute maximum achievable."

Edit: I forgot how to read my frequency counter and later realized that the value represents kHz and not Hz. The frequencies have now been verified with an oscilloscope too. Note that the faster mode generates a "low" impulse as short as 120 ns, but the loop instructions cause the "high" level to last for about 550 ns.