GPIO
🚀 Practice real-world tasks & problems for GPIO to build pro-level skills — Click here
GPIO
- General-Purpose Input Output (GPIO) used for INPUT and OUTPUT.
- GPIO INPUT → switch, buttons, keypad.
- GPIO OUTPUT → LED, Relay, 7-segment display.
GPIO Registers
Generally, in controllers (AVR, PIC) following types of GPIO registers are present.
Considering the AVR controller
Register | Purpose |
---|---|
DDRx | Configures pin direction (1 = output, 0 = input) |
PORTx | Sets pin output level OR enables internal pull-up |
PINx | Reads the voltage level on input pins (5V = logic 1, 0V = logic 0) |
where x = port number (eg B,C,D)
NOTE: ARM and RISC based 32-bit controllers have more add-on registers (e.g. PIN-func0tion-selection register, pullup-configuration register, etc).
DDRx | PORTx | STATE |
---|---|---|
0 | 0 | INPUT HIGH-IMPEDANCE (floating) |
0 | 1 | INPUT PULLUP |
1 | 0 | OUTPUT LOW (0V) |
1 | 1 | OUTPUT HIGH (5V) |
INPUT HIGH IMPEDANCE (Hi-Z)
It's like an open circuit — the pin 'floats' and its voltage can randomly vary due to electrical noise, making it unreliable unless we connect external voltage to it.
Connecting switch
Without internal PULLUP & PULLDOWN
Source & Sink current
- Source: The current flows from the GPIO pin to the load. (e.g. GPIO HIGH powering an LED).
- Sink: The current flows from the load into the GPIO pin (which acts like ground). (e.g. LED cathode (- ve) connected to GPIO).
Max Limits: Each microcontroller has max source/sink current capacity per pin. Exceeding it can damage the pin or controller.
E.g. – ATmega328 has a max GPIO source / sink current limit of 40 mA. Although it is recommended to keep it minimum (< 20 mA).
GPIO Port’s current limit:
Controller’s PORT also has its own limits for source/sink current.
E.g., AVR ATmega328 PORTC has a max sink current limit of 100 mA. As it has only
3 PORTs, the max source/sink current it can handle is up to 300 mA.
GPIO Internal Resistance
Controller's GPIO has some internal resistance e.g. ~25Ω for AVR ATmega328.
So when OUTPUT is HIGH and current flows it drops the GPIO voltage.
GPIO current | Internal voltage drop (approx) | GPIO voltage (approx) |
---|---|---|
0 mA | 0 mV | 5V |
10 mA | 250 mV | 4.750 V |
20 mA | 500 mV | 4.5 V |
40 mA | 1 V | 4 V |
GPIO cautions
GPIO Short circuit Scenarios:
GPIO Source Sink cautions (AVR ATmega328p)
How a Controller Decides HIGH or LOW on GPIO Input
Most of the controllers have a similar range as above.
Arduino
Functions
Function | Description |
---|---|
pinMode(pin, mode) | Sets a pin as INPUT, OUTPUT, or INPUT_PULLUP |
digitalWrite(pin, val) | Sends HIGH or LOW to a digital output pin |
digitalRead(pin) | Reads HIGH or LOW from a digital input pin |
Blinking an LED
| Control LED with a Switch
|