14  Analog and Digital Electronics

14.1 Learning Objectives

  • Explain the difference between analog and digital signals and why conversion between them is necessary in IoT systems
  • Describe how ADC and DAC circuits operate, including resolution, quantization error, and common architectures
  • Apply the Nyquist-Shannon sampling theorem to determine appropriate sampling rates for real-world sensor signals
  • Calculate ADC/DAC conversion values using standard formulas for temperature, distance, and motor control applications
  • Compare PWM and true DAC output methods and select the appropriate technique for a given actuator control scenario
In 60 Seconds

Analog-to-digital conversion is the essential bridge between continuous real-world sensor signals and discrete digital microcontrollers. This series covers binary number systems, ADC/DAC operation, Nyquist sampling theory, and practical worked examples – everything you need to understand how IoT devices read sensors and control actuators at the hardware level.

14.2 Overview

Every IoT device that reads a sensor or drives an actuator must cross the analog-digital boundary. This five-chapter sequence takes you from binary representation, to ADC behavior, to sampling constraints, to output generation, and finally to worked design calculations. The goal is to help you choose the right converter settings and verify whether an interface is precise enough for the job.

Analog and digital are like the difference between a slide (smooth) and stairs (steps)!

Sammy the Sensor feels temperatures that go smoothly from cold to hot - like 20.1, 20.2, 20.3 degrees. But Max the Microcontroller only understands step numbers like 20, 21, 22. ADC Andy translates between them! The more steps Andy uses, the more precise the translation becomes.

14.3 Prerequisites

Before starting this series, ensure familiarity with:


14.4 Chapter Series

This topic is divided into five focused chapters for easier learning:

14.4.1 1. Binary Number Systems

Binary Number Systems (~2,500 words)

Learn the foundation of digital electronics: - Analog vs digital signals - Binary (base-2) number system - Powers of 2 and ADC resolution - Floating point numbers and IEEE 754 - Why you should never compare floats with ==

14.4.2 2. ADC Fundamentals

ADC Fundamentals (~3,500 words)

Understand how analog-to-digital converters work: - ADC architecture and operation - Successive Approximation Register (SAR) ADCs - Resolution and quantization error - Interface challenges (1/f noise, thermal noise) - Microcontroller ADC specifications (Arduino, ESP32, STM32)

14.4.3 3. Nyquist Sampling Theory

Nyquist Sampling Theory (~2,500 words)

Master the critical sampling rate theorem: - Nyquist-Shannon sampling theorem - Aliasing and why undersampling fails - Anti-aliasing filter design - Sampling rate vs power consumption tradeoffs - Interactive aliasing demonstration

14.4.4 4. DAC and PWM Output

DAC and PWM Output (~3,000 words)

Generate analog outputs from digital systems: - DAC operation and formulas - R-2R ladder architecture - True DAC vs PWM comparison - PWM as pseudo-analog output - RC filter design for PWM smoothing - Arduino and ESP32 implementation - Hands-on labs with code examples

14.4.5 5. ADC/DAC Worked Examples

ADC/DAC Worked Examples (~3,500 words)

Integrate the full sequence in realistic calculations: - ADC conversion formula and calculations - Temperature sensor (LM35) interfacing - Quantization error analysis - Nyquist calculations for audio and vibration - Soil moisture sensor optimization (ESP32) - Ultrasonic distance measurement timing - DAC motor speed control - LED dimming with gamma correction


14.5 Learning Path

Study the series in this order because each chapter answers the next practical design question:

  1. Binary Number Systems: What do the numbers inside a microcontroller actually mean?
  2. ADC Fundamentals: How does a real sensor voltage become one of those numbers?
  3. Nyquist Sampling Theory: How fast must you sample so the number stream still represents the real signal?
  4. DAC and PWM Output: How do digital decisions turn back into LED brightness, motor speed, or audio output?
  5. ADC/DAC Worked Examples: How do you combine all of the earlier ideas in a complete IoT design?

Recommended Order: Follow chapters 1-5 in sequence. The worked-examples chapter belongs at the end because it assumes you already understand binary representation, ADC limits, Nyquist sampling, and DAC/PWM output.

Quick Reference: If you already know the theory, jump directly to Worked Examples and return to the earlier chapters only when a formula or design choice is unclear.

14.6 How To Use This Book

ADC Resolution determines measurement precision. Consider a temperature sensor outputting 0-1V for 0-100°C range:

10-bit ADC (Arduino Uno):

\[\text{Step size} = \frac{1\text{V}}{2^{10} - 1} = \frac{1\text{V}}{1023} \approx 0.978 \text{ mV}\]

\[\text{Temperature resolution} = \frac{100°\text{C}}{1023} \approx 0.098°\text{C per step}\]

12-bit ADC (ESP32):

\[\text{Step size} = \frac{1\text{V}}{2^{12} - 1} = \frac{1\text{V}}{4095} \approx 0.244 \text{ mV}\]

\[\text{Temperature resolution} = \frac{100°\text{C}}{4095} \approx 0.024°\text{C per step}\]

The 12-bit ADC provides 4× better temperature resolution – crucial for precision applications like laboratory environmental monitoring or medical devices where 0.1°C accuracy is required.

Nyquist sampling: To digitize a 60 Hz power line signal for smart meter applications:

\[f_{sample} \geq 2 \times f_{max} = 2 \times 60 \text{ Hz} = 120 \text{ Hz minimum}\]

In practice, use 5× oversampling: \(f_{sample} = 300\) Hz to avoid aliasing from harmonics.


14.7 Key Concepts Summary

  • ADC: Converts analog voltage to a digital value. Formula idea: scale the input voltage by the reference voltage, then multiply by the maximum code.
  • DAC: Converts a digital value back to analog voltage. Formula idea: scale the digital code by the reference voltage to recover the output level.
  • Resolution: The number of bits sets how many distinct levels you can represent. Formula: levels = 2^n
  • Nyquist rate: The minimum safe sampling rate is at least twice the highest signal frequency. Formula: sampling rate >= 2 x highest frequency
  • Quantization error: ADCs introduce unavoidable rounding uncertainty because they map continuous voltages into discrete steps. Rule of thumb: about +/- 0.5 LSB
  • PWM: A digital signal can behave like an analog output when the load responds to the average duty cycle. Formula idea: average voltage equals high voltage times duty cycle.

This multi-chapter example ties together binary, ADC, sampling, and DAC concepts.

Scenario: Design a predictive maintenance system that monitors machine vibration to detect bearing failures.

Requirements:

  • Detect vibrations from 10 Hz (normal operation) to 5 kHz (bearing defects)
  • Amplitude range: 0.1g to 10g (acceleration)
  • Accuracy: ±0.01g to catch early-stage failures
  • Output: Visual alert via LED brightness (proportional to vibration level)

Step 1: Sensor and ADC Selection (Chapter 2: ADC Fundamentals)

Accelerometer (ADXL1002, single-axis MEMS vibration sensor) outputs analog voltage: - Sensitivity: 40 mV/g @ 3.3V supply - Range: ±50g → output centered at 1.65V (mid-supply) - Usable output swing: ~0.65V to ~2.65V for ±25g

To achieve ±0.01g accuracy: - Voltage per 0.01g = 0.01g x 40 mV/g = 0.4 mV - Required ADC steps across 10g range = (10g x 40 mV/g) / 0.4 mV = 1,000 steps - Minimum ADC resolution = log2(1000) = 10 bits

Decision: Use ESP32’s 12-bit ADC (4,096 levels) → provides 3.3V / 4095 = 0.806 mV/step → adequate for 0.4 mV requirement with some margin when combined with signal conditioning.

Step 2: Sampling Rate Calculation (Chapter 3: Nyquist Sampling)

Maximum vibration frequency: 5 kHz (bearing defect signature)

Nyquist theorem: f_sample ≥ 2 × f_max - Minimum theoretical: 2 × 5 kHz = 10 kHz - Practical with anti-aliasing: 2.5× oversampling = 12.5 kHz

ESP32 ADC can sample at 83 kHz maximum → 12.5 kHz is well within capability.

Sampling period = 1 / 12,500 Hz = 80 µs per sample

Step 3: Binary Representation (Chapter 1: Binary Fundamentals)

ESP32 12-bit ADC outputs 0-4095: - For 2.0g vibration: output = 1.65V + (2.0g x 40 mV/g) = 1.65V + 0.08V = 1.73V - ADC value = floor((1.73V / 3.3V) x 4095) = floor(2146.8) = 2146 decimal - Binary: 2146 = 100001100010₂ (12 bits)

Step 4: PWM Output for LED Alert (Chapter 5: DAC and PWM)

Map vibration amplitude to LED brightness: - 0-1g → Dim (PWM duty cycle 10%) - 1-5g → Medium (PWM duty cycle 50%) - 5-10g → Bright (PWM duty cycle 100%)

For 2.0g reading (ADC = 2146): - Normalized vibration = 2.0g / 10g = 0.2 (20% of full scale) - PWM duty cycle = 10% + (0.2 x 90%) = 28% duty cycle - PWM value (8-bit) = 0.28 x 255 = 71 (send to ledcWrite())

Step 5: Complete Code Implementation

// ESP32 Vibration Monitor -- ADC to PWM LED Alert
#define ACCEL_PIN  34    // ADC1 input
#define LED_PIN    25    // PWM output
#define PWM_CH     0
const float V_BIAS = 1.65, SENS = 0.040; // 40 mV/g

void setup() {
  analogReadResolution(12);
  ledcSetup(PWM_CH, 5000, 8);        // 5 kHz, 8-bit
  ledcAttachPin(LED_PIN, PWM_CH);
}

void loop() {
  int raw = analogRead(ACCEL_PIN);
  float v = raw * (3.3 / 4095.0);
  float g = abs((v - V_BIAS) / SENS); // acceleration in g
  int pwm = constrain((int)(25 + (g / 10.0) * 230), 0, 255);
  ledcWrite(PWM_CH, pwm);
  delayMicroseconds(80);              // ~12.5 kHz sample rate
}

Step 6: Verification Against Requirements

  • Frequency range 10 Hz - 5 kHz: 12.5 kHz sampling (2.5x Nyquist). Achieved: yes.
  • Amplitude range 0.1g - 10g: ±50g accelerometer range (ADXL1002). Achieved: yes.
  • Accuracy ±0.01g: 0.806 mV/step / 40 mV/g = 0.020g per step (±0.010g). Achieved: yes, it meets the requirement.
  • LED brightness output: PWM from 0-100% proportional to vibration level. Achieved: yes.

Key Integration Points:

  • Binary (Ch1): ADC output is binary number requiring correct interpretation
  • ADC (Ch2): 12-bit resolution provides ±0.010g quantization error, meeting the 0.01g requirement
  • Nyquist (Ch3): 12.5 kHz sampling prevents aliasing of 5 kHz signals
  • PWM (Ch5): LED dimming via PWM provides visual feedback without true DAC

This example demonstrates how all chapters work together in a complete IoT sensing and actuation system!

14.8 Concept Relationships: How ADC/DAC Concepts Connect

  • Binary (Ch1) -> Digital representation: Requires number systems and base-2 thinking. Applied when you interpret ADC output values or transmit readings digitally.
  • Bits and resolution -> Precision limits: Requires binary and powers of two. Applied when you choose ADC resolution and estimate quantization error.
  • ADC (Ch2) -> Sensor digitization: Requires both binary and voltage concepts. Applied when reading temperature, pressure, light, and other analog sensors.
  • Quantization -> Measurement error: Requires understanding resolution and step size. Applied when checking whether a sensor system is accurate enough for its job.
  • Sampling rate (Ch3) -> Signal capture: Requires Nyquist theorem and frequency concepts. Applied in audio, vibration, and other faster-changing signals.
  • Aliasing -> Signal corruption: Requires sampling and frequency understanding. Applied when designing anti-aliasing filters and validating ADC designs.
  • DAC (Ch5) -> Analog output: Requires binary and voltage conversion. Applied in audio output and analog control signals.
  • PWM (Ch5) -> Pseudo-analog output: Requires duty-cycle and frequency understanding. Applied in LED dimming, motor speed control, and servo interfaces.
  • SPI/I2C -> ADC communication: Requires digital protocol basics. Applied when you connect external ADC chips such as ADS1115 and MCP3008.

Key Insight: Every analog sensor signal follows the same path: Physical phenomenon → Analog voltage → ADC sampling (Nyquist) → Binary representation (bits) → Digital processing → DAC or PWM → Analog output. The resolution (bits) determines precision, and the sampling rate (Hz) determines the maximum detectable frequency.


Key Takeaway

When designing an IoT sensor interface, three numbers determine success: the ADC resolution (bits) sets your measurement precision, the sampling rate (Hz) determines the fastest signal you can capture, and the output method (true DAC vs PWM) controls how your system drives actuators. Master these three parameters and you can confidently specify hardware for any sensing or control application.

Common Pitfalls

Digital circuits generate high-frequency switching noise on the ground plane. Routing analog sensor signals over or near the digital ground plane couples this noise into ADC readings. In mixed-signal PCB designs, use separate analog (AGND) and digital (DGND) ground planes connected at a single star point near the ADC’s power supply pin.

Long wire lengths, capacitive loads, and inductive coupling that are acceptable in low-speed digital circuits destroy the performance of analog signal chains. Analog signal traces must be kept short (<5 cm where possible), isolated from digital traces, and guarded with ground pour to minimize capacitive coupling.

GPIO outputs from 3.3 V microcontrollers (ESP32, STM32) do not reliably drive 5 V logic inputs that require VIH > 3.5 V. Conversely, 5 V outputs connected to 3.3 V inputs can permanently damage 3.3 V ICs. Always verify voltage level compatibility from the datasheet and add level shifters or voltage dividers where needed.

The ADC’s reference voltage directly sets the full-scale range. Noise on the reference voltage (from sharing it with noisy digital power) appears directly in the ADC output. Use a dedicated low-noise voltage reference for precision ADC applications, or at minimum add a 10 uF + 100 nF decoupling network on the VREF pin.

14.9 What’s Next?

After completing this series, continue building your IoT skills with these topics:

Next Topic Description
Sensor Interfacing and Processing Apply ADC/DAC knowledge to connect and calibrate real IoT sensors
Sensor Labs Hands-on practice wiring ADC circuits and reading sensor data on ESP32
Networking Basics Transmit your digitized sensor data over IoT communication networks
SPI Communication Interface external ADC chips (MCP3008, ADS1115) via SPI bus
I2C Communication Connect precision I2C ADCs and DACs to microcontrollers

14.10 See Also

Related Electronics Topics:

Communication Protocols:

External Resources:

Start Learning: Binary Number Systems →