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
10.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.
10.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 10.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 10.2: Signal Conditioning Challenges and Solutions: Amplification, Filtering, ADC
10.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 10.3: Voltage Divider: Two resistors in series create a proportional output voltage based on their ratio.
Try it yourself! Use the voltage-divider calculator above to see how resistor ratios become measurable sensor voltages. Predict the output first, then move the sliders.
1. Start balanced
Set R1 = 10 kΩ and R2 = 10 kΩ. The output should be half of the supply voltage.
2. Make the sensor change
Lower R1 to model bright light on an LDR, then raise R1 to model darkness.
3. Connect the meaning
Watch the ADC count move with voltage. This is the number your microcontroller actually reads.
Design question: which resistor placement gives the largest voltage swing over the sensor's real resistance range?
Learning Points
Observe:
Voltage Division: Output voltage = Input × (R2 / (R1 + R2))
Variable Resistance: Changing R1 or R2 changes V_out proportionally
Current Flow: Same current flows through both resistors (series circuit)
Sensor Application: LDR or thermistor replaces one resistor, ADC reads V_out
Example Calculations:
With a 3.3 V supply and two equal 10 kOhm resistors, the output sits halfway at 1.65 V.
If the top resistor is an LDR and bright light drops it to 5 kOhm, the output rises to about 2.2 V.
If darkness raises the LDR to 20 kOhm, the output falls to about 1.1 V.
The important idea is not memorizing the arithmetic: the ADC number moves because the sensor changes the resistor ratio.
Real-World Application: Every analog sensor (LDR, thermistor, flex sensor, potentiometer) uses this circuit to interface with microcontroller ADCs.
10.3.2 LDR Voltage Divider Example
Figure 10.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.
10.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)
10.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)"})
Try it yourself! Use the RC filter calculator above to trade off noise rejection against response time. The goal is not “maximum filtering”; the goal is “enough filtering while still seeing the real sensor event.”
1. Baseline
Start with R = 10 kΩ and C = 100 nF. Notice the cutoff is about 159 Hz.
2. More filtering
Increase C to 1 µF. Noise rejection improves, but the sensor response becomes slower.
3. Too much filtering
Push R or C very high and ask whether a fast event would be delayed or missed.
Design question: for a sensor that changes every few seconds, what cutoff removes motor noise without hiding the real change?
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
Noise Filtering: Remove electrical noise from analog sensor readings
Debouncing: Smooth mechanical switch bounces
Anti-Aliasing: Filter high frequencies before ADC sampling
Smoothing: Reduce jitter in sensor measurements
Example: A 10 kOhm resistor with a 100 nF capacitor gives a time constant of 1 ms and a cutoff of about 159 Hz. That removes faster electrical noise while preserving slower sensor changes.
Pitfall: Missing Pull-Up Resistors on I2C Lines
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.
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.
10.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)
Guided Lab: NPN Transistor LED Switch
Try it yourself! Use the base-resistor calculator that follows this explanation. You are checking whether a tiny GPIO current can safely control a much larger load current.
1. Set a load
Use 200 mA for a small relay or LED strip segment. Keep GPIO at 3.3 V.
2. Change gain
Try beta = 100, then beta = 50. The required base current rises as transistor gain falls.
3. Check safety
Compare base current with the GPIO limit. If it is too high, use a MOSFET or driver stage.
Design question: can the microcontroller pin supply the needed base current with margin, or is a MOSFET the safer choice?
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)
Base Resistor: Limits base current to safe level
Current Gain (beta): A small base current controls a larger collector current. For example, a transistor with beta near 100 can let 0.1 mA at the base control about 10 mA through the load.
Why Use Transistors:
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)
Relay Drivers: Switch relays for AC loads
Solenoid Control: Activate locks, valves
Fan Control: PWM speed control
Design Rule: Choose the base resistor by subtracting the transistor’s base-emitter drop from the GPIO voltage, then dividing by the base current you need. In a real design, add margin because beta varies strongly between individual transistors and operating conditions.
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>`
10.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 (-)
10.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>`
Guided Lab: LED with Current Limiting Resistor
Try it yourself! Use the LED resistor calculator above to choose a safe resistor before connecting any real LED. This is the simplest place to see Ohm’s law prevent hardware damage.
1. Red LED at 5 V
Set supply = 5 V, LED forward voltage = 2 V, current = 20 mA. The answer should be about 150 Ω.
2. ESP32 at 3.3 V
Change supply to 3.3 V. The resistor gets much smaller because less voltage is left to drop.
3. Blue LED check
Try a 3 V blue LED on 3.3 V. Notice the small voltage margin and why brightness can be inconsistent.
Design question: which standard resistor value is safer when the calculated value falls between two real parts?
Learning Points
Observe:
Current Limiting: Resistor prevents excessive current that would destroy LED
Ohm’s Law: R = (V_supply - V_LED) / I_desired
Brightness: LED brightness proportional to current (up to max rating)
Power Dissipation: Resistor dissipates excess power as heat
Resistor Calculation:
With a 5 V supply, a red LED drop of about 2 V, and a 20 mA target current, the resistor needs to drop 3 V. Ohm’s Law gives 150 Ohm, and 150 Ohm or 220 Ohm are common safe choices.
With a 3.3 V ESP32 GPIO and the same red LED, the calculation gives about 65 Ohm. A 100 Ohm resistor is a common safer value because it lowers current and still leaves the LED visible.
Sensor Indicator Applications:
Status LEDs: Show sensor state (active, error, standby)
Threshold Indicators: Light up when sensor exceeds limit
Multi-Color RGB: Different colors for different conditions
Brightness Feedback: PWM LED brightness based on sensor reading
Common Mistakes:
No resistor → LED burns out immediately
Too small resistor → LED overheats, shortened life
Reverse polarity → LED doesn’t light, may damage LED
Correct calculation → Long LED life, proper brightness
10.7 Quick Reference Card
Reference Card: Component Values for Basic Sensor Circuits
Circuit Type
Component
Value
Purpose
Calculation
Voltage Divider (LDR)
R1 (Fixed)
10kΩ
Reference
Match LDR mid-range
Voltage Divider (Thermistor)
R1 (Fixed)
10kΩ
Reference
Match thermistor @ 25°C
RC Low-Pass Filter
Resistor
10kΩ
Filter
f_c = 1/(2πRC)
RC Low-Pass Filter
Capacitor
100nF
Filter
Example: 159 Hz cutoff
LED Current Limit (5V)
Resistor
220Ω
Protect LED
R = (5V-2V)/20mA
LED Current Limit (3.3V)
Resistor
100Ω
Protect LED
R = (3.3V-2V)/20mA
1-Wire Pull-up
Resistor
4.7kΩ
Signal level
DHT, DS18B20
I²C Pull-up
Resistor
4.7kΩ
Signal level
SCL, SDA lines
Button Pull-down
Resistor
10kΩ
Default state
Prevent floating input
Transistor Base
Resistor
1kΩ
Current limit
I_base = (V_GPIO - 0.7V)/R
Common Calculations:
Voltage Divider:
V_out = V_in × (R2 / (R1 + R2))
RC Filter Cutoff Frequency:
f_c (Hz) = 1 / (2π × R × C)
Example: 10kΩ × 100nF = 159 Hz
LED Resistor:
R = (V_supply - V_LED) / I_LED
Example: (5V - 2V) / 0.02A = 150Ω → use 220Ω
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!”
10.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:
Formula: output voltage equals supply voltage multiplied by sensor resistance, divided by the sum of pull-up resistance and sensor resistance.
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:
Formula: cutoff frequency equals 1 divided by 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:
Base-resistor calculation:
Required base current = 500 mA / 200 = 2.5 mA
Voltage across base resistor = 3.3 V - 0.7 V = 2.6 V
R_base = 2.6 V / 2.5 mA = 1,040 Ohm
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.
10.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
10.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.