What's the different and benefit of these two usage?

Hi all,
the code below:

int x;    x = PINB;

 if ((x & 0x01) == 0);   // if select button(Pin8) pushed,

and:

if (digitalRead(8) == 0); 

got same reading results, what's difference between them?
Thanks
Adam

The amount of code the compiler generates. You can divide a number by two or shift it right 1, you should get the same answer. One way would be faster, it is up to the programmer to chose.

1 Like

Great!
thank you.

Hi, @shanren
The both your codes is non-functional because the superficial ; aftet the condition :slight_smile:

2 Likes

The argument to digitalRead() is a board pin number, which will be in the same place on an uno or nano-like board regardless of the CPU type. It can also be other values, or even a variable, while your PINB code relies on knowing that the pin in on port B and its bit position is 1.

Much whining is done about the length of code and "slowness" of the arduino digitalRead and digitalWrite calls. It's a worthwhile exercise, for the dedicated student, to look at their code and figure out WHY they are big and slow, and whether it's actually possible to do the same thing faster...

1 Like

Sorry for my typing error.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.