0
\$\begingroup\$
int i=0;
DDRD = 0xff;
PORTC = 0xff;  
while (1) 
{ 
    if(PINC5 == 1)
    {...}

I have been trying to figure out why the comparison of PC5 pin of PORTC with 1 yields False everytime. I have activated the "pull up" resistor for every pins of Port C. But still, when I compare the PC5 to 1, I don't get the expected result.

I know the proper way is to do the comparison using the bit-masking.

if((PORTC &(1<<PORTC5))==0).

But I can't figure out why the code presented above doesn't work.

I feel like I am missing some fundamentals in bit-wise operators but can't figure out what exactly. Thank you!!

The datasheet of Atmega 328P says the following:

All registers and bit references in this section are written in general form. A lower case “x” represents the numbering letter for the port, and a lower case “n” represents the bit number. However, when using the register or bit defines in a program, the precise form must be used. For example, PORTB3 for bit no. 3 in Port B, here documented generally as PORTxn.

\$\endgroup\$
4
  • \$\begingroup\$ What is the definition of PINC5? \$\endgroup\$
    – Long Pham
    Commented Jan 20, 2020 at 16:24
  • \$\begingroup\$ PINC5 is just a constant which indicated which bit of PORTC matches PC5. It is not the value of that bit. \$\endgroup\$
    – jcaron
    Commented Jan 20, 2020 at 16:24
  • 1
    \$\begingroup\$ Where is it defined? \$\endgroup\$
    – Andy aka
    Commented Jan 20, 2020 at 16:29
  • 2
    \$\begingroup\$ Look here github.com/vancegroup-mirrors/avr-libc/blob/master/avr-libc/… and see that PINC5 is a constant number equal to 5. And to read pin state you need to use a PINC register in your case. \$\endgroup\$
    – G36
    Commented Jan 20, 2020 at 16:42

1 Answer 1

3
\$\begingroup\$

PINC5 and PORTC5 are defines that equate to 5. So the code does not read status of pins of IO port C at all to get the status of the bits, it is just comparing if number 5 is number 1 and it never is. Also, PORTC is the output data register. If you want to read status of a pushbutton, you must read PINC register.

\$\endgroup\$
2
  • \$\begingroup\$ Got it!! Thanks a lot @Justme \$\endgroup\$
    – G-aura-V
    Commented Jan 20, 2020 at 16:48
  • \$\begingroup\$ @JuneStar_2918 I use ARM, not AVR, but with my compiler, with the way the built in register definitions are defined, I can't actually go "if(Register->Bit == 1)" or "if(Register->Bit == true)". I actually have to go "if(Register->Bit)" or "if(!Register->Bit)". Just so you know what's out there. \$\endgroup\$
    – DKNguyen
    Commented Jan 20, 2020 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.