10 Sensor Circuits: Switching and Interface Safety
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
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.
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.
Use 200 mA for a small relay or LED strip segment. Keep GPIO at 3.3 V.
Try beta = 100, then beta = 50. The required base current rises as transistor gain falls.
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?
10.5.1 Transistor Base Resistor Calculator
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
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.
Set supply = 5 V, LED forward voltage = 2 V, current = 20 mA. The answer should be about 150 Ω.
Change supply to 3.3 V. The resistor gets much smaller because less voltage is left to drop.
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?
This section:
Checkpoint: 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 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 | I = (5V-2V)/220Ω ≈ 13.6mA |
| LED Current Limit (3.3V) | Resistor | 100Ω | Protect LED | I = (3.3V-2V)/100Ω = 13mA |
| 1-Wire Pull-up | Resistor | 4.7kΩ | Signal level | DS18B20; DHT uses a different single-wire protocol |
| 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Ω
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_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. 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) | 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 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
| 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 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:
Checkpoint: 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 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 |
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.
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
- Electricity Fundamentals - Voltage, current, resistance, Ohm’s Law.
- Electronics Fundamentals - Semiconductors, transistors, diodes.
- Analog and Digital Electronics - ADC conversion fundamentals.
- Sensor Fundamentals - Sensor specifications and types.
- Signal Conditioning - Advanced amplification techniques.
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
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 pathsReviewed
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 stuckReviewed
How do interactive examples work?
Use the interactive guide to check how examples and simulations work before changing your project.
Interactive examples guideReviewed
