Sunday, 14 September 2014

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


What are the fastest alternatives to calling the Arduino functions digitalread() and digitalwrite()? AVR-specific or chip-specific solutions are acceptable.



Answer



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));



[...]



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!



No comments:

Post a Comment

arduino - Can I use TI's cc2541 BLE as micro controller to perform operations/ processing instead of ATmega328P AU to save cost?

I am using arduino pro mini (which contains Atmega328p AU ) along with cc2541(HM-10) to process and transfer data over BLE to smartphone. I...