NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Evaluating PIN State

July 11, 2012
by TuffLux
TuffLux's Avatar

Whats the difference between:-

((PINC &(1<<PINC5))==0) and ((1<<PINC5)==0)

If PINC5 is pulled low, shouldn't both evaluate to a 0?

July 11, 2012
by Rick_S
Rick_S's Avatar

First, your statements are incorrect in that it wouldn't be PINC5, it would be PC5. PINC is the register for the the pin values on the C port. PC5 is just equivalent to 5 as we talked about in another thread. When an equal sign is doubled up, it is a comparator not equivalency (that messed me up in the beginning).

So, this statement:

((PINC & (1<<PC5))==0)

Means:

Compare the value for the pins in the C port "AND" (1 shifted 5 times or 0b00100000) to zero.

Lets say that PORTC has been set as an input on pin5:

DDRC &= ~(1<<PC5); // set PC5 as input

Then we turn on the internal pullup resistor so when the pin is left open, it will be high otherwise if we connect it to ground it will go low (High is a value of 1 at the bit position for the pin low is a value of zero)

PORTC |= (1<<PC5); // turn on internal pull up resistor for PC5

Now, if the pin PC5 is open the 6th bit in PORTC will be set and if it is grounded, the 6th bit will be zero.

This would be something like this in binary:

0bxx1xxxxx (Bit set, pin not connected or connected to vcc (x=whatever they are and not relevant for checking the pin in question.
0bxx0xxxxx (Bit not set, pin pulled low by connecting to ground (x=whatever they are and not relevant for checking the pin in question.

So, let's say the pin is set. That's where the comparison comes in.

((PINC & (1<<PC5)) == 0) // Forumula in question
((0bxx1xxxx & 0b00100000) == 0) // Would evaluate to this
(1 == 0) // And finally this which is a false statement as 1 does not equal zero.

Now, if the pin is grounded how does it compare?

((PINC & (1<<PC5)) == 0) // Forumula in question
((0bxx0xxxx & 0b00100000) == 0) // Would evaluate to this
(0 == 0) // And finally this which is a true statement as zero does equal zero.

As for ((1<<PC5)==0), That would compare 0b00100000 to 0b00000000 and would always be false.

Hope I didn't confuse more Plain Smiley

Rick

July 11, 2012
by TuffLux
TuffLux's Avatar

Rick,

Thanks. I've seen what I've done wrong. I've been using (1<<PINC5) as a variable rather than thinking of it's binary representation.

You'd be surprised, but PINC5 actually gives the same as PC5. It might be defined in the include.

Post a Reply

Please log in to post a reply.

Did you know that interrupts can cause problems if you're not careful about timing and memory access? Learn more...