In this lesson, you will learn how to capture the current electrical state of a physical microcontroller pin by accessing the peripheral’s input data register.
The Concept of Input Sampling
In previous lessons, we configured GPIO pins as outputs to drive LEDs. Now, we reverse the flow of information. When a GPIO pin is configured as an input, the microcontroller hardware continuously samples the voltage level on that pin. If the voltage is near the logic-high threshold (e.g., 3.3V), the hardware sets a specific bit in the Input Data Register to 1. If the voltage is near ground (0V), it sets that bit to 0.
Unlike output registers, which you can read back to see what you previously wrote, the input data register is a "live" window into the electrical state of the physical pins.
Accessing the Register
To read the state, you must perform a direct memory access to the register address mapped to that specific GPIO port. Since these registers are often 32 bits wide, representing 32 individual pins, you use bitwise operations to isolate the specific pin you are interested in.
Suppose you have a structure mapped to your GPIO peripheral, and you want to read Pin 5:
// Assume GPIO_PORTA is the base address of the register block
// IDR is the Input Data Register offset
uint32_t pin_state = (GPIO_PORTA->IDR & (1 << 5));
if (pin_state != 0) {
// The voltage on Pin 5 is High (Logic 1)
} else {
// The voltage on Pin 5 is Low (Logic 0)
}
Why Bitwise Masking Matters
Because the register contains the status of all 32 pins at once, reading the raw value of the register returns a large number representing every pin's state. By applying the mask (1 << 5), we perform a bitwise AND. This clears every bit in the result except for the bit at position 5. If the resulting value is non-zero, it confirms that bit 5 is currently high.
Remember: hardware registers are volatile. Always ensure your pointer access reflects the volatile nature of the register to prevent the compiler from caching the value during polling loops.
Key Takeaway: The Input Data Register provides a real-time snapshot of pin voltage levels, which must be extracted using bitwise masking to isolate individual pin states.