When working with microcontrollers, one of the most fundamental tasks you’ll perform is controlling GPIO (General Purpose Input/Output) pins. Whether you’re blinking LEDs, reading button presses, or talking to sensors, GPIOs are your entry point into the world of hardware control.

Let’s break it down simply.


🧠 What is a GPIO?

A GPIO pin is a programmable pin on your microcontroller that can act as:

  • Input: To receive signals (e.g., from a button or sensor)
  • Output: To send signals (e.g., to turn on an LED or motor)

You decide the direction using software!


⚙️ GPIO as Output

Let’s say you want to light an LED. You configure the GPIO pin as an output and set it HIGH (voltage applied).

Example (Arduino style):

pinMode(13, OUTPUT);    // Set pin 13 as output
digitalWrite(13, HIGH); // Turn the LED on

Bare-metal C (simplified):

#define GPIO_DIR_REG   (*((volatile uint32_t*)0x400FF054))
#define GPIO_OUT_REG   (*((volatile uint32_t*)0x400FF040))
GPIO_DIR_REG |= (1 << 5);     // Set Pin 5 as Output
GPIO_OUT_REG |= (1 << 5);     // Set Pin 5 High

🔌 GPIO as Input

Now suppose you want to read a button. You’ll configure the pin as input, then read its state.

Example:

pinMode(7, INPUT);         // Configure as input
int value = digitalRead(7); // Read value (HIGH/LOW)

But here’s a twist: floating pins.


⚡ Why You Need Pull-Ups (or Pull-Downs)

When a pin is configured as input and nothing is connected, its state is undefined (floating)—it could randomly read HIGH or LOW. To fix that, we use pull-up or pull-down resistors to set a default state.

Internal Pull-Up:

Most microcontrollers let you enable an internal pull-up.

pinMode(7, INPUT_PULLUP); // Enables internal pull-up resistor

This pulls the pin HIGH by default. Now, pressing a button connected to GND will give you a LOW reading when pressed.


📊 Quick Summary

ModePurposeCode Example
OutputControl LED/MotordigitalWrite(pin, HIGH)
InputRead button/sensordigitalRead(pin)
Input Pull-UpSet default HIGHINPUT_PULLUP

🧪 Try It Yourself: Button + LED

Goal: Light up an LED when a button is pressed.

void setup() {
  pinMode(2, INPUT_PULLUP); // Button
  pinMode(13, OUTPUT);      // LED
}
void loop() {
  int buttonState = digitalRead(2);
  if (buttonState == LOW) {
    digitalWrite(13, HIGH); // Button pressed
  } else {
    digitalWrite(13, LOW);  // Button released
  }
}

🛠️ Real-World Use

GPIOs are used to:

  • Toggle relays and actuators
  • Communicate with sensors (through digital lines)
  • Detect state changes (interrupts)
  • Control backlights, buzzers, displays

LEAVE A REPLY

Please enter your comment!
Please enter your name here