Analog Comparator: Hysteresis and Wake-Up Application
Analog comparator hysteresis design: calculate thresholds, avoid noise chatter, and build ADC-free, CPU-free MCU wake-up circuits.
Contents & prerequisites
What is an Analog Comparator?
An analog comparator is a peripheral that continuously compares two analog voltages — typically an external input pin against a reference voltage or a second input pin — and produces a single-bit digital output reflecting which is larger. Unlike an ADC, it does not quantize the input into a multi-bit code; it answers one question, "is V+ above V-?", and it does so at hardware speed, without CPU involvement, and often without the core clock running at all.
This makes the comparator one of the few peripherals genuinely useful in deep sleep. A battery-powered node can shut down its ADC, its regulators for analog reference ladders, and its CPU, while a comparator sipping microamps watches a voltage rail or sensor signal and wakes the system only when something crosses a threshold.
Basic comparator architecture in microcontrollers
Internally, an MCU comparator is a differential amplifier with two inputs (often muxed from several pins or internal references) and rail-to-rail or near-rail digital output. Most vendor implementations add:
- A programmable reference source (internal bandgap-derived DAC or resistor ladder) so you don't need an external reference for the negative input.
- An input multiplexer selecting among several external pins and internal sources (VREF, DAC output, temperature sensor).
- A hysteresis control register, usually a few discrete steps (e.g., 0 mV, 10 mV, 20 mV, 50 mV) rather than a continuous value.
- An output that can be routed to a GPIO, to a timer input-capture, or directly to the interrupt/wake-up controller — bypassing the CPU entirely for the trigger event.
Comparator vs. ADC: when to use which
The core difference is informational content versus power cost. An ADC gives you a quantized amplitude — 12 bits of "how much" — at the price of a reference, a sample-and-hold, a conversion clock, and typically hundreds of microamps to low milliamps active current plus conversion latency. A comparator gives you 1 bit — "past this line or not" — for a fraction of the current (commonly single-digit to tens of microamps, check your part's datasheet) and with no conversion time beyond its propagation delay.
Use an ADC when you need the actual value: battery percentage, sensor reading for a control loop, calibration data. Use a comparator when you only need to know that a value has crossed a line: undervoltage lockout, overcurrent trip, a temperature exceeding a safety limit, a button or reed switch bouncing on a noisy line. A very common pattern combines both: comparator wakes the system, then the ADC is powered up only long enough to take a precise reading.
Typical pinout and power requirements
Comparator inputs are usually shared with GPIO pins through the alternate-function mux, so selecting a pin as a comparator input follows the same configuration model used for any other peripheral pin — see GPIO Alternate Function and Peripheral Multiplexing for how that mux selection and pin-mode configuration works in general. Power-wise, expect the comparator block itself to draw far less than the ADC's reference and sample-and-hold circuitry; the exact figure (often in the low microamp range in low-power modes) is in the electrical characteristics table of your part's datasheet, listed separately from ADC current.
Why Hysteresis Matters
Problem: noise-induced chatter and false transitions
A comparator with a single, fixed threshold and no hysteresis is a chatter generator whenever the input signal is noisy near that threshold. If Vin sits within a few millivolts of Vref and picks up even modest coupled noise — switching regulator ripple, ADC/DAC glitches, EMI — the output will toggle rapidly every time the noise crosses the line. Each toggle can generate an interrupt or wake event, so a single slow analog transition (a battery discharging, a temperature drifting) can produce dozens or hundreds of spurious edges instead of one clean transition. Downstream, this looks like a bouncing mechanical switch, except it's purely electrical.
Hysteresis band definition and calculation
Hysteresis solves this by using two thresholds instead of one: a higher threshold (V_TH) that the input must exceed to switch the output one way, and a lower threshold (V_TL) it must fall below to switch back. The difference V_HYS = V_TH − V_TL is the hysteresis band. As long as V_HYS is larger than the peak-to-peak noise riding on the input near the crossing point, the output cannot chatter — noise alone can't push the signal from below V_TL to above V_TH and back.
Sizing rule of thumb: estimate the peak-to-peak noise on the input at the transition (from scope measurement or datasheet ripple specs), then set V_HYS to at least 1.5–2x that value for margin.
Upper and lower threshold configuration
Most integrated comparators let you set hysteresis as a fixed offset applied symmetrically around a single programmed reference, rather than two independent registers. If your comparator only exposes one reference plus a hysteresis-amount field (say, 0/10/20/50 mV), then:
V_TH = V_ref + (hysteresis / 2)
V_TL = V_ref - (hysteresis / 2)
If your part instead exposes true dual thresholds (two DAC codes), you set V_TH and V_TL directly — check the reference manual's comparator chapter for which model your silicon uses, since the register-level behavior differs by vendor.
Trade-offs: response time vs. noise immunity
Widening the hysteresis band improves noise immunity but delays detection of genuine transitions — the input must travel further before the output flips, and swings that don't reach V_TH (or fall back below V_TL) are, by design, invisible. A hysteresis band tuned for a slow, noisy battery-voltage signal (tens of mV) would be inappropriate for a fast comparator-based zero-crossing detector, where even a few mV of delay skews timing. Pick the smallest band that still exceeds your measured noise floor.
Configuring Hysteresis in Hardware
Setting positive and negative input thresholds
In practice you configure three things: which pin/source drives V+ (your signal), which source drives V− (an internal reference DAC, an external resistor divider, or another pin), and the hysteresis field. A typical sequence:
/* Pseudocode - consult your MCU reference manual for exact registers */
COMP1->CSR &= ~COMP_CSR_EN; // disable while configuring
COMP1->CSR |= COMP_INPUT_PLUS_PA1; // V+ = external pin PA1
COMP1->CSR |= COMP_INPUT_MINUS_VREF; // V- = internal reference DAC
COMP1->CSR |= COMP_HYST_20MV; // hysteresis = 20 mV
COMP1->CSR |= COMP_EN; // enable comparator
Hysteresis window sizing for your application
For a 3.3 V system monitoring a battery rail with roughly 15 mVpp switching noise, a 20 mV or 50 mV hysteresis setting (whichever step your part offers just above the noise floor) is a reasonable starting point; verify on the bench with a scope on the comparator output while the battery voltage is held near the trip point.
Output filtering and edge detection
Some comparator peripherals include a digital deglitch filter — an N-cycle counter requiring the input to stay stable before propagating the output change — in addition to analog hysteresis. Where available, enabling a short filter (a few peripheral clock cycles) adds a second layer of protection against sub-microsecond glitches that hysteresis alone won't catch, at the cost of a few cycles of added latency.
Comparator output routing to GPIO or interrupt
The output can typically be routed three ways: to a dedicated GPIO for external observation, to a timer's input-capture channel for pulse-width or frequency measurement, or directly into the EXTI/interrupt controller for wake-up. For wake-up designs, the direct interrupt route is what matters, because it works even when the GPIO peripheral clock is gated in low-power mode.
Wake-Up Application: System-Level Design
Low-power operation: comparator in sleep modes
The key property that makes comparators useful for wake-up is that the analog comparator block can often remain active in STOP/STANDBY-class low-power modes where the CPU, most clocks, and most peripherals are off. Check your part's low-power mode table — comparators are usually listed alongside RTC and a handful of other "always-on domain" peripherals as available in the deepest sleep states.
Interrupt generation on threshold crossing
Configure the comparator interrupt (via EXTI or an equivalent line) for rising, falling, or both edges depending on whether you care about crossing up, crossing down, or either. This interrupt is what pulls the MCU out of sleep — the wake-up latency is then dominated by clock startup time (bringing the main oscillator back up), not by comparator response time, though the comparator's own propagation delay (datasheet parameter, often sub-microsecond to a few microseconds) adds to total reaction time for fast events.
Comparator as sensor interface (temperature, voltage, current)
Any sensor with an analog output — a shunt-resistor current sense, a thermistor divider, a photodiode transimpedance stage — can drive a comparator input directly. Set V− to a reference corresponding to your alarm threshold (via the internal DAC or a resistor divider from VREF), and the comparator becomes a hardware threshold detector for that physical quantity with zero ongoing CPU or ADC cost.
Typical wake-up flow: comparator triggers, MCU exits sleep
- MCU configures comparator (pin, reference, hysteresis) and enables its interrupt.
- MCU enters STOP/STANDBY mode; CPU clock gated, most peripherals off, comparator stays biased.
- Monitored voltage crosses V_TH (or V_TL on the return path).
- Comparator output flips; interrupt line asserts.
- Wake-up controller restarts the clock tree; CPU resumes execution at the interrupt vector.
- ISR clears the flag, optionally powers up the ADC for a precise reading, and schedules the appropriate response.
Practical Design Patterns
Battery monitoring with hysteresis wake-up
Divide the battery voltage down to the comparator's input range, set V_TH to your low-battery warning voltage and rely on hysteresis (e.g., 100–200 mV at the battery, scaled by the divider) so the system doesn't re-trigger repeatedly as the voltage sags and recovers slightly under load. Because the comparator runs continuously in sleep, you get low-battery detection without ever waking the CPU to poll the ADC.
Sensor threshold detection without ADC polling
For a thermal cutoff or a light-level trigger, wire the sensor's analog output to the comparator, set the trip reference via the internal DAC, and let the interrupt handle the event. This eliminates the periodic-wake-poll-sleep cycle a timer+ADC design would need, which is the single biggest power saver in duty-cycled sensing designs — polling every 100 ms with an ADC costs orders of magnitude more average current than a comparator sitting idle between rare events.
Debouncing strategies for analog signals
For mechanical switches (reed relays, tilt sensors) wired through an RC low-pass into a comparator, combine three techniques: an RC filter sized to the switch's bounce time constant, comparator hysteresis wide enough to reject the filtered bounce residual, and, if available, the digital deglitch filter. This three-layer approach is far cheaper in power than a CPU-based debounce routine that requires staying awake to sample a GPIO repeatedly.
Power budget: comparator current vs. ADC sampling
When budgeting sleep-mode current, treat the comparator as a fixed always-on tax (its bias current, from the datasheet) versus the ADC's cost model, which is (active current) × (conversion time) × (sample rate) plus reference settling overhead each time it powers up. For a system checking a threshold once per second, an ADC-based poll can easily cost 10–100x more average current than a comparator held continuously active, because the ADC's active current, though only drawn briefly, is much higher and recurs on every wake cycle, while the comparator's small bias current is paid once, continuously, at a much lower level.
Common Pitfalls and Best Practices
Avoiding metastability and race conditions
Near the threshold, a comparator's output can linger in an indeterminate state for longer than its specified propagation delay — this is metastability, distinct from noise-induced chatter. If the comparator output feeds directly into synchronous logic (a timer capture, a flip-flop) without the vendor's internal synchronizer, add a synchronizing register stage in your logic or rely on the wake-up controller's specified synchronization behavior, documented in the interrupt/EXTI chapter of the reference manual.
Supply decoupling for comparator stability
Comparator reference DACs and bias circuits are sensitive to supply noise; inadequate decoupling on VDD near the comparator block can inject noise directly into V_ref, effectively narrowing your hysteresis margin from the inside. Follow the datasheet's recommended decoupling capacitor placement for the analog supply domain, and keep comparator input traces short and away from switching nodes.
Input impedance and source resistance effects
Comparator inputs typically present a moderate input leakage/bias current and finite input capacitance. A high source impedance (e.g., a large-value resistor divider for low quiescent current) combined with input capacitance forms an RC lag that slows the effective slew rate seen by the comparator, which can worsen susceptibility to noise near the threshold and increase effective propagation delay. Check the datasheet's recommended maximum source resistance and add a small bypass capacitor at the input if your divider impedance is high.
Datasheet parameters: response time, offset, propagation delay
Three numbers matter most when selecting hysteresis and estimating wake latency: propagation delay (time from input crossing to output flipping, often specified at a given overdrive voltage), input offset voltage (a fixed error that shifts your effective threshold and should be added to your hysteresis margin budget), and power-up/enable time if the comparator itself is powered down between checks. All three live in the electrical characteristics table of the part's datasheet — do not assume typical values without checking your specific silicon revision.
Linking Comparators to Microcontroller Initialization
Peripheral multiplexing: comparator pin assignment
Because comparator inputs share physical pins with GPIO and other peripherals, assigning a pin to the comparator function follows the same alternate-function selection process used throughout the MCU — see GPIO Alternate Function and Peripheral Multiplexing for the general mechanism of selecting a pin's function, setting its mode to analog (comparators typically require the GPIO configured as analog input, disabling the digital input buffer to save power and avoid crosstalk).
Clock and enable configuration
Before touching comparator control registers, enable its peripheral clock (RCC/PCC or equivalent) and confirm the comparator's own enable bit — many parts require a short stabilization delay after enabling before the output is valid, specified in the datasheet as a "startup time" or "enable time."
Interrupt handler setup for wake-up events
Register the comparator's interrupt vector, configure edge sensitivity in the EXTI (or equivalent) controller, and ensure the interrupt is unmasked at both the peripheral and NVIC level before entering sleep. In the ISR, clear the pending flag first — failing to do so is a common bug that causes an immediate re-entry into the ISR or an inability to return to sleep — then handle the wake-up event (e.g., power up the ADC for a precise reading, or set a flag for the main loop).
Learning
Sign in to track your progress.
Evidence
Public projects engineers linked to Analog Comparator: Hysteresis and Wake-Up Application.
No engineer has linked a project to this topic yet. Built something that proves it? Add the project and tag it with embedded-systems-analog-comparator-hysteresis-and-wake-up-applicati — it then shows here and on your public profile.
