Skip to main content

Subsection 2.1.1 Reading a Pin: The Input Data Register

When a GPIO pin is configured as an input, the STM32C031C6 continuously samples the voltage present on that pin and reflects it in the Input Data Register (IDR). Like the ODR (Output Data Register), which we used in the previous chapter to drive pins, the IDR is a 16-bit register, one bit per pin in the port. Bit 13 of GPIOC->IDR, for example, reflects the current voltage on PC13, which is where the Nucleo board’s blue user button is connected. If the pin is at 3.3 V, the bit reads 1; if it is at 0 V, the bit reads 0.
The sampling is not done with a plain comparator. The voltage on the pin goes through a Schmitt trigger, a comparator with two thresholds instead of one, and its output is what the input data register holds. Configuring the pin as an input is what turns the Schmitt trigger on; it also disables the pin’s output buffer, and it activates whichever of the internal pull-up and pull-down resistors GPIOx->PUPDR selects. From then on the level on the pin is sampled into the input data register on every clock cycle of the internal bus, and reading GPIOx->IDR gives you the most recent sample.
The Schmitt trigger does not compare the pin voltage against a single threshold. It has two. Any voltage below \(V_{\mathrm{IL}}\) (the maximum low input voltage, roughly \(0.3 \times V_{\mathrm{DD}}\text{,}\) where \(V_{\mathrm{DD}}\) is the supply voltage, 3.3 V on the Nucleo, so about 1.0 V) is reliably read as logic 0, and any voltage above \(V_{\mathrm{IH}}\) (the minimum high input voltage, roughly \(0.7 \times V_{\mathrm{DD}} \approx 2.3\text{ V}\)) is reliably read as logic 1. In between, the output does not float: the Schmitt trigger holds whatever it last settled on, so a rising voltage is certain to read 1 once it passes \(V_{\mathrm{IH}}\text{,}\) and a falling one is certain to read 0 once it drops below \(V_{\mathrm{IL}}\text{.}\) The Schmitt trigger’s actual switching points lie between these two guaranteed levels, about 200 mV apart, and that separation is called hysteresis. It is what makes a slow or slightly noisy edge produce one clean transition rather than several.
In normal digital circuits, where signals are driven cleanly to ground or the supply rail, you stay well outside this zone and never notice it. It becomes important when signals are slow to transition, for example a slowly rising voltage from a large RC filter, or when there is significant noise on a line.
Reading a button in code is therefore straightforward, as long as the pin voltage is always driven firmly to one rail or the other. What makes a button awkward is not the reading. It is that while the button is open, nothing is driving the pin at all, and that is the subject of the next subsection.