Difference between digitalRead and PORTD read?

#define LineAIn 6
#define LineBIn 3

pinMode(LineAIn,INPUT_PULLUP);
pinMode(LineBIn,INPUT_PULLUP);

The following two statements do not work the same. Can someone tell me why?

while(digitalRead(LineAIn)&&digitalRead(LineBIn));

while(PORTD&B01001000==B01001000);

Regards,

Bert

Homework? Quiz? Test?

When you run the code, what difference do you see?

The Arduino functions read one pin at a time so the two pins might be sampled several microseconds apart. PORTD reads all 8 pins at the same time. Is that important?

Not a test or quiz. This is a real problem.

if would have thought that this statement

while(PORTD&B01001000==B01001000);

would cause the micro to loop there until one of the pins goes low then process the next statement.

This code works:

while(digitalRead(LineAIn)&&digitalRead(LineBIn));

but this code does not wait for one of the lines (pin 6 or pin 3) to drop low:

while(PORTD&B01001000==B01001000);

it goes directly to the next statement.

I'm trying to get this code to run as fast as possible and testing using digitalRead is very slow.

Regards,

Bert

Use an extra set of ().

The code (probably) compares the first B01001000 with the second B01001000, it does not compare the result of the & operation with the second B01001000.

Try

while((PORTD&B01001000)==B01001000);

Look here. C++ Operator Precedence - cppreference.com

And you'll see that the == does indeed outweigh the &. Parenthesis will indeed fix it.

Works better if you read PIND instead of PORTD.

The fact == binds tighter than & and | is a constant source of annoyance in C, its just counter-intuitive and
wrong, but we have to live with it...

Hi All,

The statement:

while((PORTD&B01001000)==B01001000); did not work properly but the statement:

while((PIND&B01001000)==B01001000); did work.

Thank you all for your suggestions.

Regards,

Bert

bvdb:
Hi All,

The statement:

while((PORTD&B01001000)==B01001000); did not work properly but the statement:

while((PIND&B01001000)==B01001000); did work.

Thank you all for your suggestions.

Regards,

Bert

Do you understand the difference between an output register (PORT) and an input register (PIN)?