Chapters

30 Analog-Digital Boundaries: Signal Contracts

electronics-controller-design
analog
digital
nyquist
adc
mixed-signal
signal-chain
binary
sensors
firmware

30.1 Start With the Decision

An ADC value is not trustworthy until its bandwidth, filter, rate, and time window are named. Those fields form the contract between an analog source and digital code.

30.2 Route Overview

This is part 3 of 3. Review Sampling Design: Product Scenarios for the preceding evidence.

30.3 Learning Objectives

  • Specify an analog-to-digital contract with bandwidth, filter, rate, and duration.
  • Diagnose aliasing caused by marginal rates and missing filters.

30.4 Chapter Roadmap

  • Analog-Digital Signal Boundary Contracts
  • Summary
  • Concept Relationships: Nyquist Sampling
  • See Also
  • Knowledge Check
  • Quiz: Nyquist Sampling Theory
  • Common Pitfalls
  • 1. Sampling Exactly at the Nyquist Rate
  • Anti-Alias Filters for Signals
  • Sampling Rate vs Duration
  • Aliased Powerline DC Offset
  • What’s Next?

30.5 Analog-Digital Signal Boundary Contracts

30.5.1 Start Simple

Prove What the Number Still Means

Picture a water sensor that produces a changing voltage. The device turns it into the number 612 and raises an alarm. Before trusting that alarm, the team must know the input range, the smallest visible step, the time of the sample, and how much noise could move the result.

Sampling rate means how often a signal is measured. An analog to digital converter (ADC) turns a changing voltage into a number. Firmware is the code stored on the device. Modulation means changing a signal to carry or control information. Pulse width modulation (PWM) is a timed on-and-off output used to imitate a changing level. Keep input and output duties separate.

Apply a known low, middle, and high input. Add noise, sample a faster change, move near a logic limit, and restart the device. Record the physical input, chosen range, sample time, raw number, converted unit, and decision. Check that the code reports values outside the proved range instead of treating them as true.

These trials do not capture every source of drift or timing error. The deeper sections show how thresholds, resolution, sampling, filtering, and output timing bound the meaning of the digital record.

Imagine a noisy sensor voltage arriving at the exact point where hardware becomes data. The boundary must decide what range, step size, noise margin, and sampling rate are acceptable before firmware treats the value as truth. Start with the physical signal range, the allowed error, and the evidence that the digital value still means what the sensor measured.

30.5.2 Learning Objectives

After this page, you should be able to:

  • Distinguish amplitude quantization from time sampling in an IoT signal chain.
  • Explain why digitizing near the sensor can make a long cable more robust.
  • Map analog and digital failure modes to the right design controls.
  • Explain how logic thresholds, noise margin, and regeneration make digital links robust.
  • Compare a bounded conversion error budget with accumulating analog-chain noise.

30.5.3 Why Signal Boundaries Follow

Analog vs. Digital Signals introduces the chapter sequence from binary representation through ADCs, sampling, DACs, PWM, and worked examples. This page turns that overview into a reviewable boundary contract: where exactly the signal becomes a number, what information is discarded, what error budget is fixed at that boundary, and why downstream digital transport is more robust than carrying a raw analog voltage.

Use it when an IoT design has to choose where to place an ADC, whether to send a raw sensor voltage or a digital code, how to justify cable length and grounding choices, or how to explain that a digital signal is still a real analog voltage interpreted through thresholds.

The mathematical gist. Analog interference maps directly through sensor sensitivity, (\Delta T=V_{noise}/S), while a digital receiver tolerates noise until it spends a guaranteed margin: (NM_L=V_{IL,max}-V_{OL,max}) and (NM_H=V_{OH,min}-V_{IH,min}). Here, 50.0 mV means 5.00°C of analog error but uses only 12.5% of a 400 mV digital margin.

Math Bridge · guided foundationsWhy does the same noise hurt analog before digital?Let Eddie connect sensor sensitivity, guaranteed thresholds, and noise headroom.

30.5.4 Overview: Digital Is Analog With Two Things Thrown Away

Almost every physical quantity a sensor measures — temperature, pressure, light, sound, acceleration — is analog: continuous in both time and amplitude, taking infinitely many values that change smoothly. A microcontroller is digital: it works with a finite set of numbers, updated at discrete instants. Turning one into the other means deliberately discarding detail along two independent axes:

Quantization (amplitude)

A continuous voltage is snapped to one of a finite set of levels. An N-bit converter has 2^N levels, so the smallest step it can represent is one LSB.

Sampling (time)

The signal is measured only at discrete instants, fs times per second. Between samples, the digital record simply has no information.

The payoff: noise immunity

Once a value is a number, small voltage noise no longer changes it. A digital HIGH/LOW is read with margin, so noise below that margin is rejected.

The payoff: regeneration

Each digital stage re-decides 0 or 1 and outputs a clean signal, so error does not accumulate. Analog signals collect noise and distortion at every stage.

The boundary contract becomes easier to audit when its amplitude and timing decisions sit on one map. Use Figure 30.1 to see where sampling, conversion, filtering, and signal quality depend on one another before deciding what evidence the digital record must retain.

Signal-processing concept map linking the core areas for IoT systems: sampling and the Nyquist criterion, the analog-to-digital pipeline, FFT for moving from the time to the frequency domain, filtering choices such as low-, high-, band-pass, and notch filters, and signal-to-noise ratio, with the relationships between them.
Figure 30.1: Signal-processing boundary map linking sampling, conversion, filtering, frequency analysis, and signal quality.

At the centre of Figure 30.1, Signal Processing branches to Sampling, FFT, Filtering, SNR, and ADC. Begin with Sampling and its “Nyquist: fs>2fmaxf_s > 2f_{max}” constraint, then follow convert to ADC, where bits set voltage resolution. The dashed dependencies show why those choices cannot be isolated: sampling rate sets FFT resolution, while filtering improves SNR. The map therefore turns “digitize early” into a qualified rule—the analogue boundary still needs an anti-aliasing filter, and the chosen rate and bit depth must preserve the evidence the application needs.

The contract is therefore not "analog bad, digital good." It is a handoff rule. Before the ADC, the design must protect amplitude, bandwidth, source impedance, reference stability, and ground return. At the ADC, it deliberately chooses what amplitude steps and time points will survive. After the ADC, the design must protect codes, timestamps, calibration metadata, and validity flags. A later dashboard can only be as trustworthy as the weakest boundary in that chain.

For example, a vibration sensor on a motor may be accurate at the sensing element but still produce misleading digital data if the analog front end clips peaks, if the anti-alias filter lets high-frequency energy fold into the band of interest, or if the digital packet drops the sampling rate and units. The boundary contract names those failure modes while the design is still reviewable.

That is why good IoT designs digitize as early as possible: the moment a reading becomes bits, it can be copied, transmitted, and stored without further degradation, whereas the raw analog voltage on a long wire keeps picking up interference.

30.5.4.1 Overview Knowledge Check

30.5.5 Practitioner: Know Which Domain a Signal Is In

Debugging mixed-signal hardware is easier when you always know whether the signal in front of you is analog or digital, because each domain fails differently and responds to different fixes.

DomainRepresented byMain enemyDesign lever
AnalogA continuous voltage or current (e.g., 10 mV/°C from a temperature sensor)Noise pickup, drift, and loading of high-impedance nodesShielding, filtering, a buffer amplifier, short traces, clean ground
DigitalCodes and logic levels (HIGH/LOW, an ADC's binary output)Aliasing, timing/setup errors, and occasional bit errorsAdequate sample rate and resolution, correct logic thresholds, retries/checksums

Worked example — the same wire, two outcomes. A temperature sensor outputs an analog 10 mV/°C signal. Run that raw analog line three metres to the microcontroller and every millivolt of picked-up noise reads as 0.1 °C of false wander. Instead, place a small ADC at the sensor and send the digital code over those three metres: the same electrical interference now has to be larger than the logic noise margin (hundreds of millivolts) before it flips a single bit, so the reading arrives intact.

A "digital" signal is still physically an analog voltage — a 3.3 V logic HIGH is a real 3.3 V. What makes it digital is the shared agreement to interpret a whole band of voltages as 1 and another band as 0. That agreement, plus margin, is the entire source of noise immunity.

A practical boundary review should write down the facts that make the handoff testable: sensor range and source impedance, expected noise and bandwidth, required anti-alias filter corner, ADC reference and resolution, sample rate, logic family, receiver thresholds, cable length, and the units attached to the digital code. If any one of those is implicit, teams debug symptoms instead of the boundary. If they are explicit, the oscilloscope trace, ADC register value, packet field, and cloud record can be compared against the same contract.

30.5.5.1 Practitioner Knowledge Check

30.5.6 Under the Hood: A Fixed Error Budget vs an Accumulating One

Digitizing does not make a signal perfect — it makes its error bounded and known. The two discretizations each set a hard limit: quantization caps amplitude detail at one LSB (you cannot recover anything finer than Vref / 2^N), and sampling caps time/frequency detail at the Nyquist frequency (you cannot represent anything above fs / 2; higher content folds back as aliasing). Choose the bits and the sample rate at the boundary and you have fixed the error budget for the entire rest of the pipeline.

The amplitude side is a rounding contract. An ideal unipolar ADC with N bits and reference Vref maps a range of input voltages onto 2^N codes, so the unavoidable conversion uncertainty is about half a code step. That error is acceptable only if it is smaller than the measurement tolerance. The time side is a band-limit contract: frequencies above half the sample rate must be removed before the converter, because no downstream digital algorithm can tell whether an aliased component came from the real event or from an under-sampled waveform.

Digital regeneration is a separate but related contract. A receiver does not preserve the exact analog waveform on the wire; it promises to classify voltages below the LOW threshold as 0 and voltages above the HIGH threshold as 1. Noise that stays inside the margin is discarded at the decision point, and the next driver emits a fresh clean LOW or HIGH. Noise that crosses the threshold is no longer "small analog error" — it has become a wrong bit, which is why checksums, retries, and timing margins still matter.

An analog chain has no such boundary. Each amplifier, connector, and long trace adds its own noise, offset, and distortion, and those errors accumulate with every stage — there is no point at which the signal is re-decided and cleaned. This is the deep reason digital dominates modern IoT: it converts an unbounded, growing analog error into a one-time, well-understood conversion error, after which the value is effectively immortal.

30.5.6.1 Under-the-Hood Knowledge Check

30.5.7 Signed Sensor Decoding Contracts

30.5.7.1 Start Simple

Prove One Negative Reading at the Boundary

Imagine a temperature register that says 0xFF9C and the dashboard shows an impossible positive value. The bytes are not wrong; the decoder forgot signedness, width, byte order, or scale. Start by writing the sensor’s register contract, then decode one known negative and one known positive sample before trusting live readings.

An analog-to-digital converter means the circuit that turns a measured voltage into a number; it is shortened to ADC. Firmware means the program stored on a device to control its hardware.

Decode the lowest, zero, highest, and one known negative sample with the released rules. Keep raw bytes, ADC width, byte order, signedness, scale, unit, firmware version, expected value, and result.

This check proves the named register contract, not every sensor mode. The deeper sections explain two’s complement, sign extension, scaling, boundary cases, and reviewable release rules.

30.5.7.2 Learning Objectives

After this page, you should be able to:

  • Explain why a bit pattern needs an encoding before it becomes a numeric value.
  • Decode unsigned and two’s-complement sensor registers into physical units.
  • Apply sign extension when moving narrow signed fields into wider firmware integers.
  • Use boundary cases to catch byte-order, signedness, and scaling mistakes.
  • State a reviewable sensor-data contract that links raw bytes to plausible measurements.

30.5.7.3 Why This Follows Binary Number Systems

Binary Number Systems teaches place value, powers of two, ADC count ranges, and the precision limits that show up in IoT data. This page turns those mechanics into a firmware contract: the same raw bytes can represent a valid measurement, a negative value, or nonsense depending on signedness, byte order, bit width, and scale.

Use it when a driver decodes multi-byte sensor registers, a negative reading appears as a huge positive number, a datasheet uses left-justified fields, or a code review needs evidence that the numeric interpretation matches the hardware contract.

The mathematical gist. A 12-bit two’s-complement field has 4,096 codes. If bit 11 is set, subtract 4,096 before multiplying by the chapter’s 0.0625°C/LSB: (0xE70=3696) becomes (-400) counts and (-25.0°C), not +231.0°C. Quantisation still contributes (q/\sqrt{12}=0.0180°C) rms, and a 1 Hz poll can only preserve real temperature content below 0.5 Hz.

Math Bridge · guided foundationsHow can the same 12 bits mean −25°C or +231°C?Let Eddie connect sign extension, scaling, quantisation noise, and polling bandwidth.

30.5.7.4 Overview: The Same Bits Mean Different Numbers

A binary pattern by itself is ambiguous — you also have to know its encoding. The byte 1111 1111 is 255 read as an unsigned number, but −1 read as a signed (two's complement) number. IoT firmware constantly moves between the two:

Worked example: a pressure sensor returns two bytes, 0x01 and 0x90. If the datasheet says the first byte is the high byte and the field is unsigned, the firmware combines them as (0x01 << 8) | 0x90 = 0x0190 = 400. With a scale of 0.25 kPa/LSB, that means 400 x 0.25 = 100 kPa. The same physical bytes would mean something else if they were little-endian, signed, or fixed-point. This is why a review should name the byte order, bit width, signedness, and scale factor next to the decoding code, not just say "read the register."

The practical habit is to decode in layers. First, combine bytes into a raw integer. Second, apply the signed or unsigned interpretation. Third, apply the scale. Fourth, check the result against the sensor's physical range. If a room-pressure sensor suddenly prints 65535 kPa, the binary pattern may be valid, but the interpretation is almost certainly wrong.

Signed decoding fails when firmware performs the right operation at the wrong stage. Before applying the temperature scale, use Figure 30.2 to distinguish the operations that inspect a field from those that reposition or modify it.

Bitwise operations in real IoT code with worked examples for AND to extract or check bits, OR to set or enable, XOR to toggle, and shift to pack or extract.
Figure 30.2: Bitwise operations used to inspect, modify, and reposition fields in IoT registers.

In Figure 30.2, the AND: Extract / Check panel masks unwanted bits—its value & 0x0F example keeps only bits 0–3—whereas SHIFT: Pack / Unpack moves a field, as raw >> 4 does for a 12-bit temperature stored in the upper bits. OR: Set / Enable and XOR: Toggle / Flip change bits, so using them during decode would alter the evidence rather than interpret it. For the running register example, assemble the two bytes, shift away the four configuration bits, apply two’s-complement signedness, and only then multiply by 0.0625 °C/LSB.

Unsigned (straight binary)

Used by unipolar ADCs that read 0 to Vref. Code C maps to voltage V = (C / 2^N) × Vref.

Signed (two's complement)

Used for values that go negative — sub-zero temperature, ±g acceleration. The top bit is the sign.

Sign bit

In an N-bit two's-complement value, bit N−1 set means negative; the range is −2^(N−1) to +2^(N−1)−1.

Sign extension

Widening a signed value must copy the sign bit into the new high bits — or a negative reading turns into a huge positive one.

30.5.7.4.1 Overview Knowledge Check

30.5.7.5 Practitioner: Decoding a Signed Sensor Register

Many I2C sensors return signed values in two's complement. A TMP102-class temperature sensor, for example, uses a 12-bit two's-complement code at 0.0625 °C per LSB. To go from code to temperature: if the top bit is 0 it is a straightforward positive number; if the top bit is 1, it is negative, and you recover the magnitude by treating it as two's complement.

Start from the exact register layout. A 12-bit temperature value may arrive left-justified in two bytes, so the firmware might need raw12 = ((msb << 8) | lsb) >> 4 before signed decoding. If msb=0x19 and lsb=0x00, raw12=0x190=400, giving 25.0 °C. If msb=0xE7 and lsb=0x00, raw12=0xE70=3696; bit 11 is set, so the signed value is 3696 - 4096 = -400, giving -25.0 °C. A robust driver keeps those intermediate values visible in logs or tests so byte-order and shift mistakes are easy to catch.

Use a boundary test before trusting the driver. Feed it 0x000, 0x001, 0x7FF, 0x800, and 0xFFF. The expected signed outputs are 0, 1, 2047, -2048, and -1. Those five cases expose off-by-one thresholds, missing sign extension, and accidental unsigned casts faster than testing only room-temperature readings.

12-bit code (hex)Signed valueTemperature (× 0.0625 °C)
0x190+400+25.0 °C
0x001+1+0.0625 °C
0xFFF−1−0.0625 °C
0xE70−400−25.0 °C

Check the negative case: 0xE70 = 3696. Since 3696 ≥ 2048, the sign bit is set, so the signed value is 3696 − 4096 = −400, and −400 × 0.0625 = −25.0 °C. Reading the same 0xE70 as a plain unsigned number would instead give 3696 × 0.0625 = +231 °C — a nonsense value that is a classic field bug.

30.5.7.5.1 Practitioner Knowledge Check

30.5.7.6 Under the Hood: Sign Extension and Why Two’s Complement Won

To load an N-bit two's-complement field into a wider integer correctly, you replicate the sign bit (bit N−1) across all the new high bits. An equivalent arithmetic recipe for a raw code that a register read gives you as an unsigned number: if the raw value is ≥ 2^(N−1), subtract 2^N; otherwise leave it. For 12 bits that is: value = (raw ≥ 2048) ? raw − 4096 : raw. That single line turns 0xFFF (4095) into −1 and 0xE70 (3696) into −400, exactly matching a proper sign extension.

Worked example in binary: the 12-bit code 1110 0111 0000 has bit 11 set, so a 16-bit signed value must become 1111 1110 0111 0000, not 0000 1110 0111 0000. The first pattern is 0xFE70, which a 16-bit signed integer reads as -400. The second pattern is 0x0E70, which reads as 3696. After scaling by 0.0625 °C, the correct value is -25.0 °C; the zero-extended bug prints 231.0 °C. Both results came from the same twelve bits. Only sign extension separated a plausible cold reading from a field failure.

The same idea applies when firmware packs status fields beside data bits. If a 14-bit signed current value sits in bits 15..2 of a register, shift first, mask to 14 bits, then sign-extend from bit 13. Sign-extending before the shift can accidentally treat a status flag as the sign bit, which turns a warning flag into a huge negative measurement.

Two's complement became universal for a concrete hardware reason: the same binary adder handles both signed and unsigned addition, and subtraction is just adding the negative, with any overflow wrapping cleanly modulo 2^N. There is a single representation of zero (unlike sign-magnitude), so no wasted −0 code. That is why nearly every microcontroller register, ADC output, and C int uses it — and why forgetting to sign-extend is such a common IoT numeric bug.

30.5.7.6.1 Under-the-Hood Knowledge Check

30.6 Summary

This chapter covered the Nyquist-Shannon Sampling Theorem - the fundamental rule for digitizing analog signals:

Read these conclusions as one connected engineering argument: Nyquist Theorem: Sample at least 2x the highest frequency component (f_sample >= 2 x f_max). Aliasing: Undersampling causes high frequencies to appear as lower frequencies. Aliased Frequency: f_alias = |f_signal - n * f_sample| (where n is the nearest integer) when Nyquist is violated; for signals between f_s/2 and f_s this simplifies to |f_signal - f_sample|. Anti-Aliasing Filters: Hardware low-pass filters remove high frequencies before ADC. Oversampling: Sampling at 2.5-5x f_max provides margin for filter roll-off. Power Trade-offs: Higher sampling rates consume more power; sample only as fast as needed.

Understanding Nyquist is essential for avoiding aliasing artifacts in IoT sensor data.

30.7 Concept Relationships: Nyquist Sampling

ConceptRelates ToRelationship
Nyquist RateSignal BandwidthNyquist rate = 2 × highest frequency component; 20 kHz audio requires ≥ 40 kSPS
AliasingUnder-samplingOccurs when f_s < 2f_max; 50 Hz signal sampled at 80 Hz appears as 30 Hz (80 - 50)
Anti-Aliasing FilterNyquist FrequencyLow-pass filter cutoff <= f_s/2 (practically f_max or f_s/4); attenuates frequencies above Nyquist to prevent aliasing
OversamplingSNR ImprovementEach 2× increase in sampling rate improves SNR by ~3 dB (effectively 0.5 bits of resolution)
OversamplingFilter Complexity4× oversampling reduces anti-aliasing filter steepness requirement from 96 dB/octave to 24 dB/octave
DecimationData RateAfter oversampling + digital filtering, downsample (decimate) to reduce storage/transmission bandwidth
Sampling RatePower ConsumptionESP32: ~2 mA base + 0.001 mA per sample/sec; 10 kHz sampling = 12 mA (6× higher than 100 Hz)

30.8 See Also

In This Series:

Follow these connections in order: Binary Fundamentals - Binary number systems and bit depth. ADC Fundamentals - Quantization, resolution, and conversion architectures. ADC/DAC Worked Examples - Practical ADC calculations and design examples. Aliasing and Anti-Alias Filter Contracts - Folded-frequency math, pre-ADC filtering, and oversampling margin. DAC and PWM Output - Digital-to-analog conversion and PWM.

Related Topics:

Follow these connections in order: Sensor Calibration - How sampling rates affect sensor accuracy. Signal Processing Essentials - Digital signal processing and frequency-domain analysis.

30.9 Knowledge Check

The checks below focus on plausible wrong frequencies, underestimated memory, missing filters, and wasteful oversampling.

Common Pitfalls

Most field failures here confuse a valid-looking number with a valid measurement. Use these pitfalls before trusting sampled data.

The Nyquist theorem requires at least 2x the highest frequency, but sampling at exactly 2x produces ambiguous results at that frequency. In practice, sample at 5-10x the highest signal frequency to leave margin for filter roll-off and timing jitter. A rule of thumb: if your highest signal frequency is 100 Hz, sample at 500-1000 Hz.

Electrical noise and interference exist at all frequencies regardless of the signal of interest. A 1 Hz temperature signal sampled at 10 Hz is contaminated by 50 Hz mains hum folded to 0 Hz DC offset if no anti-aliasing filter is present. Always filter before the ADC even if the signal of interest has very low bandwidth.

Sampling rate (samples per second) and sample acquisition time (how long each sample takes) are different concepts. The ESP32 ADC has a maximum sampling rate of approximately 100 kSps, but each conversion takes approximately 10 us. Triggering conversions faster than the ADC can complete them causes invalid readings. Always respect the minimum conversion time specified in the datasheet.

A 60 Hz (or 50 Hz) mains noise signal sampled at 100 Hz produces an alias at 40 Hz (or 50 Hz alias at 50 Hz = DC component). This adds a spurious offset to all ADC readings that looks like a sensor calibration error. When ADC readings have unexplained offsets or slow oscillations, suspect powerline noise aliasing before suspecting sensor calibration drift.

30.10 What’s Next?

Now that you understand sampling theory, explore the practical side of analog-to-digital conversion with worked examples and related topics.

TopicLinkWhy Read Next
ADC/DAC Worked Examplesanalog-digital-adc-dac-examples.htmlApply Nyquist calculations to real ADC and DAC design problems
ADC Fundamentalsanalog-digital-adc-conversion-resolution.htmlDeepen understanding of quantization, resolution, and conversion architectures
DAC and PWM Outputdac-pwm-foundations.htmlSee how digital signals are converted back to analog using DAC and PWM
Sensor Calibration../sensors/sensor-calibration-measurement.htmlLearn how sampling rate choices affect sensor measurement accuracy in practice

30.11 Continue Your Route

This final part closes the route from Analog-Digital Signal Boundary Contracts through What’s Next?. Return to Sampling Design: Product Scenarios or continue from the electronics module index.