Chapters

9 Electronics: Controller Design and Review

electronics-controller-design

9.1 Start With the Decision

A fan controller joins sensing, code, drive current, and a safe stop. The review must test the whole path.

9.2 Route Overview

This is part 2 of 2. Review Electronics: Power and Transistor Switching for the preceding evidence.

9.3 Learning Objectives

  • Review a smart fan controller from input to load.
  • Check transistor choice, serial buses, and failure states.

9.4 Chapter Roadmap

  • Checkpoint: Switching Loads
  • Concept Check: Transistor Selection
  • Concept Relationships
  • Knowledge Check
  • See Also
  • Smart Fan Controller Design
  • Checkpoint: Fan Controller Review
  • Phoebe’s Field Notes: Why the Fan Circuit Needs the Math
  • Electronics Term Matching
  • Electronics Progression Quiz
  • Label the Diagram
  • What’s Next
  • Quick Access
  • For Kids: Meet the Sensor Squad!
  • BJT vs MOSFET Resistors
  • Key Takeaway
  • Code Challenge
  • Design Contract: Serial Bus Interfaces
  • Summary
Voltage VeraCheckpoint: Switching Loads

You now know:

  • A 3.3V ESP32 GPIO cannot directly supply a 100mA LED load, a 30mA relay coil, or a 500mA motor.
  • A BJT needs base current, while a MOSFET gate draws essentially zero steady-state current but still needs a datasheet check at the available gate voltage.
  • Inductive loads need a flyback diode: the relay example uses a 1N4001, and the motor example upgrades to a 1N5819 Schottky.

9.4.1 MOSFET Power Dissipation Calculator

Use this calculator to estimate power dissipation and determine whether a heatsink is needed for your MOSFET switching circuit.

9.5 Concept Relationships

Electronics Fundamentals

ConceptRelates ToRelationship
DopingConductivityAdding impurities (P or N type) increases semiconductor conductivity by orders of magnitude
PN JunctionDiodeTwo doped layers (P+N) form a diode - the fundamental building block of all semiconductors
TransistorDiodeA transistor is two PN junctions back-to-back (NPN or PNP), forming a controllable switch
BJT Base CurrentCollector CurrentIc = β × Ib (current gain typically 100-300); base current controls collector current
MOSFET Gate VoltageDrain CurrentVoltage-controlled; Id flows when Vgs > Vgs(th); essentially zero gate current (<1µA)
Power DissipationHeatP = V × I (BJT) or I² × Rds(on) (MOSFET); >500mW requires heatsinking

Cross-module connection: Electronics principles connect to Sensor Circuits for signal conditioning, Actuator Control for motor/relay driving, and Power Management for voltage regulation and battery optimization.


9.6 Knowledge Check

Quiz: Electronics Fundamentals

9.7 See Also

Related Content Across Modules

Within This Module (Physical World):

Follow these connections in order: Sensor Circuits and Signals - Apply transistors to sensor signal conditioning; Actuators Overview - Motor drivers, relays, solenoids using power MOSFETs; Sensor Labs - Hands-on ESP32 circuit building.

Fundamentals (Module 1):

Follow these connections in order: Electricity Fundamentals - Voltage, current, resistance prerequisites; Signal Processing - Analog/digital conversion builds on transistor circuits.

Engineering & Power (Module 9):

Follow these connections in order: Power Management - Voltage regulators and DC-DC converters (made of transistors!); Energy Harvesting - Diode bridges for solar/RF power; Prototyping - PCB design and component selection.

Real-World Examples:

Follow these connections in order: Industrial IoT - High-power motor control applications; Smart Agriculture - Solenoid valve control for irrigation; Wearables - Low-power transistor design for battery life.

9.8 Smart Fan Controller Design

Temperature-Activated Fan Circuit

The transistor examples above give the parts. This challenge asks you to assemble them into one reviewable design: sensing, switching, protection, and code behavior.

Your Challenge: Design a circuit that automatically turns on a 12V DC fan (300mA) when temperature exceeds 30°C, using an ESP32 and LM35 temperature sensor.

Bring the visual evidence in Figure 9.1 into smart fan controller design. Its purpose is to reveal the LM35 in this fan controller is a three-lead analog sensor: supply, ground, and a voltage output that changes by 10 mV per degree Celsius. Its transistor-like package makes pin identification and thermal placement part of the circuit design, not details the ESP32 code can repair later. Photo: Nevit Dilmen, CC BY-SA 3.0 before a design claim is accepted.

A close-up of an LM35 analog temperature-sensor integrated circuit in a three-lead package
Figure 9.1: The LM35 in this fan controller is a three-lead analog sensor: supply, ground, and a voltage output that changes by 10 mV per degree Celsius. Its transistor-like package makes pin identification and thermal placement part of the circuit design, not details the ESP32 code can repair later. Photo: Nevit Dilmen, CC BY-SA 3.0

Inspect the three leads visible in Figure 9.1: they correspond to supply, ground, and the analogue output. The caption’s 10 mV per degree Celsius links that output to the ADC calculation, while pin identification and thermal placement warn that the transistor-like package is not self-explanatory. Confirm the flat-face orientation against the datasheet and place the body in representative airflow; neither a swapped pin nor heat from the fan driver can be corrected later by ESP32 code.

Work through the design as one signal-and-power chain. First translate the LM35 voltage into a temperature threshold, then choose a switch that survives the fan’s stall current, add an inductive-current path for switch-off, and only then write the GPIO logic. The component list below is the evidence set for those linked decisions, not a menu of interchangeable parts.

Given Components:

  • ESP32 (3.3V I/O, 12-bit ADC, max GPIO current 12mA)
  • LM35 temperature sensor (outputs 10mV/°C, e.g., 300mV @ 30°C)
  • 12V DC fan (running current: 300mA, stall current: 800mA)
  • Power supply: 12V, 1A
  • Available transistors: 2N2222 NPN BJT, IRLZ44N N-channel MOSFET
  • Resistors: assorted 1kΩ - 100kΩ
  • Diodes: 1N4001, 1N5819 Schottky

Step 1: Sensor Interface

The LM35 outputs 300mV at 30°C. ESP32 ADC reads 0-3.3V (12-bit = 4096 levels).

Question: Can you connect LM35 directly to ESP32 ADC?

  • Hint: LM35 max output is 1.5V @ 150°C. ESP32 ADC reads 0-3.3V.

Step 2: Transistor Selection

The fan draws 300mA running, 800mA stall.

Questions:

  • 2N2222 is rated for 600mA max collector current. Is it suitable?
  • If using 2N2222, what base resistor is needed for 300mA collector current (assume β=100)?
  • If using IRLZ44N MOSFET, what is the power dissipation at 300mA (Rds(on) = 0.022Ω)?

Step 3: Protection Circuit

DC motors generate inductive spikes when switched off.

Questions:

  • Which diode is better for flyback protection: 1N4001 or 1N5819 Schottky? Why?
  • Where should the flyback diode be placed (anode/cathode orientation)?

Step 4: ESP32 Code Logic

Study the conversion lines in this Arduino sketch, then modify the program to add hysteresis. You can test your solution on real ESP32 hardware or in the Wokwi online simulator (search for “ESP32 + LM35” templates).

// Fan controller challenge: verify the conversion and add hysteresis
const int tempPin = 34;  // ADC pin
const int fanPin = 25;   // GPIO output
const float adcReferenceV = 3.3;
const float adcMaxCount = 4095.0;
const float lm35VoltsPerC = 0.010;

void setup() {
  pinMode(fanPin, OUTPUT);
  digitalWrite(fanPin, LOW);
}

void loop() {
  int adcValue = analogRead(tempPin);

  // Convert ADC reading to temperature
  // LM35 outputs 10mV/°C, ESP32 ADC is 12-bit (0-4095) for 0-3.3V
  float voltage = (adcValue / adcMaxCount) * adcReferenceV;
  float tempC = voltage / lm35VoltsPerC;

  if (tempC > 30.0) {
    digitalWrite(fanPin, HIGH);  // Turn fan ON
  } else {
    digitalWrite(fanPin, LOW);   // Turn fan OFF
  }

  delay(5000);  // Check every 5 seconds
}

Your Tasks:

  1. Draw the complete circuit schematic
  2. Select BJT or MOSFET and justify your choice
  3. Calculate all resistor values
  4. Explain the ADC-to-temperature conversion in the starter code
  5. Add hysteresis to prevent fan chattering (turn ON at 30°C, turn OFF at 28°C)

Click to reveal the solution

Step 1 Solution: Sensor Interface

LM35 can connect directly to ESP32 ADC. Max output (1.5V @ 150°C) is within ADC range (3.3V). Note: The LM35 requires a minimum supply voltage of 4V, so power it from the 5V rail (available from USB or the 12V regulator), not from 3.3V.

Wiring map:

LM35 Pin / NodeConnects ToNote
VCC+5V from USB or regulated supplyLM35 needs at least about 4V
VoutESP32 ADC Pin 34Output is 10mV/°C, max about 1.5V, safe for the ESP32 ADC
GNDCommon groundESP32 and sensor must share ground

Step 2 Solution: Transistor Selection

2N2222 Analysis:

  • Rated for 600mA max, but fan can stall at 800mA → MARGINAL, NOT RECOMMENDED
  • If we proceed: Ic = 300mA, β = 100, required Ib = 3mA
  • Base resistor: R = (3.3V - 0.7V) / 3mA = 867Ω → use 820Ω
  • Power dissipation: P = Vce(sat) × Ic = 0.2V × 0.3A = 60mW (acceptable)

IRLZ44N MOSFET Analysis (BETTER CHOICE):

  • Rated for 47A → easily handles 800mA stall (OK)
  • Power dissipation: P = I² × Rds(on) = (0.3)² × 0.022 = 2mW (excellent!)
  • Gate resistor: 100Ω (limits inrush current)
  • Pull-down: 10kΩ (keeps fan off when ESP32 boots)

Winner: MOSFET for lower power loss, higher current rating, lower GPIO load

Step 3 Solution: Protection Circuit

Diode Choice: 1N5819 Schottky is better

  • Forward voltage: 0.4V (vs 0.7V for 1N4001) → less energy wasted during spike discharge
  • Reverse recovery time: <10ns (vs 2µs for 1N4001) → better for fast PWM if added later

Placement:

Component NodeConnects To
Fan positive side+12V
Fan negative sideIRLZ44N drain
1N5819 cathodeFan positive side / +12V
1N5819 anodeFan negative side / MOSFET drain
IRLZ44N sourceGND

Anode to motor-, Cathode to motor+ (or +12V rail). When motor turns off, collapsing magnetic field tries to maintain current → current flows through diode instead of spiking MOSFET.

Step 4 Solution: Complete Circuit

SubsystemConnection
Fan power+12V → DC fan positive side
Fan switch pathDC fan negative side → IRLZ44N drain → IRLZ44N source → GND
Flyback protection1N5819 across fan, cathode to +12V and anode to MOSFET drain
Temperature sensor power+5V → LM35 VCC, LM35 GND → common ground
Temperature signalLM35 Vout → ESP32 ADC Pin 34
Motor-control signalESP32 Pin 25 → 100Ω resistor → IRLZ44N gate
Boot safety10kΩ pull-down from IRLZ44N gate to GND

Step 5 Solution: Complete Code with Hysteresis

This complete sketch runs on ESP32 hardware with Arduino framework. Upload via Arduino IDE or PlatformIO.

const int tempPin = 34, fanPin = 25;
const float onTemp = 30.0, offTemp = 28.0; // 2 °C hysteresis band

void setup() {
  pinMode(fanPin, OUTPUT);
  digitalWrite(fanPin, LOW);
  Serial.begin(115200);
}

void loop() {
  int adc = analogRead(tempPin);
  float voltage = adc * (3.3 / 4095.0);
  float tempC   = voltage / 0.01;          // LM35: 10 mV/°C

  static bool fan = false;
  if (tempC > onTemp && !fan)  { digitalWrite(fanPin, HIGH); fan = true;  }
  if (tempC < offTemp && fan)  { digitalWrite(fanPin, LOW);  fan = false; }

  Serial.printf("ADC %d | %.3fV | %.1f°C | Fan %s\n",
                adc, voltage, tempC, fan ? "ON" : "OFF");
  delay(5000);
}

Key Improvements in This Solution:

  1. Hysteresis: Prevents fan from rapidly cycling on/off at exactly 30°C
  2. State variable: Tracks fan state to implement hysteresis logic
  3. Schottky diode: Better protection with lower forward drop
  4. MOSFET choice: 40x current rating margin, 30x lower power loss than BJT
  5. Pull-down resistor: Prevents fan from turning on during ESP32 boot
  6. Serial debug: Helps verify sensor readings and fan operation

Real-World Enhancements (try these next!):

  • Add PWM for variable fan speed (map temperature 25-40°C to 0-100% speed)
  • Use exponential smoothing to filter sensor noise: temp = 0.9*temp + 0.1*newReading
  • Add watchdog timer to reboot ESP32 if it hangs
  • Log temperature data to SD card or cloud (ThingSpeak, AWS IoT)

Key Lessons:

  1. Always include flyback diodes for inductive loads
  2. Choose MOSFETs for >500mA loads (lower loss, higher rating)
  3. Hysteresis prevents chattering in threshold-based control
  4. ADC-to-physical-unit conversion requires careful calculation
  5. Pull-down resistors prevent spurious activation during boot

Voltage VeraCheckpoint: Fan Controller Review

You now know:

  • The LM35 can feed the ESP32 ADC directly because its maximum output stays below 3.3V.
  • The IRLZ44N is the safer switch than a 2N2222 for the fan because the fan can stall at 800mA.
  • Hysteresis uses separate ON and OFF thresholds, such as 30°C and 28°C, so the fan does not chatter at the boundary.

The mathematical gist. A GPIO is a command, not a motor supply. For this chapter’s 300 mA fan, a 12 mA pin would be overloaded by 25.0 times. A BJT estimate needs (I_B=I_C/\beta) and (R_B=(3.3-0.7)/I_B); a MOSFET estimate uses (P=I^2R_{DS(on)}). The same controller then maps LM35 voltage into ADC counts for its 30°C/28°C hysteresis thresholds.

Math Bridge · guided foundationsHow does a GPIO command a 300 mA fan safely?Let Eddie connect load current, transistor drive, switch loss, and ADC thresholds.

9.9 What’s Next

If you want to…Read this
Learn about semiconductor doping, diodes, and LEDs in depthElectronics: Doping and Diodes
Understand conductors, insulators, and material propertiesElectronics: Conductors and Insulators
Apply electronics knowledge to analog-to-digital conversionAnalog and Digital Electronics
See electronics fundamentals in action with sensor circuitsSensor Circuits and Signals

9.10 Quick Access

NeedGo To
Calculate LED resistorCalculators
Choose MOSFET vs BJTTransistor Selection
Understand component symbolsComponent Reference
Learn about diodesDoping & Diodes
Visual component galleryComponent Reference

The Sensor Squad’s guide to the amazing world of electronics!

“Welcome to Electronics School!” announced the microcontroller. “Today I’m going to teach you how I was born — from tiny pieces of silicon!”

Temperature Terry raised a hand. “But Max, you’re so smart and complicated. How can you come from a rock?” Max laughed. “Silicon IS a special rock — a semiconductor. Scientists figured out how to add tiny bits of other materials to make it conduct electricity in clever ways. That’s how they made diodes, transistors, and eventually ME!”

the LED was fascinated. “Tell us more!” Max drew five lessons on the board:

Lesson 1: Electronics vs Electricity. Electricity is just power flowing, but electronics is SMART power — it can think and decide! Your light bulb just turns on, but your smart light bulb checks a schedule, reads sensors, and connects to Wi-Fi.”

Lesson 2: Materials. There are conductors (let electricity through), insulators (block it), and semiconductors (can do BOTH depending on conditions).”

Lesson 3: Doping. Scientists add special atoms to silicon to make N-type (extra electrons) and P-type (missing electrons). Put them together and you get diodes and transistors!”

Lesson 4: Transistors. These are tiny switches that I’m made of — millions of them! They can turn on and off super fast, which is how I think.”

Lesson 5: Choosing the right parts. Different jobs need different transistors, just like different sports need different shoes!”

the battery smiled. “And I power all of this!” The whole squad cheered — they were ready to learn electronics!

9.10.1 Key Words for Kids

WordWhat It Means
ElectronicsUsing special materials to make smart circuits that can think and decide
SemiconductorA material that can be switched between conducting and blocking electricity
TransistorA tiny switch inside every computer chip
DiodeA one-way gate for electricity
MicrocontrollerA tiny computer brain made of millions of transistors
BJT vs MOSFET Resistors

The Error: A developer uses a 10k ohm resistor from GPIO to the base/gate for both a BJT and a MOSFET. The BJT circuit barely turns on, while the MOSFET works perfectly.

Why: BJTs are current-controlled — a 10k ohm base resistor only provides Ib = 2.6V/10k ohm = 0.26mA, which can only switch Ic = 26mA (with beta=100). MOSFETs are voltage-controlled — with essentially zero DC gate current, the gate resistor does not set steady-state gate voltage. The MOSFET is suitable only if its datasheet gives low Rds(on) at the available GPIO voltage.

Fix: For BJTs, use a ~1k ohm base resistor (provides ~2.6mA, enough to switch ~260mA). For MOSFETs, resistor value is less critical (100 ohm to 1k ohm), but always add a 10k ohm pull-down to prevent floating gate.

Quick Reference:

Load CurrentRecommended TransistorBase/Gate ResistorPull-downFlyback Diode
<100mA2N2222 BJT1k ohmNot criticalYes (if inductive)
100-500mA2N2222 or small MOSFET1k ohm (BJT) / 100 ohm (FET)10k ohmYes
500mA-5ALogic-level MOSFET100 ohm10k ohmYes
>5AHigh-current MOSFET + heatsink10-100 ohm10k ohmYes

See the Transistor Switching Examples above for detailed calculations and worked examples.

Key Takeaway

Electronics is the bridge between raw electrical power and intelligent IoT devices. Understanding semiconductors, diodes, and transistors enables you to safely interface sensors, efficiently control actuators, optimize battery life, and debug hardware issues — skills that apply to every IoT project from prototype to production.


Total Reading Time: ~80 minutes | Difficulty Range: Beginner to Intermediate

9.11 Design Contract: Serial Bus Interfaces

The overview above connects silicon, diodes, transistors, GPIO limits, and driver circuits into a broad electronics map. The next integration question is how those electrical building blocks reach the microcontroller through real sensor and peripheral buses.

For the layered engineering checks, continue to Serial Bus Interface Contracts. It compares I2C, SPI, and UART wiring, selection, throughput, addressing, pull-up behavior, clocking, bus capacitance, and common failure modes.

9.12 Summary

This module covers the electronics skills needed to build and review IoT hardware: electricity fundamentals, semiconductor behavior, transistor selection, analog-digital conversion, and practical circuit-design workflows.

9.13 Continue Your Route

This final part closes the route from Checkpoint: Switching Loads through Summary. Return to Electronics: Power and Transistor Switching or continue from the electronics module index.