What are the fastest alternatives to calling the Arduino functions
digitalwrite()? AVR-specific or chip-specific solutions are acceptable.
Access the digital ports directly!
The 3 methods I tested were
- digitalWrite(pin, LOW); digitalWrite(pin, HIGH);
- CLR(PORTB, 0) ; SET(PORTB, 0);
- PORTB |= _BV(0); PORTB &= ~(_BV(0));
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
Folks at Arduino.SE have already discussed and tested this. As it turns out,
digitalWriteFast() is not much of improvement over regular
digitalWrite(). Direct port access, however, is about 35-40 times faster than
Use the ChipKit Uno32. It's much faster than the AVR-based Arduinos. It will also deal with your timing problems.