Arduino: faster alternatives to digitalread() and digitalwrite()?

Access the digital ports directly!

  • http://www.billporter.info/ready-set-oscillate-the-fastest-way-to-change-arduino-pins/

The 3 methods I tested were

  • digitalWrite(pin, LOW); digitalWrite(pin, HIGH);
  • CLR(PORTB, 0) ; SET(PORTB, 0);
  • PORTB |= _BV(0); PORTB &= ~(_BV(0));

[...]

enter image description here

As you can see, digitalWrite takes around 56 cycles to complete, while direct Port addressing takes 2 cycles. That’s a big difference in time for programs that have lot’s of IO operations!


This library is a good alternative: http://code.google.com/p/digitalwritefast/


As suggested above, access the digital ports directly. But with style!

By writing hard-coded values directly into the hardware registers, you loose in readability and portability.

I've published on Github a tool I called HWA that lets you use an object-oriented interface to the hardware that does not require a C++ compiler and produces high efficiency binary code.

HWA is there: https://github.com/duparq/hwa