Chapters

10 Sensor Circuits: Switching and Interface Safety

sensors
sensor
circuits

10.1 Start With the Decision

A GPIO pin can command a load but cannot safely feed it. A transistor and resistor must keep the control path within limits.

10.2 Route Overview

This is part 2 of 2. Review Sensor Circuits: Dividers and Filtering for the preceding evidence.

10.3 Learning Objectives

  • Size an NPN transistor switch and base resistor.
  • Check LED current, GPIO load, and interface margin.

10.4 Chapter Roadmap

  • Transistor Switch Circuit
  • Guided Lab: NPN Transistor LED Switch
  • Learning Points
  • Basic LED Circuit
  • Current-Limited LED Lab
  • Learning Points
  • Checkpoint: GPIO Load Safety
  • Quick Reference Card
  • Sensor Circuit Component Values
  • For Kids: Meet the Sensor Squad!
  • Checkpoint: Complete Interface Margin
  • Concept Relationships
  • Label the Diagram
  • Code Challenge
  • Resistive Dividers and ADC Load
  • Next Analog Input Practice
  • Summary
  • Key Takeaway
  • See Also
  • Common Pitfalls
  • 1. Wrong Pull-Up Resistor Value for I2C
  • Missing Sensor Decoupling
  • 3. Transistor Base Resistor Omission
  • Divider Resistor Range Mismatch
  • What’s Next

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:

Start with Current Amplification: Small base current (~1mA) controls large collector current (~20mA). Then Switching Action: Transistor acts as electronic switch (ON/OFF). Next Saturation Mode: When ON, V_CE ≈ 0.2V (fully conducting). Finally 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:

Start with Current Amplification: Microcontroller pin (12mA typical max) controls 500mA+ loads. Then Voltage Isolation: Separate power supply for load. Next Protection: Prevents damaging microcontroller with high-power loads. Finally 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:

Start with LED Drivers: Control high-power LEDs. Then Motor Control: Drive DC motors (with flyback diode). Next Relay Drivers: Switch relays for AC loads. After that Solenoid Control: Activate locks, valves. Finally 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.

10.5.1 Transistor Base Resistor Calculator

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

Current-Limited LED Lab

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:

Start with Current Limiting: Resistor prevents excessive current that would destroy LED. Then Ohm’s Law: R = (V_supply - V_LED) / I_desired. Next Brightness: LED brightness proportional to current (up to max rating). Finally Power Dissipation: Resistor dissipates excess power as heat.

Resistor Calculation:

Start by 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. Finally 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:

Start with Status LEDs: Show sensor state (active, error, standby). Then Threshold Indicators: Light up when sensor exceeds limit. Next Multi-Color RGB: Different colors for different conditions. Finally Brightness Feedback: PWM LED brightness based on sensor reading.

Common Mistakes:

Start by No resistor → LED burns out immediately. Then Too small resistor → LED overheats, shortened life. Next Reverse polarity → LED doesn’t light, may damage LED. Finally Correct calculation → Long LED life, proper brightness.

Physics PhoebeCheckpoint: GPIO Load Safety

You now know:

  • A 3.3 V GPIO with a 12 mA limit cannot drive a 200 mA motor directly, so the transistor stage supplies the load current.
  • With beta=100, the 200 mA motor example needs about 2 mA of base current and a 1.3k ohm base resistor.
  • LED resistors use the same discipline: 5 V, 3.2 V, and 20 mA gives 90 ohms, with 100 ohms as the nearest safe standard value.

The individual patterns are now in place. The rain-sensor design shows how they combine into one complete sensor-to-actuator chain.

10.7 Quick Reference Card

Circuit TypeComponentValuePurposeCalculation
Voltage Divider (LDR)R1 (Fixed)10kΩReferenceMatch LDR mid-range
Voltage Divider (Thermistor)R1 (Fixed)10kΩReferenceMatch thermistor @ 25°C
RC Low-Pass FilterResistor10kΩFilterf_c = 1/(2πRC)
RC Low-Pass FilterCapacitor100nFFilterExample: 159 Hz cutoff
LED Current Limit (5V)Resistor220ΩProtect LEDR = (5V-2V)/20mA
LED Current Limit (3.3V)Resistor100ΩProtect LEDR = (3.3V-2V)/20mA
1-Wire Pull-upResistor4.7kΩSignal levelDHT, DS18B20
I²C Pull-upResistor4.7kΩSignal levelSCL, SDA lines
Button Pull-downResistor10kΩDefault statePrevent floating input
Transistor BaseResistor1kΩCurrent limitI_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Ω

Transistor Base Resistor (NPN):

R_base = (V_GPIO - 0.7V) / (I_collector / β)
Example: (3.3V - 0.7V) / (100mA / 100) = 2.6kΩ → use 1kΩ
(Using lower value provides ~2.6× saturation margin for reliable switching)

Temperature Terry 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!”

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!”

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!”

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 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.

Given:

  • Rain sensor: Resistive rain sensor board (exposed PCB traces), resistance varies with wetness
    • Dry: >1 MOhm (essentially open circuit)
    • Light rain: 50-200 kOhm
    • Heavy rain: 2-20 kOhm
  • MCU: ESP32, 3.3V GPIO, 12-bit ADC (0-3.3V input)
  • 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_pullupV_out (dry, 1 MOhm)V_out (light rain, 100 kOhm)V_out (heavy rain, 10 kOhm)Current (heavy rain)
10 kOhm3.27V3.00V1.65V0.165 mA
47 kOhm3.15V2.24V0.58V0.058 mA
100 kOhm3.00V1.65V0.30V0.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)CCutoff Frequency20 kHz Attenuation
10 kOhm100 nF159 Hz-42 dB
10 kOhm1 uF16 Hz-62 dB
47 kOhm100 nF34 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

ComponentValueCost (EUR)Purpose
Rain sensor PCBCustom0.35Detect water on traces
R_pullup47 kOhm0.01Voltage divider
R_filter10 kOhm0.01RC filter
C_filter1 uF ceramic0.03RC filter
R_base1 kOhm0.01Transistor bias
2N2222ANPN transistor0.05Relay driver
1N4148Flyback diode0.02Relay coil protection
TotalEUR 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.

Physics PhoebeCheckpoint: Complete Interface Margin

You now know:

  • The 47 kOhm pull-up keeps the rain detector under the 0.5 mA budget while producing 3.15 V dry, 2.24 V light rain, and 0.58 V heavy rain.
  • The selected 10 kOhm and 1 uF RC filter has a 16 Hz cutoff and reduces 20 kHz motor noise by 62 dB.
  • The relay driver uses a 1 kOhm base resistor so the ESP32 can switch a 500 mA coil while the flyback diode protects the transistor.

10.8 Concept Relationships

This ConceptRelates ToRelationship Type
Voltage DividerOhm’s LawApplies V=IR with series resistors
RC FilterTime Constantτ=RC determines response speed
Cutoff FrequencyFilter Designfc=1/(2πRC) sets noise rejection point
Transistor SwitchCurrent Amplificationβ (beta) gain enables GPIO to control high power
LED ResistorCurrent LimitingOhm’s Law calculates safe resistor value
Label the Diagram
Code Challenge

10.9 Resistive Dividers and ADC Load

The main chapter above introduces the practical circuit blocks: voltage dividers, RC filters, transistor switches, and LED current limiting. The companion page goes deeper on the most common analog input pattern: resistive sensors, ratiometric dividers, source impedance, ADC sample windows, and loading effects.

Next Analog Input Practice

Continue with Resistive Dividers and ADC Loading to verify that a divider voltage is stable, ratiometric, and low-impedance enough for the ADC before trusting the code.

10.10 Summary

This chapter covered the essential circuit building blocks for sensor interfacing:

Start with Voltage Dividers: Convert resistance changes (from LDRs, thermistors) into voltage changes readable by ADCs. Then RC Filters: Remove high-frequency noise from sensor signals with simple passive components. Next Transistor Switches: Allow low-power GPIO pins to control high-power loads like motors and relays. Finally 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.

10.11 Key Takeaway

Sensor circuits should preserve the physical signal clearly enough for measurement: excitation, biasing, filtering, amplification, conversion, and protection must match the sensor and environment.

10.12 See Also

Start with Electricity Fundamentals - Voltage, current, resistance, Ohm’s Law. Then Electronics Fundamentals - Semiconductors, transistors, diodes. Next Analog and Digital Electronics - ADC conversion fundamentals. After that Sensor Fundamentals - Sensor specifications and types. Finally Signal Conditioning - Advanced amplification techniques.

Common Pitfalls

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.

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.

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.

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.

10.13 What’s Next

ChapterDescription
Resistive Dividers and ADC LoadingRatiometric dividers, thermistor/LDR conversion, source impedance, sample time, and ADC loading
Signal ConditioningWheatstone bridges, instrumentation amplifiers, and the complete signal conditioning chain
Sensor Interfacing and ProcessingConnecting sensors to microcontrollers via ADC, I2C, SPI, and UART interfaces
Sensor Fundamentals and TypesSurvey of sensor categories, specifications, and selection criteria for IoT applications
Electricity FundamentalsReview voltage, current, resistance, and Ohm’s Law that underpin every circuit in this chapter
Analog and Digital ElectronicsADC resolution, sampling rates, and digital-to-analog conversion principles

10.14 Continue Your Route

This final part closes the route from Transistor Switch Circuit through What’s Next. Return to Sensor Circuits: Dividers and Filtering or continue from the sensors module index.