Sensor circuit fundamentals cover four essential building blocks: voltage dividers (convert resistance changes from LDRs and thermistors into measurable voltages), RC filters (remove high-frequency electrical noise using a resistor-capacitor pair), transistor switches (let low-power microcontroller pins control high-power loads like motors and relays), and LED current-limiting circuits (protect LEDs from burnout). These four patterns solve the vast majority of sensor-to-microcontroller interfacing challenges.
Key Concepts
Voltage Divider: A two-resistor circuit where the output voltage is proportional to the ratio of resistor values; the foundation for reading resistive sensors like thermistors and LDRs
Pull-Up Resistor: A resistor connecting a signal line to the supply voltage, defining the default HIGH state for open-drain digital sensors and I2C lines
Pull-Down Resistor: A resistor connecting a signal line to ground, defining the default LOW state and preventing floating inputs on buttons and digital sensor outputs
RC Low-Pass Filter: Resistor and capacitor combination with cutoff fc = 1/(2piRC); attenuates electrical noise above the cutoff frequency while passing the sensor signal
Transistor Switch: A bipolar or MOSFET transistor used as a digitally-controlled switch, allowing a low-current GPIO pin to control higher-current loads
LED Current Limiting Resistor: A series resistor calculated as R = (Vsupply - Vf) / If that prevents LED overcurrent; always required — LEDs have no self-limiting resistance
Decoupling Capacitor: A 100 nF ceramic capacitor placed close to a sensor’s VCC pin to filter power supply noise and prevent it from coupling into analog readings
Ground Loop: A condition where multiple ground connections create different potentials, introducing voltage offsets and noise into sensor measurements; prevented by star-topology single-point grounding
23.1 Learning Objectives
By the end of this chapter, you will be able to:
Design Voltage Dividers: Calculate resistor values for interfacing resistive sensors with ADCs
Build RC Filters: Create low-pass filters to remove noise from sensor signals
Implement Transistor Switches: Use transistors to control high-power loads from GPIO pins
Calculate LED Resistors: Properly size current-limiting resistors for LED indicators
Debug Basic Circuits: Use multimeters to diagnose common sensor circuit issues
For Beginners: Sensor Circuits
Sensor circuits are the wiring and small components that connect a sensor to a microcontroller. Think of it like plumbing – you need the right pipes (wires), valves (resistors), and filters to get clean water (signal) from the source (sensor) to the tap (microcontroller). Without these circuit building blocks, the sensor’s signal would be too weak, too noisy, or at the wrong voltage for the microcontroller to read properly.
23.2 Introduction
Sensor circuits form the critical bridge between the physical world and digital microcontrollers. A sensor might detect temperature, light, or motion, but its raw electrical output – a changing resistance, a tiny voltage, or a noisy analog signal – is rarely in a form the microcontroller can use directly. This chapter teaches you the four fundamental circuit patterns that solve this problem: voltage dividers, RC filters, transistor switches, and LED current-limiting circuits. Together, these building blocks handle the vast majority of sensor-to-microcontroller interfacing needs in IoT systems like the ESP32.
How It Works: Essential Sensor Circuit Building Blocks
Sensor circuits use four fundamental patterns to connect sensors to microcontrollers:
Step 1: Voltage Divider (Resistive Sensors)
Two resistors in series divide input voltage proportionally
Formula: Vout = Vin × (R2 / (R1 + R2))
LDR or thermistor acts as variable resistor R1
Result: Resistance changes become voltage changes ADC can measure
Step 2: RC Filter (Noise Removal)
Resistor + capacitor create time constant: τ = R × C
High frequencies pass through capacitor to ground (attenuated)
Low frequencies (sensor signal) pass through to output smoothly
Result: Clean signal with 60Hz motor noise removed
Step 3: Transistor Switch (Load Control)
Small base current (2mA from GPIO) controls large collector current (500mA to motor)
Current gain β amplifies: I_collector = β × I_base
Master these four patterns and you can interface 90% of IoT sensors and actuators.
What Are Sensor Circuits? (Simple Explanation)
Analogy: Think of sensor circuits like translating between languages.
Imagine you speak English, but your friend only speaks French. You need: 1. A translator (to convert the language) 2. Volume adjustment (if they whisper too quietly) 3. Noise filtering (to ignore background chatter)
Sensor circuits work the same way—they convert sensor “language” (analog voltages) into “microcontroller language” (digital numbers)!
Figure 23.1: Sensor Signal Conditioning Pipeline: Amplification, Filtering, and ADC Conversion
The Three Main Challenges
When connecting a sensor to a microcontroller, you face three problems:
Challenge
Real-World Example
Solution
Signal too weak
Thermistor outputs only 0.01V change
Amplification - Boost the signal
Signal too noisy
Electrical interference from motors
Filtering - Remove the noise
Wrong format
Sensor speaks analog, MCU needs digital
ADC Conversion - Translate it
Figure 23.2: Signal Conditioning Challenges and Solutions: Amplification, Filtering, ADC
23.3 Voltage Divider Circuit
Theory: A voltage divider is the most fundamental circuit for interfacing resistive sensors (LDR, thermistors, potentiometers) with microcontrollers. It converts resistance changes into voltage changes that ADCs can measure.
Voltage Divider Circuit
Figure 23.3: Voltage Divider: Two resistors in series create a proportional output voltage based on their ratio.
Real-World Application: Every analog sensor (LDR, thermistor, flex sensor, potentiometer) uses this circuit to interface with microcontroller ADCs.
23.3.2 LDR Voltage Divider Example
Figure 23.4: LDR Voltage Divider: Light-to-Voltage Conversion Circuit
Real-World Applications:
Automatic Street Lights: Turn on when ambient light falls below threshold
Display Brightness: Adjust screen based on room lighting (phones, tablets)
Solar Panel Tracking: Detect sun position for maximum efficiency
Camera Exposure: Measure ambient light for automatic settings
Smart Blinds: Open/close based on sunlight intensity
Putting Numbers to It
LDR Voltage Divider Design: An LDR varies from 200Ω (bright sunlight) to 10kΩ (darkness). Design a voltage divider with 3.3V supply to maximize ADC range (0-3.3V).
Option 1: LDR on top, 10kΩ fixed resistor on bottom
Voltage at midpoint: \[
V_{out} = V_{in} \times \frac{R_{bottom}}{R_{top} + R_{bottom}}
\]
Voltage range: 0.55V to 3.0V → 2.45V span (74% of ADC range) ✓ Better!
Key insight: Place the variable resistor (sensor) on the bottom of the voltage divider for maximum voltage swing. Fixed resistor value should be near the geometric mean of sensor range: \(\sqrt{200 \times 10{,}000} = 1{,}414\Omega\) → use 1kΩ standard value.
23.4 RC (Resistor-Capacitor) Filter Circuit
Theory: RC circuits create time delays and filter signals. Essential for debouncing switches, filtering sensor noise, and creating timing circuits.
Time Constant:τ = R × C (tau, in seconds)
Cutoff Frequency:f_c = 1 / (2πRC)
23.4.1 RC Filter Calculator
Show code
viewof rc_r = Inputs.range([100,100000], {value:10000,step:100,label:"Resistance R (Ω)"})viewof rc_c_nF = Inputs.range([1,10000], {value:100,step:1,label:"Capacitance C (nF)"})
The Mistake: Connecting I2C sensors directly to microcontroller GPIO pins without external pull-up resistors, relying solely on internal weak pull-ups (40-100kohm typical).
Why It Happens: Many tutorials skip pull-up resistors because simple single-sensor setups “work” with internal pull-ups. Developers assume if it works on the bench, it will work in production.
The Fix: Always install external pull-up resistors on SDA and SCL lines:
Standard I2C (100kHz): Use 4.7kohm pull-ups to 3.3V
Fast I2C (400kHz): Use 2.2kohm pull-ups to 3.3V
Multiple sensors or long wires (>30cm): Use 1kohm pull-ups
Calculation: Pull-up value = Rise Time / (0.8473 x Bus Capacitance). For 400kHz with 100pF total capacitance: R = 300ns / (0.8473 x 100pF) = 3.5kohm (use 2.2kohm standard value).
Symptoms of weak pull-ups: Intermittent communication failures, sensors work individually but not together, communication fails in humid/hot environments, NACK errors at higher clock speeds.
Interactive Circuit: RC Low-Pass Filter
Try it yourself! See how RC circuits filter high-frequency noise from sensor signals.
What This Simulates: An RC low-pass filter that smooths noisy sensor readings.
How to Use:
Click RUN/Stop button to start
Observe the input square wave (top oscilloscope trace)
See the filtered output (bottom trace) - sharp edges smoothed
Right-click resistor/capacitor to change values
Watch how time constant affects filtering
Learning Points
Observe:
Low-Pass Filtering: High frequencies (noise) blocked, low frequencies (signal) pass through
Time Constant τ: Larger R or C = slower response, more filtering
Filters out noise above 159Hz, preserving slower sensor changes.
Tradeoff: Hardware Filtering vs Software Filtering
Option A (Hardware RC Filter): Cutoff frequency fixed at design time (f_c = 1/(2piRC)), no CPU overhead, power consumption adds 0.01–0.1 mW, cost $0.05–0.50 for resistor/capacitor. Provides true anti-aliasing before ADC, removes high-frequency noise physically. Cannot be adjusted after deployment, requires PCB space, component tolerance affects cutoff (+-10–20%).
Option B (Software Digital Filter): Cutoff frequency adjustable in code, CPU overhead 0.1–2% per filter, no additional power for passive filtering but adds MCU active time. No BOM cost increase. Allows adaptive filtering based on conditions, can implement complex filters (Kalman, median). Cannot remove aliased frequencies (must sample fast enough), adds latency of N/2 samples for N-tap filter.
Decision Factors: Choose hardware filtering when noise frequencies exceed half your sampling rate (prevents aliasing that software cannot fix), when CPU resources are constrained, or when EMI/RFI is severe (motor noise, switching power supplies). Choose software filtering when filter characteristics need runtime adjustment, when implementing complex filters like Kalman or adaptive algorithms, when PCB space is limited, or when different filtering is needed for different operating modes.
23.5 Transistor Switch Circuit
Theory: Transistors act as electronic switches, allowing low-power microcontroller pins to control high-power loads (LEDs, motors, relays). Essential for driving actuators.
NPN Transistor Operation:
Base voltage > 0.7V → Transistor ON (collector-emitter conducts)
Base voltage < 0.7V → Transistor OFF (no conduction)
Interactive Circuit: NPN Transistor LED Switch
Try it yourself! See how transistors amplify signals to control loads.
What This Simulates: An NPN transistor switching an LED on/off, controlled by a small base current.
How to Use:
Click RUN/Stop button
Click the switch (bottom left) to toggle base current
Watch the LED turn on/off
Observe current flow through the transistor
Right-click transistor to see β (current gain)
Learning Points
Observe:
Current Amplification: Small base current (~1mA) controls large collector current (~20mA)
Switching Action: Transistor acts as electronic switch (ON/OFF)
Saturation Mode: When ON, V_CE ≈ 0.2V (fully conducting)
Current Amplification: Microcontroller pin (12mA typical max) controls 500mA+ loads
Voltage Isolation: Separate power supply for load
Protection: Prevents damaging microcontroller with high-power loads
Efficient: Minimal power loss in saturation
Important: When driving inductive loads (motors, relays, solenoids), always add a flyback diode (e.g., 1N4148) reverse-biased across the load. When the transistor switches off, the inductor generates a high-voltage spike that can destroy the transistor without this protection.
Sensor-Actuator Applications:
LED Drivers: Control high-power LEDs
Motor Control: Drive DC motors (with flyback diode)
tr_vbe =0.7tr_ib_mA = tr_ic_mA / tr_betatr_rbase = (tr_vgpio - tr_vbe) / (tr_ib_mA /1000)html`<div style="background: var(--bs-light, #f8f9fa); padding: 1rem; border-radius: 8px; border-left: 4px solid #E67E22; margin-top: 0.5rem;"><p><strong>Required Base Current:</strong> I_base = ${tr_ic_mA.toFixed(0)} mA / ${tr_beta.toFixed(0)} = <strong>${tr_ib_mA.toFixed(2)} mA</strong></p><p><strong>Base Resistor:</strong> R_base = (${tr_vgpio.toFixed(1)} - 0.7) / ${tr_ib_mA.toFixed(2)} mA = <strong>${tr_rbase.toFixed(0)} Ω</strong></p><p><strong>GPIO Current Check:</strong> ${tr_ib_mA <=12?"✓ Safe for ESP32 GPIO ("+ tr_ib_mA.toFixed(2) +" mA < 12 mA limit)":"⚠ Exceeds ESP32 GPIO limit of 12 mA! Use a Darlington pair or MOSFET."}</p><p><strong>Power in Base Resistor:</strong> ${((tr_vgpio - tr_vbe) * tr_ib_mA /1000*1000).toFixed(2)} mW</p></div>`
23.6 Basic LED Circuit
Theory: LEDs (Light Emitting Diodes) require current limiting resistors to prevent burnout. Understanding LED circuits is fundamental to building indicator lights and displays.
LED Characteristics:
Forward Voltage (V_f): ~2V (red), ~3V (blue/white)
Forward Current (I_f): 20mA typical
Polarity: Anode (+) to cathode (-)
23.6.1 LED Resistor Calculator
Show code
viewof led_vsupply = Inputs.range([1.8,12], {value:3.3,step:0.1,label:"Supply Voltage (V)"})viewof led_vf = Inputs.range([1.0,4.0], {value:2.0,step:0.1,label:"LED Forward Voltage V_f (V)"})viewof led_if_mA = Inputs.range([1,30], {value:20,step:1,label:"Desired LED Current (mA)"})
Show code
led_vdrop = led_vsupply - led_vfled_valid = led_vdrop >0led_r = led_valid ? led_vdrop / (led_if_mA /1000) :0led_power_mW = led_valid ? led_vdrop * led_if_mA :0led_standard =!led_valid ?0: led_r <=56?56: led_r <=68?68: led_r <=82?82: led_r <=100?100: led_r <=120?120: led_r <=150?150: led_r <=180?180: led_r <=220?220: led_r <=270?270: led_r <=330?330: led_r <=470?470: led_r <=560?560: led_r <=680?680: led_r <=1000?1000:Math.ceil(led_r /100) *100html`<div style="background: var(--bs-light, #f8f9fa); padding: 1rem; border-radius: 8px; border-left: 4px solid #E74C3C; margin-top: 0.5rem;">${led_valid ?html`<p><strong>Voltage Across Resistor:</strong> ${led_vsupply.toFixed(1)} - ${led_vf.toFixed(1)} = ${led_vdrop.toFixed(1)} V</p><p><strong>Calculated Resistor:</strong> R = ${led_vdrop.toFixed(1)} V / ${led_if_mA.toFixed(0)} mA = <strong>${led_r.toFixed(0)} Ω</strong></p><p><strong>Nearest Standard Value:</strong> ${led_standard} Ω</p><p><strong>Resistor Power Dissipation:</strong> ${led_power_mW.toFixed(1)} mW${led_power_mW >250?" -- Use 1/2W resistor!":""}</p>`:html`<p><strong>Supply voltage (${led_vsupply.toFixed(1)} V) must exceed LED forward voltage (${led_vf.toFixed(1)} V).</strong> Increase supply voltage or choose a different LED.</p>`}</div>`
Interactive Circuit: LED with Current Limiting Resistor
Try it yourself! Learn how to properly drive LEDs with current limiting.
What This Simulates: An LED circuit with adjustable current-limiting resistor.
Sammy the Sensor was teaching a class about sensor circuits, and the whole squad was paying attention!
“Today we’re learning the four superpowers of sensor circuits!” Sammy announced.
“Superpower #1: The VOLTAGE DIVIDER!” Sammy held up two resistors. “Imagine a water slide with two pools. Water flows from the top, fills the first pool (that’s resistor 1), then flows into the second pool (resistor 2), then goes to the ground. The water level between the pools changes based on how big each pool is. That’s exactly how voltage dividers work! When I’m an LDR (light sensor), my resistance changes with light, so the voltage in the middle changes too!”
Lila the LED demonstrated superpower #2: “The RC FILTER! Picture a sponge in a stream. Fast splashes (high-frequency noise) get absorbed by the sponge, but the slow, steady flow of water (your real signal) passes right through. The resistor is like the narrow path, and the capacitor is like the sponge. Together, they clean up messy signals!”
Max the Microcontroller showed superpower #3: “The TRANSISTOR SWITCH! My GPIO pins are like a small child – they can push a light doorbell button (small current), but they can’t push open a heavy door (big current). A transistor is like having a grown-up helper: the child pushes a small button (base current), and the grown-up opens the heavy door (collector current). That’s how I control big motors and relays!”
Bella the Battery covered superpower #4: “The LED RESISTOR! Lila here needs exactly the right amount of current – too much and she burns out! The current-limiting resistor is like a speed bump on a road. It slows down the current to exactly the right speed. Without it, current rushes in too fast and – POP! – no more LED.”
“And that’s it!” Sammy concluded. “Four simple building blocks, and you can connect almost any sensor to any microcontroller. Now go build something amazing!”
23.7.1 Worked Example: Husqvarna Robotic Lawnmower Rain Sensor Circuit Design
Scenario: Husqvarna is designing a rain detection circuit for the Automower 450X robotic lawnmower. The sensor must detect rain onset within 5 seconds so the mower can return to its charging station before the wet grass causes wheel slippage and mowing quality degradation.
Power budget: Sensor must consume less than 0.5 mA average (to preserve mower battery)
Noise environment: Motor EMI generates 50 mV spikes at 20 kHz switching frequency
Step 1: Design the voltage divider
The rain sensor is a variable resistor. A fixed pull-up resistor creates a voltage divider:
V_out = V_supply x R_sensor / (R_pullup + R_sensor)
R_pullup
V_out (dry, 1 MOhm)
V_out (light rain, 100 kOhm)
V_out (heavy rain, 10 kOhm)
Current (heavy rain)
10 kOhm
3.27V
3.00V
1.65V
0.165 mA
47 kOhm
3.15V
2.24V
0.58V
0.058 mA
100 kOhm
3.00V
1.65V
0.30V
0.030 mA
Selected: R_pullup = 47 kOhm. This provides good voltage range (3.15V to 0.58V across rain conditions) while keeping current well under the 0.5 mA budget.
Step 2: Design the RC noise filter
The motor EMI noise at 20 kHz must be filtered. The rain signal changes slowly (seconds), so a low cutoff frequency is acceptable:
Cutoff frequency = 1 / (2 x pi x R x C)
R (series)
C
Cutoff Frequency
20 kHz Attenuation
10 kOhm
100 nF
159 Hz
-42 dB
10 kOhm
1 uF
16 Hz
-62 dB
47 kOhm
100 nF
34 Hz
-55 dB
Selected: R = 10 kOhm, C = 1 uF (cutoff = 16 Hz). This attenuates 20 kHz motor noise by 62 dB (reducing 50 mV spikes to 0.04 mV – far below the ADC’s 0.8 mV step size). The 16 Hz cutoff still responds to rain onset within 100 ms.
Step 3: Design the return-to-station transistor driver
When rain is detected, the MCU must activate a high-current relay (500 mA coil) to engage the homing navigation. The GPIO pin can only source 12 mA:
Selected: R_base = 1 kOhm (nearest standard value), NPN transistor 2N2222A (rated 800 mA continuous). The GPIO drives 2.6 mA into the base, which switches 500 mA through the relay coil.
Step 4: Complete circuit bill of materials
Component
Value
Cost (EUR)
Purpose
Rain sensor PCB
Custom
0.35
Detect water on traces
R_pullup
47 kOhm
0.01
Voltage divider
R_filter
10 kOhm
0.01
RC filter
C_filter
1 uF ceramic
0.03
RC filter
R_base
1 kOhm
0.01
Transistor bias
2N2222A
NPN transistor
0.05
Relay driver
1N4148
Flyback diode
0.02
Relay coil protection
Total
EUR 0.48
Result: The complete rain detection circuit costs EUR 0.48 in components, consumes 0.058 mA in standby (light rain threshold monitoring), rejects motor EMI noise by 62 dB, and can activate the homing relay within 100 ms of rain detection. All four fundamental circuit patterns (voltage divider, RC filter, transistor switch, and protection diode) are used in a single practical design.
Key Insight: These four circuit building blocks – voltage divider, RC filter, transistor switch, and protection components – appear together in nearly every sensor interface. The design sequence is always the same: (1) convert the sensor’s electrical change into a voltage the ADC can read, (2) filter noise before the ADC, (3) amplify or switch the output signal if needed. Total BOM cost under EUR 0.50 for a complete sensor-to-actuator signal chain.
23.8 Concept Relationships
This Concept
Relates To
Relationship Type
Voltage Divider
Ohm’s Law
Applies V=IR with series resistors
RC Filter
Time Constant
τ=RC determines response speed
Cutoff Frequency
Filter Design
fc=1/(2πRC) sets noise rejection point
Transistor Switch
Current Amplification
β (beta) gain enables GPIO to control high power
LED Resistor
Current Limiting
Ohm’s Law calculates safe resistor value
🏷️ Label the Diagram
Code Challenge
23.9 Summary
This chapter covered the essential circuit building blocks for sensor interfacing:
Voltage Dividers: Convert resistance changes (from LDRs, thermistors) into voltage changes readable by ADCs
RC Filters: Remove high-frequency noise from sensor signals with simple passive components
Transistor Switches: Allow low-power GPIO pins to control high-power loads like motors and relays
LED Circuits: Properly calculate current-limiting resistors to protect LEDs and indicate sensor states
These fundamental circuits form the building blocks for more complex signal conditioning chains covered in the next chapter.
I2C requires pull-up resistors on SDA and SCL. Too large a value (>10 kohm) slows rise time and causes errors at 400 kHz. Too small (<1 kohm) wastes current. Use 4.7 kohm for 100 kHz, or 2.2 kohm for 400 kHz operation.
2. Missing Decoupling Capacitors on Sensor Power
Without a 100 nF bypass capacitor close to the sensor’s VCC pin, supply transients couple directly into the analog signal, causing noisy readings. Place the capacitor within 10 mm of the sensor power pin.
3. Transistor Base Resistor Omission
Connecting a GPIO directly to a transistor base without a series resistor can draw excessive base current, potentially damaging the GPIO. Calculate the base resistor to keep base current within the GPIO’s output current rating.
4. Voltage Divider Fixed Resistor Mismatched to Sensor Range
For a thermistor divider, the fixed resistor should be near the sensor’s midrange resistance. If too different, the voltage swing across the operating temperature range is compressed and ADC resolution is wasted. Choose the fixed resistor near the geometric mean of the sensor’s resistance range.