MEAM.Design - ATmega32 Programming - I/O Ports (GPIO)


The ATmega32u4 has many GPIO pins spread across ports B, C, D, and F. The accessible pins depend on the board layout. All of the pins are true read-modify-write, have selectable internal pull-up resistors, and include protection diodes to Vcc and ground (thankfully!).


To configure and use a port pin:

You'll need to read and/or modify three registers (replace the x with the appropriate port letter - B, C, D, or F):

DDRx - The "Data Direction Register" - clearing a bit will configure that pin to input, while setting a bit will configure the pin for output
PORTx - The "Data Register" - If the corresponding bit in DDRx is set, then clearing the PORTx bit will take the output low, while setting the PORTx bit will take the output high. On the other hand, if the corresponding bit in DDRx is cleared, then clearing the PORTx bit will disable the internal pull-up resistor, while setting the PORTx bit will enable the internal pull-up resistor.
PINx - The "Port Input Pins" - This register represents the state of pins configured as inputs, and can be read using the bit_is_set(PINx, BIT) or bit_is_clear(PINx, BIT) routine found in the AVR distribution include/avr/sfr_defs.h automatically included via <avr/io.h>.


Important Notes (Please Read!):

All of the I/O pins are multiplexed with other features and the behavior could be overridden by one of a number of subsystems (timer, ADC, SPI, etc.) when they are enabled.
There are CURRENT LIMITS!. It is important that you do not try to sink or source more than 40mA per pin, no more than 100mA for a single port, and no more than 200mA for the whole board. If you're lucky, it will fry just the pin. If you're unlucky, it will fry the whole board. Check your circuit requirements, and use MOSFETs if you need to supply more current to your load!
All of the I/O register pointers are pre-defined, and a set of macros have been defined in m_general.h, MEAM_general.h or teensy_general.h (latest version available here) for you to easily manipulate and check individual bits.