Digital Inputs/Outputs

All the buses on an AVR are both readable and writable, if they are used in the default logical input/output (I/O) mode. AVR buses are named as letters from the beginning of the Latin alphabet: A, B, C etc. Some AVRs might not have bus A, though, if bus B exists. Each bus is 8-bit and each bit usually has its own pin on the controller. Pins are counted with numbers starting from zero. For both directions on the bus, there are two separate registers. In addition, there is a register to decide the real direction of the bus, where a bit value of 1 marks the bus as output and 0 as input. Altogether, each bus has three registers:

• PORT - for setting the output value of the bus.
• PIN - for reading the input on the bus.
• DDR - for setting the direction of the bus.

Example

Task: make pins 0-3 on bus B inputs, pins 4-7 outputs, set pin 5 high and read the values of pins 0-3 to a variable. The C code for it looks like this:

```#include <avr/io.h>

int main()
{
unsigned char x;

// Pins 0-3 as inputs, 4-7 as outputs
DDRB = 0xF0;

// Set pin five as high
PORTB |= (1 << PIN5);

// Read the values from inputs 0-3
x = PINB & 0x0F;
}```

In this example, the inputs are used in Hi-Z (high impedance) mode. In essence, the input does not put virtually any load on the source of the signal. This mode might be necessary, if the pin is used as a data bus. It is wise to use a pull-up resistor on the input, if the pin is used for a button, a switch or any other solution, where the input is connected to ground. For that, the output bit of the corresponding pin must be set high in the input mode - as a result, a resistor is placed between the supply voltage and the input, which keeps the input voltage high unless it is being pulled down by something. The goal of a pull-up resistor is to prevent floating of the input due to static electricity and other interferences. After booting the controller, all IO buses are in the high impedance input mode by default.

Usually, the pins on the IO bus are also used for other peripherals, aside from the logical connections. If there is a need to use the alternate function of the pin, the appropriate IO pin mode can be found in the AVR's datasheet. For example to use an ADC channel as an input, the pin should be in input mode and to generate PWM signal, it should be in output mode. On the other hand, some peripheral modules select the IO pin mode by themselves.