Focused on Your Needs
1. Configure I/O Digital Pins
This tutorial shows how to set input and output on each pin on Atmel AVR microcontroller.
Usually there are 8 I/O pins in each port in an Atmel AVR microcontroller. These pins can be set as input or output from the Data Direction Register (DDRx), and can be set in HIGH, LOW, or tri state from Pin Output Register (PORTx).
Example 1: set PIN0 - PIN4 in PORTA to output HIGH, and PIN5-PIN7 in port A to output LOW
DDRA = 0b11111111; //Set all pins in PORTA as outputs
PORTA = 0b00011111; //Set PIN0-PIN4 to HIGH , while the rest of pins stay LOW
Alternatively, the code in Example 1 can be written as:
DDRA = 0xFF; //Set all pins in PORTA as outputs
PORTA = 0x1F; //Set PIN0-PIN4 to HIGH , while the rest of pins stay LOW
In many cases, only a specific pin needs to be changed while other pins remain the same. The code below then becomes more efficient with an OR operation.
Example 2: set PIN 4 in PORTA to output HIGH, while the rest of pins stay at the original stage
DDRA |= 0b00010000; //Set PIN4 in PORTA as an output
PORTA |= 0b00010000; //Set PIN4 in PORTA to HIGH
Alternatively, the code in Example 2 can be written as:
DDRA |= 1 << 4; //Set PIN4 in PORTA as an output
PORTA |= 1 << 4; //Set PIN4 in PORTA to HIGH
There is no direct way to set 0 to a register bit. The best way is to use NOT + AND operation.
Example 3: Set PIN4 in PORTA to input and make the pin in tri state
DDRA &= ~(1 << 4); //Set PIN4 in PORTA as an input
PORTA &= ~(1 << 4); //Set PIN4 in PORTA to tri state
When the pin is tri-stated, the internal pull-up resistor is disabled, so the pin needs to connect to an external pull-up or pull-down resistor.
Example 4: Write an if statement to do something when the input pin senses a HIGH signal
DDRA &= ~(1 << 4); //Set PIN4 in PORTA as an input
PORTA &= ~(1 << 4); //Set PIN4 in PORTA to tri state, the pin needs to connect to a pull-down resistor
if (bit_is_set (PINA, 4))
{
Do something
}
Example 5: Write an if statement to do something when the input pin senses a LOW signal
DDRA &= ~(1 << 4); //Set PIN4 in PORTA as an input
PORTA |= 1 << 4; //Set PIN4 in PORTA to HIGH or enable the pull-up
if (bit_is_clear (PINA, 4))
{
Do something
}