digitalRead()

Reading the input state of a pin is a key part of many programs and is much simpler on an AVR, in fact you don’t even have to do anything! The PINX register automatically updates to reflect the digital state of the pin and can be referenced anywhere in your program. Below we will take a look at how to reference the registar to provide a 1 or 0 value for each pin.

First set the pin to an input as shown in the pinMode() tutorial.

To isolate the bit we are after we again use a bit mask and the bitwise AND operator as shown below. This line can be referenced as the condition of an IF statement or used to assign the pin state to a variable.

PINB & (1<<PINB7)

A the sum of the AND operation is shown below for both cases.

     0b10000000                 0b10000000
AND  0b10000000            AND  0b00000000
---------------            ---------------
     0b10000000 (TRUE)          0b00000000 (FALSE)

To create a variable, var, that stores an int reflecting the state of pin 7 of port b the following code can be used.

int var = PINB & (1<<PINB7);

The integer ‘var’ can now be used to reference the input state of pin B7. Note that this variable wont update automatically like register.

The Xplained board used throughout these tutorials includes a user button in a pulldown configuration. In this situation pressing the button pulls the signal low and so prefixing the reference with a ‘!’ will create a TRUE value on a button press.