0
0
Embedded Cprogramming~5 mins

GPIO register configuration in Embedded C

Choose your learning style9 modes available
Introduction

GPIO register configuration lets you control pins on a microcontroller to read inputs or send outputs.

Turning an LED on or off by controlling a pin
Reading a button press from a pin
Setting a pin to output a signal like PWM
Configuring pins for communication like SPI or I2C
Syntax
Embedded C
GPIOx->MODER = value;  // Set pin mode
GPIOx->OTYPER = value; // Set output type
GPIOx->OSPEEDR = value; // Set speed
GPIOx->PUPDR = value;   // Set pull-up/pull-down
GPIOx->IDR;            // Read input data
GPIOx->ODR = value;    // Write output data

GPIOx means the GPIO port like GPIOA, GPIOB, etc.

Each register controls different pin settings using bits.

Examples
This sets pin 5 of GPIOA as output by setting bits 10 and 11 in MODER register.
Embedded C
GPIOA->MODER |= (1 << 10);  // Set pin 5 as output
This configures pin 2 of GPIOB with pull-up resistor enabled.
Embedded C
GPIOB->PUPDR &= ~(3 << 4);  // Clear pull-up/down for pin 2
GPIOB->PUPDR |= (1 << 4);       // Enable pull-up for pin 2
This reads the state of pin 3 on GPIOC.
Embedded C
uint32_t input = GPIOC->IDR & (1 << 3);  // Read pin 3 input
Sample Program

This program configures pin 5 of GPIOA as output and turns an LED on and then off with a delay.

Embedded C
#include <stdint.h>
#include "stm32f4xx.h"  // Example MCU header

int main() {
    // Enable clock for GPIOA (usually done in RCC register)
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;

    // Set PA5 as output (LED pin on many boards)
    GPIOA->MODER &= ~(3 << (5 * 2));  // Clear mode bits for pin 5
    GPIOA->MODER |= (1 << (5 * 2));   // Set pin 5 as general purpose output

    // Turn LED on
    GPIOA->ODR |= (1 << 5);

    // Simple delay loop
    for (volatile int i = 0; i < 1000000; i++);

    // Turn LED off
    GPIOA->ODR &= ~(1 << 5);

    while(1) {}
    return 0;
}
OutputSuccess
Important Notes

Always enable the clock for the GPIO port before configuring it.

Each pin uses two bits in MODER to set mode: 00=input, 01=output, 10=alternate function, 11=analog.

Use bitwise operations to change only the bits you want without affecting others.

Summary

GPIO register configuration controls how pins behave on a microcontroller.

Use MODER to set pin mode, PUPDR for pull-up/down, and ODR/IDR to write/read pin states.

Remember to enable the GPIO clock before configuring pins.