Arduino: Replace digitalWrite for 25x faster execution

in #arduino6 years ago (edited)

2000px-Arduino_Logo.svg (1).png

The digitalWrite() function in arduino can be replaced with a faster command called _BV().

Execution of _BV() is found to be 25 times faster than digitalWrite().

For example if the code contains the following line

digitalWrite(2, HIGH);
This can be replaced by
PORTD |= _BV(2);

and

digitalWrite(2, LOW);
by
 PORTD &= ~_BV(2);

The only downside of coding this way is portability. digitalWrite() can be executed on any microcontroller and will always hit the desired output. The output being an argument of the function. Whereas _BV() need one variable and one argument to identify the output. PORTD and 2. Therefore you would have to review the entire code if you were to port this code to a different microcontroller.

The table below gives the equivalence of each output pin and their _BV equivalent for the common Arduino UNO (atmega328).

Arduino Uno Pin # _BV HIGH Level _BV LOW Level
0 PORTD |= _BV(0) PORTD &= ~_BV(0)
1 PORTD |= _BV(1) PORTD &= ~_BV(1)
2 PORTD |= _BV(2) PORTD &= ~_BV(2)
3 PORTD |= _BV(3) PORTD &= ~_BV(3)
4 PORTD |= _BV(4) PORTD &= ~_BV(4)
5 PORTD |= _BV(5) PORTD &= ~_BV(5)
6 PORTD |= _BV(6) PORTD &= ~_BV(6)
7 PORTD |= _BV(7) PORTD &= ~_BV(7)
8 PORTB |= _BV(0) PORTB &= ~_BV(0)
9 PORTB |= _BV(1) PORTB &= ~_BV(1)
10 PORTB |= _BV(2) PORTB &= ~_BV(2)
11 PORTB |= _BV(3) PORTB &= ~_BV(3)
12 PORTB |= _BV(4) PORTB &= ~_BV(4)
13 PORTB |= _BV(5) PORTB &= ~_BV(5)
14 PORTC |= _BV(0) PORTC &= ~_BV(0)
15 PORTC |= _BV(1) PORTC &= ~_BV(1)
16 PORTC |= _BV(2) PORTC &= ~_BV(2)
17 PORTC |= _BV(3) PORTC &= ~_BV(3)
18 PORTC |= _BV(4) PORTC &= ~_BV(4)
19 PORTC |= _BV(5) PORTC &= ~_BV(5)
Sort:  

Congratulations @lechacal! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!