How to Configure GPIO Pin as Input in Embedded C
To configure a GPIO pin as input in embedded C, set the pin's direction register bit to 0 using
GPIOx->DIR &= ~(1U << PIN_NUMBER);. This configures the pin to read external signals instead of outputting voltage.Syntax
To configure a GPIO pin as input, you typically clear the corresponding bit in the direction register. This means setting the bit to 0.
GPIOx: The GPIO port (like GPIOA, GPIOB).DIR: Direction register controlling input/output.PIN_NUMBER: The pin number you want to configure.&= ~(1U << PIN_NUMBER): Clears the bit to set pin as input.
c
GPIOx->DIR &= ~(1U << PIN_NUMBER);Example
This example shows how to configure pin 5 of GPIO port A as input and then read its value.
c
#include <stdint.h> #include <stdio.h> // Simulated GPIO registers for demonstration typedef struct { uint32_t DIR; // Direction register uint32_t DATA; // Data register } GPIO_TypeDef; GPIO_TypeDef GPIOA = {0}; #define PIN_NUMBER 5 int main() { // Configure pin 5 as input (clear bit 5 in DIR) GPIOA.DIR &= ~(1U << PIN_NUMBER); // Simulate external signal: set bit 5 in DATA to 1 GPIOA.DATA |= (1U << PIN_NUMBER); // Read pin 5 value int pin_value = (GPIOA.DATA & (1U << PIN_NUMBER)) ? 1 : 0; printf("Pin %d input value: %d\n", PIN_NUMBER, pin_value); return 0; }
Output
Pin 5 input value: 1
Common Pitfalls
Common mistakes when configuring GPIO pins as input include:
- Not clearing the direction bit, leaving the pin as output.
- Forgetting to enable the GPIO clock before configuration (hardware-specific).
- Not configuring pull-up or pull-down resistors if needed, causing floating input.
- Reading the wrong data register or pin number.
c
/* Wrong: Setting pin as output instead of input */ GPIOA.DIR |= (1U << PIN_NUMBER); // This sets pin as output /* Correct: Clearing bit to set as input */ GPIOA.DIR &= ~(1U << PIN_NUMBER);
Quick Reference
Summary tips for configuring GPIO pin as input:
- Clear the pin bit in the direction register to set input.
- Enable GPIO peripheral clock before configuration.
- Configure pull-up/pull-down resistors if your hardware requires it.
- Read the input data register to get pin state.
Key Takeaways
Clear the GPIO direction bit to configure a pin as input.
Always enable the GPIO clock before configuring pins.
Use pull-up or pull-down resistors to avoid floating inputs.
Read the input data register to get the pin's current state.