Index

Port Registers
The ATmega 328 has 3 sets of registers of controlling the I/O pins. These are called port B, port C and port D. Each port is associated with 3 registers called DDRx, PORTx and PINx, where x is either B, C, or D. The bits in the DDRx registers are used to set individual pins controlled by the corresponding port to be either inputs (bit = 0) or outputs (bit = 1). If a pin is set to be an output, writing to the corresponding bit in the PORTx register will set its value. reading from a PORTx register will return the value last written to it independently of which bits have been set to outputs or inputs, i.e. if a pin is set to be an input, reading PORTx will not be affected by the actual state of the pin. To read the state of any pins set to be inputs, the PINx register must be used.
Bits in port registers map onto pins as follows.
Port B
bit 0 | bit 1 | bit 2 | bit 3 | bit 4 | bit 5 | bit 6 | bit 7 |
---|---|---|---|---|---|---|---|
D8 | D9 | D10 | D11 | D12 | D13 | N/A | N/A |
Port C
bit 0 | bit 1 | bit 2 | bit 3 | bit 4 | bit 5 | bit 6 | bit 7 |
---|---|---|---|---|---|---|---|
A0 | A1 | A2 | A3 | A4 | A5 | N/A | N/A |
Port D
bit 0 | bit 1 | bit 2 | bit 3 | bit 4 | bit 5 | bit 6 | bit 7 |
---|---|---|---|---|---|---|---|
Rx | Tx | D2 | D3 | D4 | D5 | D6 | D7 |
Examples
void set_port_c(byte value)
{
DDRC = DDRC | 0b00111111; // set all pins to be outputs;
PORTC = PORTC | (value & 0b00111111); // ouput lower 6 bits of value on all 6 pins;
}
byte read_port_c()
{
DDRC = DDRC & ~0b00111111; // set all pins to be inputs;
return PINC & 0b00111111; // return lower 6 bits of port data;
}
{
DDRC = DDRC | 0b00111111; // set all pins to be outputs;
PORTC = PORTC | (value & 0b00111111); // ouput lower 6 bits of value on all 6 pins;
}
byte read_port_c()
{
DDRC = DDRC & ~0b00111111; // set all pins to be inputs;
return PINC & 0b00111111; // return lower 6 bits of port data;
}