_apin.read()!=0 inefficient ?

18 Apr 2011

Hi all..

I'm using some pins as jumpers. I pull them high when I want the hardware to signal to the code that something is turned on.

In hardware I have a 3.3v rail.. and bunch of jumpers so I can connect them to certain pins.

everytime I want to check it in my code I do this...

if (apin.read()!=0) { ..do something.. }

My Q: Will that read take time ( a lot?) compared to reading them all and defining them at the beginning of the program ? They are solder bridges, they won't be changing.

I'm wondering if it's bad practise to keep reading them.

18 Apr 2011

Your code could look like this:

if (apin.read()) { Something meaning full ... }

how much time is a lot? 10'S of microseconds I am guessing.

Regards Ceri

18 Apr 2011

Good point,.. I get so used to the coding style we use at work, where everything has to be spelt out.. That I forget that would work ! I spose I'm just wondering what is the better coding style in C and hardware. To keep reading them. or read them once, then keep testing a variable.

18 Apr 2011

I don't expect any difference in compiled code between if (apin.read()) and if (apin.read()!=0), or even if (apin!=0).

On small microcontrollers with little RAM it often makes sense to not reserve another bit to store the state of a pin, but just keep testing the pin. On mbed that's not an issue. As for the speed, the current mbed API is pretty fast (the pin read is inlined into direct register access) so I don't expect the difference will be noticeable, but reading the pin state does take a little longer than checking a variable. Also, if you test the variable often, the compiler might reserve a register for it, and this will be even faster than a variable in RAM.