10 Sensor Circuits: Switching and Interface Safety
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)
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
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?
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, 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 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Ω
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_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.
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 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 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
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 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
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.
