Chapters

10 Sensor Circuits: Switching and Interface Safety

sensors
sensor
circuits

10.1 Start With the Decision

This section: Start With the Decision — A GPIO pin is a software-controlled signal pin.

A GPIO pin is a software-controlled signal pin. It can power a small load within its voltage and current ratings. For a larger load, a transistor carries the load current while the pin commands it. A resistor limits current in the control path. Check both parts against their ratings.

10.2 Route Overview

This section: Route Overview — This is part 2 of 2.

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

10.3 Learning Objectives

This section: Learning Objectives

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

10.4 Chapter Roadmap

This section: 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

This section: Transistor Switch Circuit — Theory: Transistors act as electronic switches, allowing low-power microcontroller pins to control high-power loads (LEDs, motors, relays).

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:

  • A forward-biased base-emitter junction with sufficient base current can turn the transistor ON. About 0.7 V across base-emitter is a useful rule of thumb for silicon BJTs, but the value varies with device, current, and temperature.
  • Removing base drive turns the transistor OFF apart from leakage current.
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: A GPIO limited to about 12 mA can switch a 500 mA load through a suitably rated driver; size base drive from the transistor’s saturation data, not active-region gain alone.
  • Separate Load Supply: The load can have its own supply if the grounds and ratings are handled correctly.
  • Protection: A suitably rated driver and flyback path protect the controller.
  • Efficiency: Saturation can reduce transistor power loss.

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. The data-sheet forced current ratio at the intended collector current, not the active-region beta, determines a saturated switch design. Check that the GPIO can supply that base current; otherwise choose a suitable MOSFET or driver.

10.5.1 Transistor Base Resistor Calculator

Check your understanding: Use the questions below to check the key idea

10.6 Basic LED Circuit

This section: Basic LED Circuit — Theory: LEDs (Light Emitting Diodes) require current limiting resistors to prevent burnout.

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:

  • 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:

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:

  • 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:

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.

Check your understanding: Use the questions below to check the key idea Check your understanding: Use the questions below to check the key idea

This section:

Physics Phoebe, Physics and measurement-foundations expertCheckpoint: 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, 2 mA and 1.3k ohm are only active-region estimates for the 200 mA motor example; use the data-sheet forced ratio and GPIO limit to select a switch.
  • 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

This section: 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 LEDI = (5V-2V)/220Ω ≈ 13.6mA
LED Current Limit (3.3V)Resistor100ΩProtect LEDI = (3.3V-2V)/100Ω = 13mA
1-Wire Pull-upResistor4.7kΩSignal levelDS18B20; DHT uses a different single-wire protocol
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 - V_BE) / I_base
Example: for a 20mA load and a data-sheet forced ratio of 10,
I_base ≥ 20mA / 10 = 2mA; with assumed V_BE = 0.7V,
R_base ≤ (3.3V - 0.7V) / 2mA = 1.3kΩ → use 1kΩ
(Check actual GPIO and transistor ratings; active-region β is not a saturation specification.)

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

Illustrative scenario: A robotic mower needs to detect rain onset within 5 seconds and signal its controller to return to a charging station.

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; usable input range depends on attenuation and calibration
  • 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. The calculations below treat the 10 kOhm resistor as the filter’s whole source resistance; an unbuffered divider adds its Thevenin resistance and changes the cutoff and settling time:

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 ideal RC stage: R = 10 kOhm, C = 1 uF (cutoff ≈ 15.9 Hz), attenuating a 20 kHz sinusoid by about 62 dB. With the 47 kOhm/10 kOhm divider connected directly, its 8.25 kOhm Thevenin resistance adds to the filter resistance: the effective time constant is about 18.25 ms and the cutoff about 8.72 Hz. Verify actual ADC acquisition loading and the required rain-detection latency in the assembled circuit.

Step 3: Design the return-to-station transistor driver

When rain is detected, the MCU activates an illustrative 20 mA relay coil to signal the controller. Assume a GPIO base-current budget of 12 mA for this worked example; check the chosen MCU’s actual output rating:

Base-resistor calculation:

  • Required base current for a forced ratio of 10 = 20 mA / 10 = 2 mA
  • Voltage across base resistor = 3.3 V - 0.7 V = 2.6 V
  • Maximum R_base at that current = 2.6 V / 2 mA = 1,300 Ohm

Selected: R_base = 1 kOhm, 2N2222A transistor. Under the stated 0.7 V base-emitter assumption, the GPIO supplies about 2.6 mA of base current, giving a forced ratio of 20/2.6 ≈ 7.7 for the 20 mA relay coil. Check the actual transistor, GPIO, relay, and flyback diode ratings before building the circuit.

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 for these illustrative values: The listed component prices sum to EUR 0.48, the heavy-rain divider draws about 0.058 mA, and an ideal 10 kOhm/1 uF filter attenuates a 20 kHz sine wave by about 62 dB. Relay response and total standby current depend on the actual hardware and firmware. The example combines a voltage divider, RC filter, transistor switch, and protection diode.

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.

This section:

Physics Phoebe, Physics and measurement-foundations expertCheckpoint: 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 illustrative 20 mA relay driver uses a 1 kOhm base resistor; verify GPIO, transistor, relay, and flyback diode ratings for the actual parts.

10.8 Concept Relationships

This section: 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

This section: 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 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 section: Summary — These fundamental circuits form the building blocks for more complex signal conditioning chains covered in the next chapter.

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.

10.11 Key Takeaway

This section: 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.

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

This section: See Also

Common Pitfalls

This section: Common Pitfalls

I2C requires pull-up resistors on SDA and SCL. As a 3.3 V, 3 mA sink-current rule of thumb, values above about 10 kohm can give edges that are too slow, while values below about 1 kohm can exceed the sink-current limit. Choose each value from the bus capacitance, permitted rise time, supply voltage, and devices’ low-level sink-current limits. Values such as 4.7 kohm at 100 kHz or 2.2 kohm at 400 kHz are starting examples, not guarantees; measure rise time and LOW voltage on the assembled bus.

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

This section: 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 section: Continue Your Route — This is the last part of this chapter.

This is the last part of this chapter. Return to Sensor Circuits: Dividers and Filtering or continue from the sensors module index.

Find help

3 reviewed answers.

Where should I start in a module?

Open the module page from the sidebar to see its chapters in order. Use the module map to return to a topic you need.

Modules and paths

Reviewed

What can I try when a project does not work?

Check the symptom, then work through the diagnostic steps. Keep the error message and the smallest example that reproduces it.

When you are stuck

Reviewed

How do interactive examples work?

Use the interactive guide to check how examples and simulations work before changing your project.

Interactive examples guide

Reviewed