Using digitalWrite and Read with Port Manipulation

Thread Starter

Abdel_Rahman

Joined Jul 19, 2016
42
Can I use both direct functions digitalWrite and digitalRead along with port manipulation in the same code
Such as:

void setup() {
pinMode(2, INPUT); pinMode(3, INPUT);
}

void loop() {
if ( PINE & B00100000 ) {//dosomething
}}
and does that have a positive effect on the arduino speed as I expect?
 

Thread Starter

Abdel_Rahman

Joined Jul 19, 2016
42
Thanks for Reply :)

The Other Code is:

void setup() { pinMode(2, INPUT); pinMode(3, INPUT);}
void loop() {if ( digitalRead(3)) {//dosomething}}

I know that Port manipulation is faster than using digitalRead() and digitalWrite() functions. isn't it??
 

m zaid

Joined Jan 9, 2016
46
It pretty much depends on the compiler for how is the translation of your C code to assembly. Coding by assembly is using the specific and the most basic instructions a microcontroller can support. Each instruction takes a few oscillator cycle to know how fast.

For example for a 8 bit PIC microchip device, the best you could do for a 'digital read and test of a bit' is using the single instruction 'btfsc' which reads bit test file skip next line if clear. If you were to read the port and compare it to a literal byte, you'd be doing more assembly i.e.
movlw 0x20
andwf PINE,0
movwf buffer
btfsc buffer,5
goto FALSE
.
.

See a microcontroller's datasheet about it's instruction set. Page 55.
 
Last edited:

dannyf

Joined Sep 13, 2015
2,197
I know that Port manipulation is faster than using digitalRead() and digitalWrite() functions. isn't it??
Yeah. Per my test (https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/), the speed gains from using register access ranges from 20x - 70x. The arduino team could have done a much better job there.

For STM32-based Arduino, the speed penalty isn't as much: 5 - 20x (https://dannyelectronics.wordpress.com/2016/04/30/the-price-of-stm32-arduino/).
 

4WorX

Joined Jul 27, 2016
1
Yeah. Per my test (https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/), the speed gains from using register access ranges from 20x - 70x. The arduino team could have done a much better job there.

Very nice write up. That was very helpful.
I knew there was overhead with the Arduino C, but didn't have a grasp of how much.

For those of us with little (or no) experience with assembly language, do you have a quick reference guide where an alternative technique from the standard Arduino approach?

Again many thanks.
 
Top