AVR – Thorough Explanation of DDRx, PORTx, and PINx


Okay this might be a really dumb question, but I don't really get these 3,
my main confusion is, why we need three of them? Why can't we r/w on port like normal register? (please don't downvote).
And also from searching around the web, someone mentions about pullups resistor, and now I'm super confused…

Best Answer

They chose to group he control bits in registers by function. They only need three control bits per pin. Using one register per pin is wasteful, and with 8 pins per port, you would need 24 bits of control state, which is 3 registers worth, anyway. They cram that into two registers by contextualizing the meaning of PORT bits. Grouping it differently could also make for some ugly low- level software.

The bits directly support the data path for an I/O pin. The DDR is the data direction register.

If a DDR bit is high, the pin is configured as an output, and the value of the corresponding PORT bit sets the value of the pin HIGH or LOW.

If a DDR bit is low, the pin is configured as an input, and if the corresponding PORT bit is set, an internal pull-up resistor is enabled, otherwise the pin is floating subject to external circuits. In any case, the corresponding PIN bit reflects the logic state of the pin, HIGH or LOW.

If you read enough avr-gcc code, you see a lot of use if the _BV macro to construct bit masks, which can be a useful way to manipulate an entire 8-bit port with of state in one instruction for parallel functionality.

Update to request for clarification For each pin, you have to encode the following control state in AVR8 architecture.

  • whether the pin is configured as input or output
  • for input, whether the internal pull-up resistor is enabled or not.
  • for output, what value should be driven to the pin
  • for input, what binary value is on the pin

There is no way to encode all that information in one bit per pin. They already compress some of that state by contextualizing the meaning of ther PORT bits based on corresponding DDR bits.

Could it be encoded differently? Sure, but the architecture is what it is in hardware. You have to look at the I/O pin block diagram in the datasheet to fully understand. Doing so, it should be clear how these control bits for each pin influence the datapath.

PIN bits are not really a control bits. Together, three control states are encoded by two bits per pin between DDR and PORT registers.