Electronics · Optional embedded electronics and a sensor logger
GPIO, timing and dependable button events
A program that counts six presses when a button was pressed once may be faithfully reporting its raw input. Dependable behaviour needs an electrical input contract and a timing rule, not just a line of code that reads a pin.
Lesson preparation and course links
Use the circuit and analogue-signal chapters. Keep voltage levels, timing and measurement uncertainty with every digital or sampled-data claim.
Back to the Electronics chapterAfter reading, you can
Relate software pin states to electrical limits, schedule work with elapsed time, and derive one accepted event from a bouncing input.
A digital pin is an electrical connection
A general-purpose input/output pin, or GPIO, connects a microcontroller’s internal logic to a physical terminal. Input mode observes a pin voltage; output mode drives a voltage through transistors inside the chip. The software words high and low therefore describe electrical conditions, rather than abstract numbers with unlimited voltage or current. A pin that reads a switch is doing a different job from a pin supplying an indicator.
Start with a pin contract: the allowed supply voltage, guaranteed input thresholds, output voltages at stated load currents, leakage, startup state and absolute maximum limits. Guaranteed thresholds define regions that must be recognized as low or high. A voltage between them is not a third valid data value; its interpretation is unspecified for that input. A maximum stress rating also does not promise correct operation at that stress.
Check levels and loading together
Consider a fictional 3.3 V input whose contract guarantees low at or below 0.8 V and high at or above 2.0 V. An output guaranteed to remain at least 2.7 V under the intended load has a high-level margin of 2.7 − 2.0 = 0.7 V before other disturbances are included. These are assumed example limits, not universal microcontroller numbers. Repeat the comparison for the low state and for every relevant supply and temperature condition.
A pull-up resistor weakly connects an input to its supply so that an open switch does not leave the voltage uncontrolled. With a 10 kΩ pull-up at 3.3 V, an ideal closed switch to the return draws 0.33 mA. Real input leakage, switch resistance and capacitance change both settled voltage and response time. Pin current, total port current and total device current are separate constraints; meeting one does not establish the others.
Define what happens before the program is ready
Pin function, direction, output value and pull resistor are distinct settings. A terminal may initially belong to a debug interface, remain an input or have a device-specific pull enabled. Read the exact device documentation instead of assuming that a variable’s initial value establishes a physical pin voltage. An externally driven pin must also remain within its allowed conditions when the microcontroller is unpowered.
For an output that must begin inactive, establish a deliberate startup sequence and verify the pin through reset and configuration. For an input, select a defined idle level and specify which transition means an action. An interrupt is a mechanism that asks the processor to handle an event; it does not make a bouncing or electrically invalid signal reliable. Keep interrupt work short and transfer longer decisions to a clear state machine.
Use elapsed time without stopping other work
A timer counts events from a clock and supplies a time reference. A nonblocking program records when something happened and checks whether its required interval has elapsed, while continuing to service other work. In contrast, a blocking delay postpones the calling task and can prevent it from observing events. Neither approach removes timer-clock error, interrupt latency or variation in when software actually runs.
Suppose the program examines a switch every 1 ms. Record the observed sampling interval as well as its intended value. A late task should have a defined policy: skip obsolete observations, report an overrun, or process buffered observations with their actual timestamps. Repeating a task by adding its period to the previous scheduled deadline can avoid cumulative drift, but it does not recover information that was never sampled.
Accept a stable state, not every contact edge
Mechanical contacts can make several brief connections while settling. Debouncing turns that raw activity into one accepted logical state. In an elapsed-time method, keep an accepted state, a candidate state and the time when that candidate was first observed. Whenever a sample differs from the candidate, replace the candidate and restart its timer. Accept it only when it has remained the candidate for the chosen interval.
Choose the interval from observed switch behaviour and the required response, rather than treating 10 ms as a law. For our teaching example, require 10 ms of unchanged sampled candidate state. Ten consecutive samples 1 ms apart span only 9 ms, so counting samples without defining the timing rule can create an off-by-one error. Debounce the release as well as the press when both events matter. Hardware filtering or peripherals are alternatives, with their own thresholds and timing limits.
Separate state, event and response time
An accepted state says that the input is currently pressed. A press event says that it changed from accepted released to accepted pressed. Generate that event once at the transition; do not generate it on every later sample that still reads pressed. Other tasks can then consume the event while the debounce state continues to be maintained.
A sampled filter cannot prove what happened between samples. A pulse shorter than the sampling interval can be missed, and repeated interference synchronized to the samples can imitate a stable level. If a narrow pulse must be detected or an action has safety consequences, select hardware capture, a qualified input stage and a suitable system design. For an ordinary human-operated teaching switch, test recorded press and release sequences, startup, long holds, rapid repeated actions and deliberately delayed tasks.
Work a ten-millisecond acceptance window
Sample every 1 ms. The raw sample first reads pressed at 2 ms, released at 3 ms, pressed at 4 ms, released at 5 ms and pressed at 6 ms; it remains pressed afterward. Each change restarts the candidate timer. Its final start is therefore 6 ms.
At 15 ms the candidate has lasted only 9 ms and is not accepted. At 16 ms it has lasted 10 ms, so accepted state changes to pressed and one press event is emitted. If physical bouncing ended at 5.7 ms, this particular acceptance occurs 10.3 ms later. A different sampling phase changes that latency; the observed 10 ms rule applies to sampled candidate history, not continuous observation.
The independent electrical check is I = 3.3 V/10 kΩ = 0.33 mA through the closed ideal pull-up path, with resistor power P = 3.3 × 0.00033 = 1.089 mW. Timing correctness does not replace this load check.
Try the reasoning
A fictional output guarantees at least 2.7 V under load, while the receiving input requires at least 2.0 V for high. What is the nominal guaranteed high-level margin before other disturbances?
Show the answer and reasoning
Subtract the receiver requirement from the guaranteed output: 2.7 − 2.0 = 0.7 V. Supply variation, ground differences and noise must still fit within an appropriate complete interface budget.
Why do ten unchanged samples taken 1 ms apart not automatically prove a 10 ms duration?
Show the answer and reasoning
There are nine intervals between ten samples, so the first-to-last span is 9 ms. An elapsed-time rule needs a timestamp and a comparison against 10 ms, or a sample-count rule that is explicitly derived from the desired span.
The accepted input remains pressed for a second. Should a press event be emitted every millisecond?
Show the answer and reasoning
No. State and event are different. Emit the press event when the accepted state changes from released to pressed; a continued hold preserves the state without creating another transition.
Does reading an input in an interrupt eliminate the need for debouncing?
Show the answer and reasoning
No. Interrupts can respond to each electrical edge, including bounce. The input still needs defined electrical conditions and a filter or state machine appropriate to the event requirements.
A one-millisecond polling loop must detect a 100 µs pulse. What is missing from that design?
Show the answer and reasoning
The pulse can occur entirely between observations. A guaranteed detection requirement needs a suitable capture peripheral, latch or faster qualified observation path, plus explicit pulse-width and timing specifications.
What to carry forward
A pin contract establishes valid electrical states; a time rule establishes when an observed state is accepted; a state transition establishes when an event occurs.
References
Sources supporting this lesson’s explanations and examples.