Digital logic for firmware engineers
Logic levels, gates, flip-flops, setup and hold, and timing diagrams.
Ones and zeros are voltages
Inside a chip, a bit is a voltage. A logic family defines which voltages count as 0 and 1, with a gap between them so noise does not flip a bit:
| Threshold (typical 3.3 V CMOS) | Meaning |
|---|---|
V_IL ≈ 0.3 × VDD ≈ 1.0 V | An input below this is guaranteed to read 0 |
V_IH ≈ 0.7 × VDD ≈ 2.3 V | An input above this is guaranteed to read 1 |
V_OL < 0.4 V, V_OH > 2.9 V | What an output guarantees at its rated current |
Between V_IL and V_IH the input is undefined. Noise margin is the gap between what an output guarantees and what an input needs. This is why a 3.3 V output may not reliably drive a 5 V CMOS input (V_IH at 5 V ≈ 3.5 V), and why a slowly rising signal through the undefined region can make an input toggle several times unless it has Schmitt-trigger hysteresis (different thresholds for rising and falling edges).
Combinational logic: gates
| Gate | Output is 1 when | C operator |
|---|---|---|
| AND | All inputs are 1 | & |
| OR | Any input is 1 | | |
| NOT | The input is 0 | ~ (bitwise), ! (logical) |
| XOR | The inputs differ | ^ |
| NAND, NOR | Inverted AND, OR | ~(a & b), ~(a | b) |
NAND and NOR are each universal: any logic function can be built from one of them alone, and CMOS implements them most cheaply. The bit-manipulation lessons are these gates applied 32 bits at a time.
Useful identities (De Morgan's laws), which also simplify C conditions:
NOT (A AND B) = (NOT A) OR (NOT B) !(a && b) == (!a || !b)
NOT (A OR B) = (NOT A) AND (NOT B) !(a || b) == (!a && !b)
Building arithmetic from gates
A half adder adds two bits: sum = A XOR B, carry = A AND B. A full adder adds a carry in as well. Chaining 32 full adders gives a 32-bit adder; the carry rippling through them is why real CPUs use faster carry-lookahead designs.
#include <stdio.h>
#include <stdint.h>
/* An 8-bit ripple-carry adder built only from AND, OR and XOR on single bits. */
static uint8_t add8(uint8_t a, uint8_t b, int *carry_out) {
uint8_t sum = 0;
int carry = 0;
for (int i = 0; i < 8; i++) {
int x = (a >> i) & 1, y = (b >> i) & 1;
int s = x ^ y ^ carry; /* full adder: sum bit */
carry = (x & y) | (carry & (x ^ y)); /* full adder: carry out */
sum |= (uint8_t)(s << i);
}
*carry_out = carry;
return sum;
}
int main(void) {
int c;
uint8_t r = add8(100, 27, &c);
printf("100 + 27 = %u, carry %d\n", r, c);
r = add8(200, 100, &c);
printf("200 + 100 = %u, carry %d (300 does not fit in 8 bits)\n", r, c);
return 0;
}
That carry out is exactly the C flag the CPU sets, and why unsigned arithmetic wraps.
Other combinational building blocks: multiplexers (select one of N inputs: the pin-mux selecting a peripheral for a GPIO is one), decoders (one of N outputs active: chip-select generation), comparators.
Sequential logic: memory
Combinational outputs depend only on current inputs. Sequential logic also remembers.
- A latch is transparent while its enable is active, and holds its value when it goes inactive.
- A D flip-flop captures its D input only at a clock edge and holds it until the next edge. Registers, counters and state machines in hardware are built from flip-flops.
Setup and hold time
A flip-flop only captures reliably if D is stable for a setup time before the clock edge and a hold time after it. Violate them and the flip-flop can become metastable: its output hovers between 0 and 1 for an unpredictable time before settling either way.
This matters to firmware engineers in two places:
- Asynchronous inputs (a button, a signal from another clock domain) must pass through a synchroniser, usually two flip-flops in series, before being used. MCU GPIO inputs already include one, which is why an input pin's value is delayed by a couple of clock cycles.
- Bus timing in datasheets (SPI, parallel buses, external memory) is specified as setup and hold times relative to clock edges. Violating them causes intermittent bit errors that depend on temperature and board.
Counters and timers
A chain of flip-flops wired to count is a counter. Every hardware timer peripheral is a counter with comparators attached, and a prescaler is a counter whose overflow clocks the next one.
Finite state machines in hardware
A register holding the state, plus combinational logic computing the next state and the outputs: exactly the Moore and Mealy machines from the state-machine lessons, which is where those terms come from.
Reading a timing diagram
Datasheets describe interfaces with timing diagrams: signals drawn against time, with parameters such as t_SU (setup), t_H (hold), t_CO (clock-to-output delay) and t_PD (propagation delay). To check an interface:
- Find the clock edge on which the receiver samples.
- Check data from the transmitter is stable from
t_SUbefore that edge tot_Hafter it, using the transmitter's worst-case output delay and the receiver's worst-case requirements. - The margin left is your tolerance for trace delays, clock skew and temperature.
#include <stdio.h>
int main(void) {
/* SPI at 20 MHz: does the peripheral's data arrive in time for the MCU to sample it? */
double period_ns = 1000.0 / 20.0; /* 50 ns */
double half = period_ns / 2; /* data launched on one edge, sampled half a period later */
double t_co_max = 12.0; /* peripheral: clock to data out, worst case */
double trace_ns = 2.0; /* board delay, round trip for the clock and data */
double t_su_mcu = 6.0; /* MCU input setup requirement */
double slack = half - (t_co_max + trace_ns) - t_su_mcu;
printf("setup slack at 20 MHz: %.1f ns %s\n", slack, slack > 0 ? "(meets timing)" : "(FAILS)");
half = (1000.0 / 40.0) / 2;
slack = half - (t_co_max + trace_ns) - t_su_mcu;
printf("setup slack at 40 MHz: %.1f ns %s\n", slack, slack > 0 ? "(meets timing)" : "(FAILS)");
return 0;
}
This is exactly the calculation behind "the SPI works at 20 MHz but not at 40".
Programmable logic
When software is too slow or too jittery, logic can be implemented in hardware: CPLDs and FPGAs contain configurable gates and flip-flops described in a hardware description language (Verilog, VHDL). Many MCUs also include small programmable blocks (configurable logic cells, PIO state machines on the RP2040) for custom timing-critical interfaces.
Pitfall: Reading an input that is changing at the moment of sampling gives an unpredictable result. Firmware sampling an external signal from another clock domain (an encoder, a sync pulse) should read it twice or use a hardware capture feature.
Interview question: What is metastability and how is it handled?
Answer: When a flip-flop's input changes within its setup and hold window, the output can stay at an intermediate voltage for an unpredictable time before settling to 0 or 1. If downstream logic samples it in that state, different parts may see different values. It is handled by passing signals that cross clock domains, or come from outside, through a synchroniser of two (or more) flip-flops clocked by the receiving domain, giving the first flip-flop a full clock period to settle. The probability of failure falls exponentially with the settling time allowed.
Interview question: Why might a 3.3 V microcontroller fail to drive a 5 V logic input reliably?
Answer: A 5 V CMOS input typically needs at least 0.7 × VDD, about 3.5 V, to guarantee a logic 1, and a 3.3 V output cannot reach that, so the input sits in its undefined region. TTL-level inputs (V_IH about 2 V) work, as do 5 V parts with "TTL-compatible" or 3.3 V-tolerant inputs. Otherwise use a level shifter. The reverse direction, 5 V into a 3.3 V pin, needs the pin to be 5 V tolerant or a divider or level shifter.
Build it: will a 3.3 V chip drive a 5 V chip?
This is step 2 of the module project. The power bank's 3.3 V microcontroller must switch the 5 V USB boost converter on through its enable pin, and drive a 5 V shift register for the LEDs. Whether a "high" from one chip counts as "high" at the other is decided by four numbers in their datasheets.
Lab: Logic level compatibility and noise margins
A driver guarantees its output is at least VOH when high and at most VOL when low. A receiver reads anything at or above VIH as high and anything at or below VIL as low. All in millivolts.
noise_margin_high(drv, rcv)returnsVOH - VIH, andnoise_margin_low(drv, rcv)returnsVIL - VOL(both may be negative, so use signed integers).compatible(drv, rcv)returns true when both margins are at least 400 mV (the design rule here, for noise on a long board).verdict(drv, rcv)prints one line:ok (high margin X mV, low margin Y mV), orNOT ok (...)with the same numbers.
Going deeper
Interview question: How would you combine a garage door opener's remote, wall button and safety beam into a safe decision?
Answer: Treat the safety beam as an interlock: closing is allowed only while the beam is clear, and a break during closing reverses the door at once, preferably in hardware as well as firmware. The remote and wall button are just requests to a state machine. Debounce the inputs, and verify every combination of inputs and states.
Interview question: What is the difference between a latch and a flip-flop?
Answer: A latch is level-sensitive: while its enable is active the output follows the input, and it holds the last value when the enable goes inactive. A flip-flop is edge-triggered: it samples its input only at a clock edge and holds it until the next edge. Synchronous designs use flip-flops because their timing is defined at edges, which makes analysis of setup and hold times straightforward; latches inferred by mistake in HDL code are a common source of timing problems.
Interview question: Why do MCU GPIO inputs add a couple of clock cycles of delay?
Answer: External signals are asynchronous to the MCU clock, so each input passes through a synchroniser, typically two flip-flops, to avoid metastability propagating into the core logic. Each stage adds a clock cycle. It is usually invisible, but it matters for very fast bit-banged protocols and when measuring precise timing with software reads.
Explain it: In your own words, explain setup and hold time and give one way violating them shows up in firmware.
Answer: A flip-flop samples its input at a clock edge, and for the sample to be reliable the input must be stable for a minimum time before the edge (setup) and after it (hold). If data changes inside that window, the flip-flop may capture the wrong value or become metastable. In firmware this shows up as intermittent bit errors on a fast bus such as SPI when the clock is raised too high or traces are long: the peripheral's data arrives too late for the microcontroller's setup time, so some bits are read wrong, often depending on temperature or the particular board.