# AtTiny85 reading from PIN

First, I'm kinda new to this AVR world, please don't be too hard.

I'm running into a very simply problem. I'm trying to use the ATTiny85 inside the Arduino framework, but without the Arduino functions digitalRead or digitalWrite (too slow). I have no problem writing signal to pins (PORTB &= 0b00000001), But whatever I try, I'm not able to READ from the pin (PINB & 0b0000001).

However, this is not entirely true. whatever I try (PINB & 0b000001, PINB & 0b000010, PINB & 0b000100, I'm always value reading from the PIN 0 (physical pin 5). Does anyone have try to read the ATTiny pin without the Arduino function ? I'm simply trying to do digital read here. (no analog) Here a sample code which reproduce the problem.

DDRB = 0b00001000; // set the LED pin as output.
while (1)
{

if ( PINB & 0b00000010 != 0) // read the PIN to check if the button is pressed.
{
PORTB = 0b00000000; //Turn Off the LED when the button is pressed
}
else
{
PORTB = 0b00001000;  //Turn on one LED by default
}
}
}
• Operator precedence. != comes before &. Brackets are your friend. – Tom Carpenter Apr 11 '16 at 19:49
• Damn, you are right.... If this is my only problem, I good for a triple head-bashing on the desk. And you know what is funny, I program in C++ for more than 20 years. But because it is in a context where I'm not comfortable, I immediately put the blame on the hardware ;) – Martin Tétreault Apr 11 '16 at 20:11

## 1 Answer

It all comes down to Operator precedence.

In C/C++, != is evaluated before &. As a result, your condition is effectively:

if ( PINB & (2 == 0))

Which it should be clear that this is always going to be 0 - 2 == 0 is always 0.

You have two choices:

1. Use something with a higher precedence in the if statement, for example ():

if ( (PINB & 2) != 0 )

Which will work as expected - the parenthesis are evaluated before the !=.

2. Rely on the fact that any non-zero value is considered true:

if (PINB & 2) //True is anything non-zero.

• Shame on me... yes you are right. It was as simple as this... Lesson learned, check the code twice before putting the blame on the hardware. – Martin Tétreault Apr 12 '16 at 17:36