How to Read GPIO Pin State in Embedded C: Simple Guide
To read a GPIO pin state in embedded C, use the
GPIO_ReadPin() function or directly access the input data register of the GPIO port. This returns the pin's current logic level as 0 (low) or 1 (high).Syntax
The typical syntax to read a GPIO pin state involves accessing the input data register or using a provided function like GPIO_ReadPin(). For example:
pin_state = GPIOx->IDR & (1 << pin_number);reads the pin state by masking the input data register.pin_state = GPIO_ReadPin(GPIOx, pin_number);uses a function to get the pin state.
Here, GPIOx is the GPIO port (like GPIOA, GPIOB), and pin_number is the pin index (0-15).
c
uint8_t pin_state = (GPIOA->IDR & (1 << 5)) ? 1 : 0;
Example
This example shows how to read the state of pin 5 on GPIO port A and print its value. It assumes the pin is configured as input.
c
#include <stdio.h> #include <stdint.h> // Mock definitions for demonstration volatile uint32_t GPIOA_IDR = 0; // Simulated input data register int main() { // Simulate pin 5 is high GPIOA_IDR = (1 << 5); // Read pin 5 state uint8_t pin_state = (GPIOA_IDR & (1 << 5)) ? 1 : 0; printf("GPIOA Pin 5 state: %d\n", pin_state); return 0; }
Output
GPIOA Pin 5 state: 1
Common Pitfalls
Common mistakes when reading GPIO pins include:
- Not configuring the pin as input before reading.
- Reading the wrong port or pin number.
- Not masking the input data register correctly, leading to wrong values.
- Assuming the pin state is stable without debouncing for mechanical switches.
Always ensure the pin is set as input and use proper bit masking.
c
/* Wrong way: reading without masking */ uint8_t pin_state_wrong = GPIOA->IDR; // May contain other pins' states /* Right way: mask the specific pin */ uint8_t pin_state_right = (GPIOA->IDR & (1 << 5)) ? 1 : 0;
Quick Reference
| Concept | Description | Example |
|---|---|---|
| GPIO Port | The hardware port group (e.g., GPIOA, GPIOB) | GPIOA |
| Pin Number | Pin index within the port (0-15) | 5 |
| Input Data Register (IDR) | Register holding current pin states | GPIOA->IDR |
| Bit Masking | Use bit shift to isolate pin state | (1 << 5) |
| Reading Pin | Check if pin bit is set (1) or cleared (0) | (GPIOA->IDR & (1 << 5)) ? 1 : 0 |
Key Takeaways
Always configure the GPIO pin as input before reading its state.
Use bit masking to isolate the specific pin's state from the input data register.
Reading the entire input register without masking can cause incorrect results.
Pin state returns 1 for high voltage and 0 for low voltage.
Debounce mechanical inputs to avoid unstable readings.