AVR C

These pins are usually organized in groups of eight and referred to as a port. The AVR uses the alphabet to name these ports, for example: PortA, PortB, etc. The pins of PortA are referred to as PA0 - PA7.

All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other.

Each port consists of three registers:

  • DDRx – Data Direction Register
  • PORTx – Pin Output Register
  • PINx – Pin Input Register

where x = Port Name (A, B, C or D).

DDRx

The DDxn bits in the DDRx Register select the direction of this pin. If DDxn is written to '1', Pxn is configured as an output pin. If DDxn is written to '0', Pxn is configured as an input pin.

PORTx

The PORTxn bits in the PORTx register have two functions. They can control the output state of a pin and the setup of an input pin.

As an Output: If a '1' is written to the bit when the pin is configured as an output pin, the port pin is driven high. If a ‘0’ is written to the bit when the pin is configured as an output pin, the port pin is driven low.

As an Input: If a '1' is written to the bit when the pin is configured as an input pin, the pull-up resistor is activated. If a ‘0’ is written to the bit when the pin is configured as an input pin, the port pin is tri-stated.

PINx

The PINxn bits in the PINx register are used to read data from port pin.

When the PORTx register disables the pull-up resistor the input will be tri-stated, leaving the pin left floating. When left in this state, even a small static charge present on surrounding objects can change the logic state of the pin. If you try to read the corresponding bit in the pin register, its state cannot be predicted.

Examples

All PORTA pins set as inputs with pull-ups enabled and then read data from PORTA:

DDRA = 0x00;  // make PORTA all inputs
PORTA = 0xFF; // enable all pull-ups
data = PINA;  // read PORTA pins into variable data

PORTB set to tri-state inputs:

DDRB  = 0x00; // make PORTB all inputs
PORTB = 0x00; // disable pull-ups and make all pins tri-state

PORTA lower nybble set as outputs, higher nybble as inputs with pull-ups enabled:

DDRA  = 0x0F; // lower pins output, higher pins input
PORTA = 0xF0; // output pins set to 0, input pins enable pull-ups

PWM

PWM