The Field Guide to Electronic Components

A plain-language encyclopedia for hobbyists, makers, and anyone who wants to understand what the parts in an electronic circuit actually do. There's no math beyond multiplication and division, and no prior training is assumed.

The component chapters (4–31) follow the same pattern, so once you've read one you know where to look in the others. Each opens with what the part is and how it works, usually with an everyday analogy, then covers:

Every component chapter then ends with the same three sections:

Chapters 1–3 (foundations) and 32–34 (practice) are organized by topic instead.


Contents

Part I — Foundations

# Chapter Covers
1 Electricity basics Voltage, current, resistance, Ohm's law, power, energy, AC/DC, series/parallel, ground
2 Reading schematics and datasheets Symbols, reference designators, conventions, part numbers, reading a datasheet
3 Tools and measurement Multimeter functions, oscilloscopes, logic analyzers, bench supplies and more

Part II — Connections, switching and protection

# Chapter Covers
4 Wire and cable Gauges, solid vs stranded, insulation, cable types, color codes
5 Connectors Headers, JST, Molex, barrel, USB, audio, terminals, crimping
6 Switches and relays Poles and throws, switch types, ratings, relays, reed and solid-state relays
7 Fuses and circuit protection Fuses, polyfuses, breakers, GFCI, TVS, MOVs, reverse-polarity and ESD protection

Part III — Passive components

# Chapter Covers
8 Resistors Types, color codes, SMD codes, power ratings, uses
9 Potentiometers and resistive sensors Pots, trimmers, thermistors, LDRs, FSRs, strain gauges
10 Capacitors Ceramic, electrolytic, tantalum, film, supercaps; codes; uses
11 Inductors and transformers Coils, ferrites, chokes, transformers, inductive kickback
12 Crystals and oscillators Quartz crystals, resonators, oscillator modules

Part IV — Semiconductors

# Chapter Covers
13 Diodes How semiconductors work, rectifier, Schottky, Zener, TVS, bridges
14 LEDs and optoelectronics LEDs, displays, IR, lasers, photodiodes, phototransistors, optocouplers
15 Addressable LEDs WS2812B, SK6812, WS2811, APA102: data, power, level shifting
16 Bipolar transistors (BJTs) NPN/PNP, switching, amplifying, Darlingtons, common parts
17 MOSFETs and other FETs N/P-channel, logic-level, gate drive, JFETs, IGBTs
18 Thyristors, TRIACs and SSRs SCRs, TRIACs, DIACs, optotriacs, solid-state relays

Part V — Power

# Chapter Covers
19 Batteries Chemistries, sizes, capacity, packs, charging, safety
20 Voltage regulators Linear, LDO, buck, boost, buck-boost, charge pumps
21 Power supplies and USB power Wall adapters, bench supplies, USB/USB-C/PD, budgets, brownouts

Part VI — Things that move, sound and show

# Chapter Covers
22 Motors and actuators DC, gear, brushless, stepper, servo, solenoid, drivers
23 Sound: speakers, buzzers, amplifiers, microphones Transducers, amp classes, mic types, audio noise
24 Displays 7-segment, LCD, TFT, OLED, e-paper, VFD, Nixie, backlights, touch

Part VII — Input and sensing

# Chapter Covers
25 Input devices Buttons, debouncing, encoders, keypads, joysticks, capacitive touch
26 Sensors Temperature, light, distance, motion, presence, current, gas, force, position

Part VIII — Chips and computers

# Chapter Covers
27 Integrated circuits and digital logic Packages, logic families, gates, shift registers, multiplexers
28 Analog ICs: op-amps, comparators, the 555 Op-amp circuits, comparators, timers, voltage references
29 Microcontrollers and single-board computers GPIO, ADC, PWM, special pins, sleep, programming
30 Communication interfaces UART, RS-232/485, I²C, SPI, I²S, 1-Wire, CAN, USB, wireless
31 Interfacing and level shifting Connecting 3.3 V and 5 V, driving loads, reading outside signals, isolation

Part IX — Practice

# Chapter Covers
32 Soldering and prototyping Irons, solder, flux, joints, breadboards, perfboard, PCBs
33 Safety Shock, mains, batteries, capacitors, heat, fumes, lasers
34 Troubleshooting and diagnosis Method, symptom tables, component failure modes

Appendices

A Cheat sheet Formulas, codes, tables
B Glossary Terms A–Z
C Identifying parts by sight Through-hole and SMD galleries, chip sizes, look-alikes
D Common pinouts TO-92, TO-220, SOT-23, DIP chips, everyday connectors

Where to start

1 — Electricity basics

Everything in this guide comes back to a handful of ideas: voltage, current, resistance, power, and the rule that current only flows around a complete loop. Get comfortable with these and every component chapter becomes a variation on a theme.


1.1 Charge, and what's actually moving

All matter is made of atoms, and atoms contain electrons, tiny particles with a negative electric charge. In metals like copper, some electrons aren't tied to any one atom. They drift freely through the metal like a crowd in a hallway. Electric current is those electrons being pushed along in a common direction.

💡 Conventional current vs electron flow. Early experimenters (Benjamin Franklin among them) guessed that current flows from + to −. Much later, we learned that electrons actually move from − to +. By then the convention was everywhere, so it stuck. Schematics, arrows on diode symbols, and nearly every textbook use conventional current (+ → −). It makes no practical difference as long as you're consistent.


1.2 The three quantities

The most common way to picture electricity is water in pipes:

The water analogy: pressure is voltage, flow rate is current, a narrow pipe is resistance.
The water analogy: pressure is voltage, flow rate is current, a narrow pipe is resistance.
Quantity Symbol Unit Water analogy What it really is
Voltage V (or E, U) volt (V) Water pressure The "push," the energy difference per unit of charge between two points
Current I ampere, "amp" (A) Flow rate How much charge passes a point per second (1 A = 1 coulomb per second)
Resistance R ohm (Ω) Narrowness of the pipe How strongly a path opposes current

Three rules follow directly:

Unit prefixes

Prefix Symbol Multiplier Example
giga G × 1,000,000,000 1 GΩ insulation resistance
mega M × 1,000,000 1 MΩ resistor
kilo k × 1,000 4.7 kΩ resistor, 1 kV
(none) × 1 5 V, 2 A
milli m ÷ 1,000 20 mA, 500 mV
micro µ (often written u) ÷ 1,000,000 100 µF, 10 µA
nano n ÷ 1,000,000,000 100 nF
pico p ÷ 1,000,000,000,000 22 pF

Engineers often put the prefix where the decimal point would go: 4k7 = 4.7 kΩ, 2R2 = 2.2 Ω, 3V3 = 3.3 V. It avoids a tiny dot that can vanish on a printed page.


1.3 Ohm's law

The relationship between the three quantities is the most useful equation in hobby electronics:

V = I × R (voltage = current × resistance)

Cover the quantity you want; the other two show the formula.
Cover the quantity you want; the other two show the formula.

Rearranged:

Examples:

Memory aid: write V on top of a triangle with I and R side by side underneath. Cover the quantity you want and the other two show you the formula.

Where Ohm's law doesn't apply directly: parts like diodes, LEDs, and transistors are non-linear, meaning their resistance changes with the voltage across them. Resistors, wires, and heating elements behave "ohmically." For the others, you use their datasheet curves (later chapters show how).


1.4 Power and energy

Power is the rate at which energy is used or delivered, measured in watts (W):

P = V × I

Combining with Ohm's law gives two more handy forms:

Examples: a 12 V motor drawing 2 A uses 24 W. 100 mA through a 100 Ω resistor turns 0.1² × 100 = 1 W into heat.

Energy is power over time, the "amount in the tank":

💡 Almost all wasted electrical power ends up as heat. A part's power rating really says how much heat it can get rid of before it's damaged. That's why power ratings go down when parts are packed into a hot, enclosed box.


1.5 DC and AC

Why the grid uses AC: transformers (chapter 11) can step AC voltage up or down efficiently. Power stations send electricity long distances at hundreds of thousands of volts, where the current, and so the loss in the wires (I²R), is small. Then it's stepped down near your house.

Frequency and period

Frequency (hertz, Hz) is how many cycles happen per second. The period is the time for one cycle: period = 1 ÷ frequency. 60 Hz has a period of about 16.7 ms.

Peak vs RMS

An AC voltage is constantly changing, so which number do you quote? By convention, the RMS ("root mean square") value. That's the steady DC voltage that would heat a resistor by the same amount. For a sine wave, peak = RMS × 1.414. So "120 V" mains actually peaks at about 170 V, and "230 V" peaks at about 325 V. Meters labelled True RMS measure this correctly even for non-sine waveforms.

💡 The "War of the Currents" in the 1880s–90s pitted Thomas Edison's DC system against Nikola Tesla's and George Westinghouse's AC. AC won for long-distance distribution. Today, though, the very longest power links (undersea cables, links between countries) use high-voltage DC, because modern electronics can convert efficiently at the ends.


1.6 Pulsed DC and PWM

A lot of "DC" in electronics isn't steady:

Steady DC, alternating AC, and PWM at three duty cycles.
Steady DC, alternating AC, and PWM at three duty cycles.

1.7 Circuits: the loop rule

Current flows only around a complete, closed loop, out of the source's positive terminal, through the load, and back to the source's negative terminal. Break the loop anywhere, on either side, and all current stops.

A complete circuit, an open circuit, and a short circuit.
A complete circuit, an open circuit, and a short circuit.

The four states a path can be in:

State What it means Result
Closed / complete An unbroken path through the load The circuit works
Open A break somewhere: switch off, broken wire, blown fuse, cracked solder joint No current at all
Short circuit A near-zero-resistance path bypassing the load Very large current, heat, blown fuses, damaged supplies
High resistance / intermittent A path that's "mostly" connected: corroded contact, loose screw, marginal joint Voltage lost in the wrong place, erratic behavior

The return path matters as much as the supply path. The ground or negative wire carries exactly the same current back as the positive wire carries out.


1.8 Series and parallel

Every connection between two parts is one or the other (or a combination).

Series shares current and splits voltage; parallel shares voltage and splits current.
Series shares current and splits voltage; parallel shares voltage and splits current.

Series: end to end, one path

Parallel: side by side, several paths

Kirchhoff's two laws (the formal version)

These two statements, plus Ohm's law, are enough to analyze any circuit made of resistors and sources.


1.9 Ground and reference

Ground (GND, 0 V, common, −) is simply the point in a circuit that everyone agrees to call zero volts. Every other voltage is measured relative to it. "The 5 V rail" means "5 V above ground."

Kinds of "ground" you'll see:

Term Meaning
Circuit / signal ground The shared 0 V reference inside a device, usually the supply's negative terminal
Earth ground A conductor literally connected to the earth: the third prong on a mains plug. It's a safety path that carries fault current and trips protection
Chassis ground The metal case of a device, often bonded to earth for safety
Analog / digital ground Separate ground paths in sensitive designs, joined at a single point to keep noisy digital currents out of delicate analog measurements

The one rule to remember: two devices that exchange signals must share a ground. A signal is a voltage relative to ground. If the devices' grounds aren't connected, the receiver has no reference and the signal is meaningless.


1.10 Voltage drop

Any current flowing through any resistance loses voltage across it: V_drop = I × R. That includes things you might think of as "just wire":

Example: 2 A through a cable with 0.5 Ω of total (out-and-back) resistance loses 1 V. On a 5 V circuit, that leaves only 4 V at the far end. Low-voltage, high-current circuits are the most sensitive, because a small loss is a large percentage of the supply. The remedies are thicker wire, shorter runs, fewer connectors, or sending a higher voltage and converting it down near the load.


1.11 Conductors, insulators and semiconductors

Class Behavior Examples
Conductor Lots of free electrons. Low resistance Silver (best), copper, gold, aluminum, steel
Insulator Almost no free charge. Blocks current Plastic, rubber, glass, ceramic, dry air, PTFE
Semiconductor In between, and controllable. Adding impurities ("doping") changes it dramatically Silicon, germanium, gallium arsenide, silicon carbide

Semiconductors are the basis of diodes, transistors, LEDs, and all integrated circuits (chapter 13 explains how).

💡 Silver conducts slightly better than copper, but copper is the practical choice. It's nearly as good and far cheaper. Gold is worse than both. It's used on connector contacts because it never corrodes, not because it conducts better.

💡 Insulators have limits. Push enough voltage across air and it breaks down and conducts. That's a spark, or lightning. Dry air withstands roughly 3,000 V per millimeter.


1.12 Quick reference

I want… Use
Current from voltage and resistance I = V ÷ R
Voltage across a resistor V = I × R
Power P = V × I = I² × R = V² ÷ R
Energy in a battery Wh = Ah × V
Runtime hours ≈ Wh ÷ watts
Series resistance R1 + R2 + …
Parallel resistance (two) R1 × R2 ÷ (R1 + R2)
AC peak from RMS peak = RMS × 1.414
Period from frequency period = 1 ÷ frequency

2 — Reading schematics and datasheets

A schematic is a map of connections, not a picture of what a circuit looks like physically. A datasheet is the manufacturer's manual for a part. Together they tell you almost everything. This chapter covers how to read both, and how to decode part numbers and markings.


2.1 Schematic basics

How to tell connected wires from crossing ones.
How to tell connected wires from crossing ones.

2.2 Common symbols (described)

Component Symbol description
Wire A line
Junction A filled dot where lines meet
Resistor A zigzag line (US/Japan) or a plain rectangle (Europe/IEC)
Variable resistor / potentiometer Resistor with an arrow through it (variable), or an arrow pointing at its side (the wiper of a pot)
Capacitor (non-polarized) Two parallel straight lines with a gap
Capacitor (polarized/electrolytic) One straight and one curved plate, or two plates with a "+" on one side
Inductor A row of humps (loops), with parallel lines beside it if it has an iron/ferrite core
Transformer Two inductors facing each other with core lines between
Diode A triangle pointing at a bar. Current flows in the direction the triangle points. The bar is the cathode
Zener diode Diode whose bar has small bent "wings"
Schottky diode Diode whose bar has small S-shaped hooks
LED Diode with two small arrows pointing outward (light out)
Photodiode / phototransistor Arrows pointing inward (light in)
NPN transistor Circle with base line; the emitter arrow points out
PNP transistor Emitter arrow points in (mnemonic: "PNP = Pointing iN Permanently")
MOSFET Gate drawn as a line separated from the channel by a gap (the insulation). The arrow direction shows N- or P-channel
Battery (single cell) A long line (+) and a short, thicker line (−)
Battery (multi-cell) Several long/short pairs
DC source A circle with + and −
AC source A circle with a sine wave inside
Ground A line with three shrinking lines below (earth), a downward triangle (signal ground), or a line with hatch marks (chassis)
Switch A lifted lever between two dots
Push button A bridge above two contacts, pushed down to connect
Fuse A small rectangle with a line through it, or an S-curve
Lamp A circle with an X inside
Speaker A small rectangle with a flared cone beside it
Motor A circle containing "M"
Crystal A rectangle between two plates
Op-amp / comparator A triangle with two inputs (+ and −) on the flat side and an output at the point
Logic gates Distinct shapes: AND (D-shape), OR (curved shield), NOT (triangle with a bubble); a bubble on any output means "inverted"
IC / module A rectangle with numbered or named pins
Antenna A "Y" or an inverted triangle on a stalk
Test point A small circle or labelled pad
The symbols you'll meet most often.
The symbols you'll meet most often.

2.3 Reference designators

Every part on a schematic and circuit board gets a letter-plus-number label. The letters are standard:

Letter Part Letter Part
R Resistor Q Transistor (BJT or FET)
RV / VR Variable resistor / pot U / IC Integrated circuit
C Capacitor Y / X Crystal / oscillator
L Inductor F Fuse
T Transformer K / RL Relay
D Diode, LED S / SW Switch
LED / DS Light / display J / P / CN Connector (J = jack, fixed; P = plug)
TP Test point BT Battery
FB Ferrite bead M Motor
LS / SP Loudspeaker MIC Microphone
TH / RT Thermistor Z / ZD Zener (some conventions)

The number is just a label (R1, R2, R47…). It doesn't indicate value or importance.


2.4 Naming conventions you'll see on pins


2.5 Block diagrams, wiring diagrams and PCB views


2.6 Part numbers and markings

Part numbers look cryptic but follow patterns:

To recognize a part from its shape before you can read its marking, see Appendix C. Pinouts of common parts are in Appendix D.


2.7 How to read a datasheet

Datasheets can run to hundreds of pages, but most follow the same order. Read these sections first:

  1. Front page / features: the headline specs (voltage range, current, speed, interface) and a one-paragraph description. Often enough to decide if a part fits.
  2. Pin configuration and functions: which pin is which, and which signals are active-low.
  3. Absolute maximum ratings: limits that must never be exceeded, even briefly. These are not operating conditions. A part run at its absolute maximum isn't "within spec"; it's on the edge of damage.
  4. Recommended operating conditions: the range you should design within.
  5. Electrical characteristics: the real behavior (input thresholds, output current, leakage, timing), each with min / typ / max and the test conditions. Design to min and max, not typical. "Typical" is what an average part does at 25 °C.
  6. Typical characteristics (graphs): how the part behaves across temperature, voltage, and load. Useful for non-linear parts like diodes and MOSFETs.
  7. Application information / typical application circuit: the manufacturer's own example circuit. Copy it as your starting point. Most "new chip doesn't work" problems come from a missing capacitor or resistor shown here.
  8. Layout guidelines: where to put capacitors and how to route high-current paths.
  9. Package / mechanical drawings: dimensions, pin 1 location, recommended PCB footprint.

Tips:

3 — Tools and measurement

You can't see electricity, so every diagnosis depends on instruments. This chapter covers the multimeter in depth, the other tools worth knowing about, and the measurement habits that stop you from fooling yourself.


3.1 The multimeter

A digital multimeter (DMM) combines a voltmeter, ammeter, and ohmmeter, usually with extras. It's the one essential tool.

Terminals

Terminal Used for
COM The black lead, for every measurement
VΩ (often also marked for diode, capacitance, Hz, temperature) The red lead, for almost everything
mA / µA The red lead, for small currents (usually fused at a few hundred mA)
10 A / 20 A The red lead, for large currents (separately fused, often time-limited)

Habit: after measuring current, move the red lead straight back to VΩ. Leaving it in a current jack and then touching a battery "to check voltage" is the most common way to blow a meter's fuse, or worse.

Functions

Function Symbol Measures Circuit power How to connect
DC voltage V with a straight + dashed line (⎓) Steady voltage On Across (in parallel with) the two points
AC voltage V~ Mains, transformer outputs On Across
Millivolts mV Small voltages On Across
Resistance Ω Resistor value, wire integrity Off Across the part
Continuity A sound-wave or speaker icon "Connected or not" (beeps below a few tens of Ω) Off Across the two points
Diode test Diode symbol Forward voltage of a junction Off Red on anode, black on cathode
Capacitance Capacitor symbol / F Capacitor value Off, discharged Across the part
DC / AC current A⎓, A~, mA, µA Current flowing On In series: break the circuit and route the current through the meter
Frequency / duty Hz, % Signal rate and PWM duty On Across the signal
Temperature °C / °F Via a thermocouple probe — Probe on the object
NCV NCV Presence of AC mains, without contact — Hold near the wire

Key specs when buying


3.2 Measuring well

Voltage is measured across a part; current is measured through it.
Voltage is measured across a part; current is measured through it.

Voltage (parallel)

Touch black to the reference (usually ground) and red to the point of interest. A negative reading just means the probes are reversed, which is itself useful information. Measure under real load. A weak battery or bad connection can read fine with nothing drawing current and collapse when something does.

Current (series)

  1. Estimate the current. If unsure, start with the high-current jack.
  2. Turn off the circuit, open the path (e.g. unplug the positive lead), and bridge the gap with the meter.
  3. Power up, read, power down, remove the meter, restore the circuit.
  4. Return the red lead to VΩ.

Never connect a meter in current mode across a voltage source. In current mode it's nearly a short circuit.

Resistance, continuity, diode, capacitance

These modes push a small test current from the meter itself, so the circuit must be unpowered (and capacitors discharged). Measuring in-circuit is often misleading, because other parts in parallel change the reading. Lift one leg of a part for a true value.

The voltage-drop test

To find a bad connection, measure the voltage across the connection (a switch, connector, crimp, or fuse) while current flows. A good joint shows a few millivolts. A bad one shows tenths of a volt or more. This finds faults continuity testing misses, because continuity uses a tiny current that a marginal contact can still pass.

Measuring across a single connection while current flows.
Measuring across a single connection while current flows.

Sanity-checking the meter

Before trusting a surprising reading: touch the probes together (≈ 0 Ω, beep), measure a known battery, and check the meter's own battery and fuses. Cracked leads and blown fuses cause most "my meter is wrong" moments.


3.3 Other test instruments

Tool What it does When it's worth it
Oscilloscope Draws voltage vs time: waveforms, ripple, noise, signal shape Anything where a signal changes: PWM, audio, switching supplies, data edges. USB and handheld scopes are affordable
Logic analyzer Records many digital lines and decodes protocols (I²C, SPI, UART) into bytes Debugging communication between chips. Inexpensive 8-channel USB models work with free software
Bench power supply Adjustable voltage with an adjustable current limit First power-up of a new or repaired circuit: a short just hits the limit instead of burning something
Component tester Plug in an unknown part; it identifies type, value, and pinout Sorting mystery transistors, capacitors, diodes
LCR meter Measures inductance (L), capacitance (C), resistance (R) precisely Inductors, and accurate capacitor values
ESR meter Measures a capacitor's equivalent series resistance, often in-circuit Finding tired electrolytic capacitors in power supplies
USB power meter Inline voltage, current, energy, and USB-PD info Anything USB-powered
Clamp meter Measures current by clamping around one wire, no circuit break Mains and high-current DC (needs a DC-capable clamp)
Logic probe A pen that lights for high / low / pulsing Quick checks on digital lines
Thermal camera / IR thermometer Shows temperature Finding the part that's overheating on a board
Signal / function generator Produces sine, square, and other test signals Testing filters, amplifiers, inputs
Insulation tester ("megger") Measures very high resistance at high test voltage Checking mains wiring and motor insulation

3.4 Hand tools for electronics


3.5 Measurement habits

  1. Know what you expect before you measure. "This should be 3.3 V." A reading only means something against an expectation.
  2. Check the mode, range, and unit on the display every time. mV vs V and kΩ vs MΩ are the classic misreads.
  3. Measure at the part, not just at the supply. Voltage lost on the way is often the fault.
  4. Measure under load and during the problem. Use MIN/MAX capture for dips too fast to see.
  5. Keep one hand clear on anything above about 50 V, so current can't flow across your chest.
  6. Write readings down. Comparisons across time or between a good and a bad unit are the fastest diagnostic you have.

4 — Wire and cable

Wire is the most overlooked component in a circuit. It has resistance, a current limit, a voltage rating, and a temperature rating, and it fails in predictable ways. Choosing the right wire is as much a design decision as choosing a resistor.


4.1 What a wire is

A conductor (almost always copper) inside insulation. A cable is several insulated conductors in a common outer jacket, sometimes with a shield.

Conductor materials

Material Notes
Bare copper The standard. Excellent conductivity, easy to solder
Tinned copper Copper coated in tin. Resists corrosion (good for marine and humid use), solders easily. Slightly higher resistance
Silver-plated copper Used in high-frequency and high-temperature (PTFE) wire
CCA (copper-clad aluminum) Aluminum core with a thin copper skin. Cheaper, but ~60 % more resistance than copper of the same size, brittle, and hard to crimp. Common in bargain speaker and network cable. Avoid for power
Aluminum Used for utility and some building wiring in large sizes. Needs special connectors, because it expands and oxidizes
Nichrome / resistance wire Deliberately high resistance: heating elements, hot-wire foam cutters
Enamelled ("magnet") wire Copper with a thin varnish insulation. Used to wind coils, motors, and transformers. Strip the enamel by scraping or burning before soldering

4.2 Wire size: gauge

AWG (American Wire Gauge)

AWG numbers run backwards: a smaller number is thicker wire. Every 3 gauge steps roughly doubles (or halves) the copper cross-section, and every 6 steps doubles the diameter.

Common wire gauges, conductor drawn to scale.
Common wire gauges, conductor drawn to scale.
AWG Diameter (mm) Area (mm²) Resistance (Ω per meter) Typical current, chassis wiring* Typical use
10 2.59 5.26 0.0033 ~30 A+ Heavy DC, battery cables
12 2.05 3.31 0.0052 ~20–25 A 20 A household circuits, heavy DC
14 1.63 2.08 0.0083 ~15–20 A 15 A household circuits
16 1.29 1.31 0.013 ~10–13 A Extension cords, speaker wire
18 1.02 0.82 0.021 ~7–10 A Lamp cords, LED power feeds
20 0.81 0.52 0.033 ~5 A Moderate DC power
22 0.64 0.33 0.053 ~3 A Hookup wire, breadboards
24 0.51 0.20 0.084 ~2 A Signal, network cable (Cat5/6)
26 0.40 0.13 0.13 ~1 A Ribbon and data cable
28 0.32 0.08 0.21 ~0.5–1 A Ribbon cable, jumper wires
30 0.25 0.05 0.34 ~0.5 A Wire-wrap, fine internal wiring

* Rough figures for short runs in open air. Bundled, enclosed, or hot wiring must be derated (run at less current). Building wiring follows electrical codes, not this table.

Metric sizes

Outside North America, wire is sized by cross-sectional area in mm². 0.5, 0.75, 1.0, 1.5 and 2.5 mm² are common. 1.5 mm² is roughly 16 AWG, and 2.5 mm² roughly 14 AWG.

Choosing a size

Wire size is limited by two things:

  1. Heat: too much current and the insulation softens or melts.
  2. Voltage drop: at low voltages, this usually bites first. V_drop = I × (Ω per meter) × length × 2 (×2 for out and back). For example, 3 A over 3 m of 22 AWG loses 3 × 0.053 × 6 ≈ 0.95 V. That's almost 20 % of a 5 V supply.

A good target for low-voltage DC is to lose under 3–5 % of the supply voltage in the wiring.


4.3 Solid vs stranded

Solid Stranded
Construction One thick conductor Many thin strands twisted together
Flexibility Stiff. Fatigues and cracks if flexed repeatedly Flexible. Survives movement and vibration
Best for Breadboards, fixed wiring inside walls, wire-wrap Anything that moves: cables, harnesses, robots, test leads
Terminating Holds shape in push-in and screw terminals Tin the tip or use a ferrule in screw terminals, or strands splay out

Strand count is written like "7/0.2" (7 strands of 0.2 mm) or "19/32" (19 strands of 32 AWG). More, finer strands = more flexible. Very fine, highly flexible wire is often labelled "silicone" or "test lead" wire.

💡 The skin effect: at high frequencies, current crowds toward the surface of a conductor. Litz wire, made of many individually insulated fine strands woven together, fights this. It's used in induction cookers and wireless chargers.


4.4 Insulation

Insulation Temperature Properties Common in
PVC ~80–105 °C Cheap, general purpose. Melts back when soldered nearby Hookup wire, cords
Silicone ~150–200 °C Very flexible, heat-resistant, but tears easily Test leads, RC models, hot areas
PTFE (Teflon) ~200–260 °C Doesn't melt from a soldering iron, thin, slippery, tough Aerospace, high-temp, wire-wrap
XLPE (cross-linked polyethylene) ~90–125 °C Tough, good dielectric Automotive (GXL/TXL), power cable
Rubber / neoprene varies Flexible, rugged, oil-resistant types Heavy-duty cords
Enamel (polyurethane/polyimide) 130–220 °C Very thin film Coils, motors, transformers

Insulation also has a voltage rating (commonly 300 V or 600 V for hookup wire). Thin signal wire may be rated for very little. Don't use it where mains-level voltages could appear.


4.5 Types of wire and cable

Cross-sections of common constructions.
Cross-sections of common constructions.
Type Construction Used for
Hookup wire Single insulated conductor, solid or stranded (22–18 AWG) General internal wiring, breadboards
Jumper wires ("Dupont") Thin stranded wire with 2.54 mm pin/socket ends Breadboard prototyping
Ribbon cable Many conductors side by side in a flat strip, 1.27 mm pitch typical IDC connectors, internal data cables
FFC / FPC Flat printed conductors on thin plastic film Laptops, displays, cameras, keyboards
Zip cord / lamp cord Two conductors joined by a thin web, split by hand Lamps, speaker wire
Speaker wire Two-conductor, marked polarity (stripe, rib, or color) Amplifier to speaker
Multi-conductor cable Several insulated wires in a round jacket Control, sensor runs, power + signal together
Twisted pair Two wires twisted around each other Differential signals, noise rejection: Ethernet, RS-485, CAN
Shielded cable Conductors wrapped in foil or braid, plus a drain wire Audio, sensitive signals, noisy environments
Coaxial cable Center conductor, dielectric, braided shield, jacket, all concentric RF, antennas, video, TV (50 Ω and 75 Ω types)
Network cable (Cat5e/Cat6) Four twisted pairs of ~24 AWG Ethernet, and handy multi-core signal cable. Solid for fixed runs, stranded for patch cords
Bus / bare wire Uninsulated copper Ground buses, jumpers on perfboard, sculpture circuits
Wire-wrap wire Very thin (30 AWG) solid wire Wire-wrap prototyping
Building cable (NM-B, "Romex") Two or three solid conductors + bare ground in a jacket Household mains wiring (governed by electrical code)
Automotive primary wire Stranded, oil and heat-resistant insulation Vehicles
Welding cable Extremely fine-stranded, thick, flexible Very high DC current: batteries, inverters, welding

4.6 Color conventions

Colors are conventions, not guarantees. Always verify with a meter.

Low-voltage DC

Mains wiring

Conductor North America Europe/IEC (modern) UK (older)
Hot / live / line Black (also red) Brown Red
Neutral White Blue Black
Ground / earth Green, or bare copper Green/yellow stripes Green

⚠️ In North America, black = hot on mains, while on DC, black = ground. Never assume.

Ethernet (T568B)

White-orange, orange, white-green, blue, white-blue, green, white-brown, brown (pins 1–8). T568A swaps the orange and green pairs.

Hobby servos

Brown/black = ground, red = power, orange/yellow/white = signal.


4.7 Terminating and joining wire


4.8 Did you know?


4.9 Testing wire and cable

Test How Good result
Continuity end to end Meter in continuity mode, power off, one probe each end Beep, near 0 Ω
Intermittent break Hold continuity, then flex the cable along its length and at each end Steady beep. Crackling or dropouts = broken strands
Short between conductors Continuity between each pair of conductors, and to the shield Silent (OL)
Resistance of a long run Ω mode across a conductor Matches the Ω-per-meter × length
Under load Voltage at the source minus voltage at the load, while running Small (a few percent of supply)
Mapping an unmarked cable Short two conductors at the far end, find the pair that beeps, repeat Each conductor identified

4.10 How wire fails

Failure Cause Symptom Fix
Broken strands at a joint Flexing where wire meets a stiff point (solder, crimp, connector) Intermittent, works when wiggled Re-terminate, add strain relief
Cracked solid wire Repeated bending Open circuit Replace with stranded where it moves
Undersized wire Too much current or too long a run Warm or hot wire, low voltage at load Thicker wire, shorter run, higher supply voltage
Corrosion Moisture, especially at cut ends Green/black copper, high resistance Cut back to bright copper; use tinned wire
Insulation damage Sharp edges, heat, UV, rodents Shorts, shocks Grommets, heat-shrink, UV-rated jacket
CCA fatigue Aluminum core work-hardens and breaks Intermittent or open Use pure copper

5 — Connectors

A connector lets you join and separate circuits without soldering. Every connector is a pair of metal contacts held together by spring pressure. That makes each one a small resistance and a potential failure point. Connectors are where a large share of real-world faults live.


5.1 How a connector works

Key specs

Spec Meaning
Pitch Center-to-center spacing of contacts (e.g. 2.54 mm = 0.1")
Current rating Per contact, usually at a stated temperature rise
Voltage rating Set by the spacing and insulation between contacts
Mating cycles How many connect/disconnect cycles before wear (from ~25 for cheap parts to thousands)
Wire range Which AWG the crimp contacts accept
Ingress protection (IP) Dust and water resistance (e.g. IP67 = dust-tight, survives immersion to 1 m)

Gender and naming

"Male" = pins, "female" = sockets. Some families call the free (cable) half the plug and the fixed (panel/board) half the jack or receptacle. Be careful: some families put pins in the plug, others sockets in the plug.


5.2 Board and wire-to-board connectors

Family Pitch Typical current Notes
Pin headers + Dupont housings 2.54 mm ~1–3 A per contact The hobby standard. Unpolarized unless keyed, so easy to plug in offset or backwards
2.0 mm / 1.27 mm headers 2.0 / 1.27 mm ~1 A Compact versions
JST PH 2.0 mm 2 A Small batteries, speakers, sensors. Very common on LiPo cells
JST XH 2.5 mm 3 A Battery balance leads, 3D printers
JST SH 1.0 mm 1 A Tiny. Used by "Qwiic"/"STEMMA QT" I²C modules
JST GH 1.25 mm 1 A Latching. Drones, flight controllers
JST ZH 1.5 mm 1 A Small internal wiring
JST VH 3.96 mm 10 A Power
"JST SM" 2.5 mm 3 A Inline wire-to-wire. Classic on LED strips
Molex KK 254 2.54 mm ~2.5 A Classic friction-lock connector in PCs and appliances
Molex Micro-Fit 3.0 3.0 mm ~5 A PC power (GPU and motherboard power are similar Mini-Fit)
Molex Mini-Fit Jr. 4.2 mm ~9 A ATX motherboard and PCIe power
Molex Picoblade 1.25 mm ~1 A Compact internal wiring
IDC box headers 2.54 / 1.27 mm ~1 A Ribbon cable, keyed with a notch, and press-on termination
FFC/FPC connectors 0.5 / 1.0 mm < 1 A Flat flexible cables. A latch (flip-lock or slide) must be opened before inserting or removing
Board-to-board mezzanine 0.4–1.27 mm varies Stacking boards (e.g. compute modules)
Card edge varies varies Gold "fingers" on a PCB edge slide into a socket: PCIe, RAM, old game cartridges

⚠️ JST is a manufacturer, not a connector. "JST connector" can mean any of a dozen incompatible families. Always identify by pitch and series.


5.3 Terminals and wire joins

Type Description Used for
Screw terminal block (PCB) Wire clamped under a screw, 2.54 / 3.5 / 5.0 / 5.08 mm pitch Field wiring, prototypes
Pluggable terminal block A screw terminal that unplugs from its PCB header Equipment you may need to swap
Spring / push-in terminal A spring clamp, operated by lever or push-in Fast, vibration-resistant
Barrier strip Screw terminals separated by raised barriers Panels, higher voltage
DIN-rail terminal blocks Modular blocks snapped onto a 35 mm rail Control panels
Ring / fork (spade) terminals Crimped onto wire, secured under a screw or stud Battery posts, grounding, power
Quick-disconnect (blade / "spade") terminals Flat 2.8, 4.8 or 6.3 mm tabs and receptacles Switches, appliances, automotive
Bullet connectors Round pin and sleeve RC models, automotive
Butt splices Crimp tube joining two wires end to end Permanent inline joins
Lever connectors Lever-clamp blocks Joining wires without tools
Ferrules Metal sleeve crimped on stranded wire Clean entry into screw terminals

5.4 Power connectors

Connector Details
DC barrel jack Most common: 5.5 × 2.1 mm and 5.5 × 2.5 mm (outer × inner). They look identical but mismatch (loose or won't fit). Others: 3.5 × 1.35, 4.0 × 1.7. Polarity varies: check the symbol on the supply (a dot with + in the center = center-positive, the most common)
XT30 / XT60 / XT90 Polarized high-current DC (≈30/60/90 A bursts). Hobby batteries and power systems
Deans (T-plug) Older high-current RC connector
Anderson Powerpole Genderless, stackable, 15–45 A. Popular in radio and solar
SAE 2-pin Motorcycle/solar maintainer leads. Polarity not standardized. Check
Automotive (cigarette lighter) 12 V socket Center pin positive
IEC 60320 C13/C14 The "kettle"-style mains cord on PCs and monitors. C7/C8 "figure-8" and C5/C6 "cloverleaf" for smaller devices
NEMA 1-15 / 5-15 North American wall plugs (2-prong / 3-prong grounded). Other countries use their own types (Type C, G, I, etc.)
Barrel-plug polarity symbols and a plug end view.
Barrel-plug polarity symbols and a plug end view.

5.5 Signal, data and audio connectors

Connector Details
USB-A / USB-B Classic host (A) and device (B) ends. Blue inserts indicate USB 3.x
Mini-USB / Micro-USB Older small devices. Micro-B is fragile at the solder tabs
USB-C Reversible, 24 pins. Carries power (up to 240 W with PD), data, and video. Needs CC resistors to negotiate power (chapter 21)
3.5 mm / 6.35 mm (¼") audio jacks TS (tip-sleeve, mono/guitar), TRS (tip-ring-sleeve, stereo or balanced), TRRS (headset with mic, two competing standards: CTIA and OMTP)
RCA (phono) Consumer audio/video. Red/white = audio R/L, yellow = composite video
XLR 3-pin locking. Balanced microphone and pro audio
Speakon Locking speaker connector for high power
RJ45 (8P8C) Ethernet. RJ11/RJ12 = telephone (6P)
D-sub (DB9/DE9, DB25, DA15) Serial ports, older PC and industrial gear. VGA is a high-density 15-pin (DE15)
HDMI / DisplayPort / DVI Digital video, with high-speed differential pairs
SMA / BNC / F-type / U.FL RF coaxial: SMA (Wi-Fi/GPS antennas), BNC (test equipment, CCTV), F (TV/satellite), U.FL (tiny board-mounted antenna leads)
Circular / aviation (GX12, GX16, M8, M12) Screw-locking round connectors for sensors and industrial use
Banana (4 mm) and binding posts Test leads, bench supplies, speakers
Alligator / crocodile clips, test hooks Temporary test connections
IC sockets Hold DIP chips so they can be removed. Machined-pin types are more reliable than stamped
SIM / SD / microSD sockets Removable cards. Push-push or hinged

5.6 Waterproof and outdoor connectors


5.7 Crimping, the right way

  1. Match the contact to the wire gauge, and the crimper die to the contact family.
  2. Strip the right length. The copper should fill the wire barrel with a hair protruding. The insulation should sit under the insulation barrel.
  3. Open-barrel contacts have two crimps: the conductor crimp (on bare copper) and the insulation crimp (gripping insulation, for strain relief).
  4. Crimp with a proper tool. Pliers make loose, unreliable crimps.
  5. Tug-test every crimp. It shouldn't pull out.
  6. Insert the contact into the housing until it clicks. The small locking tang should hold it. A contact that pushes back out when mated is a classic intermittent fault.
An open-barrel crimp contact: conductor crimp, insulation crimp and locking tang.
An open-barrel crimp contact: conductor crimp, insulation crimp and locking tang.

A good crimp is a gas-tight cold weld and is more reliable than solder in a vibrating environment. Don't solder a crimped contact. The solder wicks up and makes a stiff, fatigue-prone spot.

Removing a contact from a housing: press down the locking tang (through the small window in the housing) with a pin or extraction tool, then pull the wire gently.


5.8 Did you know?


5.9 Testing connectors

Test How
Pin-to-pin continuity Continuity from each pin to the corresponding wire or far-end pin, power off
Wiggle test Hold continuity (or monitor voltage under load) while flexing the connector and cable
Voltage drop under load Measure across the mated connector (same conductor, both sides) with current flowing. More than ~50–100 mV on a power pin is suspect
Short check Continuity between adjacent pins. Should be open
Visual Look into sockets for spread, bent, or pushed-back contacts, discoloration (heat), corrosion, melted plastic
Retention A contact that slides back when pushed with a probe has a failed lock tang

5.10 How connectors fail

Failure Cause Symptom
Loose / spread socket Wear, oversized probes jammed in Intermittent
Pushed-back contact Not locked into its housing Works until mated firmly, then goes open
Fretting corrosion Micro-movement from vibration or temperature Rising resistance over months
Overheating Current above rating, or a poor crimp Discolored or melted housing, burnt smell
Wrong polarity / offset Unkeyed headers plugged one pin over, or barrel polarity mismatch Nothing works, or damage
Cracked solder at board-mounted connectors Mechanical stress from cable pulls Intermittent. Visible ring crack around the pin
Contamination Flux, dust, oxidation High resistance
Wrong family A "similar" connector from another family forced to fit Loose, poor contact

6 — Switches and relays

A switch opens or closes a circuit by moving metal contacts together or apart. A relay is a switch operated by an electromagnet instead of a finger. They're the simplest components in electronics, yet ratings, contact bounce, and arcing make them more interesting than they first appear.


6.1 Poles, throws and states

Term Meaning
Pole The number of separate circuits the switch controls at once
Throw The number of positions each pole can connect to
SPST Single pole, single throw: a simple on/off
SPDT Single pole, double throw: a common terminal connects to one of two others ("changeover")
DPST Two independent on/off circuits, moved together
DPDT Two SPDTs moved together. Handy for reversing a motor
ON-ON SPDT with no middle position
ON-OFF-ON SPDT with a center-off position
(ON)-OFF Parentheses mark a momentary position that springs back
NO (normally open) Open until actuated
NC (normally closed) Closed until actuated
Break-before-make Opens one contact before closing the next (the usual)
Make-before-break Closes the new contact before opening the old, so the circuit never goes dead
SPST, SPDT, DPST and DPDT switches.
SPST, SPDT, DPST and DPDT switches.

Momentary switches return when released. Latching (maintained) switches stay put.


6.2 Types of switch

Type Description Typical use
Toggle A lever flipped between positions Panel on/off, mode selection
Rocker A seesaw paddle, often illuminated Power switches on appliances and power strips
Slide A sliding actuator, usually SPDT Small power switches, mode selection
Push button (momentary) Contacts close while pressed Doorbells, reset buttons, arcade buttons
Push button (latching) Push on, push off Flashlights, power buttons on older equipment
Tactile (tact) switch Small PCB button (6×6 mm, 12×12 mm) with a crisp "click" Microcontroller inputs, keypads
DIP switch A row of tiny slide or rocker switches in an IC-sized package Configuration settings
Rotary switch A knob selecting one of several positions, 1–4 poles Mode selectors, multimeter dials
Micro switch (snap-action) A lever or plunger that snaps contacts over at a precise point Limit switches, door interlocks, mouse buttons
Limit switch A rugged micro switch with a roller or lever Machines: detecting end of travel
Reed switch Two flexible contacts sealed in a glass tube, closed by a magnet Door/window sensors, float switches, bike speedometers
Tilt / ball switch A metal ball (or, historically, mercury) that rolls to make contact Tilt detection, anti-tamper
Key switch Operated by a physical key Security, machine enable
Keyboard switches Mechanical key switches ("MX-style"), membrane, scissor Keyboards
Membrane switch Printed conductive layers pressed together through a spacer Appliance panels, remote controls
Foot switch Floor-mounted pedal Tools, music effects
Thumbwheel / BCD switch Digit wheel outputting a binary code Setting numeric values
Emergency stop Large red mushroom button, latching, usually NC Machinery safety
Pressure / float / flow switches Actuated by a physical quantity Pumps, tanks, HVAC

6.3 Ratings

Every switch has voltage and current ratings, often separate for AC and DC:


6.4 Contact bounce

When metal contacts close, they bounce several times over roughly 1–20 ms before settling. A person sees one press, but a fast microcontroller may see several.

One button press as a microcontroller sees it.
One button press as a microcontroller sees it.

Chapter 25 covers wiring buttons to microcontrollers.


6.5 Relays

How a relay works

A coil wound around an iron core becomes an electromagnet when current flows. It pulls a hinged iron armature, which moves one or more switch contacts. When the coil is switched off, a spring returns the armature. The coil and the contacts are electrically isolated, so a small, safe signal can control a large or dangerous circuit.

Reading a relay

Spec Meaning
Coil voltage Nominal operating voltage (3, 5, 12, 24 V DC; 120/230 V AC)
Coil resistance / current e.g. 5 V coil, 70 Ω → about 70 mA. Too much for a microcontroller pin to drive directly
Pick-up (must-operate) voltage The minimum that reliably closes it (often ~75 % of nominal)
Drop-out voltage Below this it releases
Contact form 1 Form A = SPST-NO, Form B = SPST-NC, 1 Form C = SPDT (common, NO, NC)
Contact rating e.g. 10 A 250 V AC / 10 A 30 V DC (resistive)
Operate / release time Typically 5–15 ms
Mechanical / electrical life e.g. 10 million operations unloaded, 100,000 at full load

Terminal labels: COM (common), NO (normally open), NC (normally closed), and two coil terminals (sometimes marked + and − if the relay has a built-in diode or LED).

Driving a relay from a microcontroller

A relay coil draws too much current for a logic pin, and it's an inductor, so switching it off produces a high-voltage spike (chapter 11). The standard driver:

The standard relay driver: transistor, base resistor and flyback diode.
The standard relay driver: transistor, base resistor and flyback diode.

Types of relay

Type Description
General-purpose electromechanical The classic "sugar cube" PCB relay
Automotive relay 12 V coil, high-current contacts, standard pin numbers (30, 85, 86, 87, 87a)
Latching (bistable) relay Stays in its last position with no coil power. Pulsed to change. Saves energy
Reed relay A reed switch inside a coil. Fast, small, low-current, very long life
Signal relay Small, gold contacts, for low-level signals
Power relay / contactor Large contacts for motors and heaters. Contactors are heavy-duty relays for industrial loads
Time-delay relay Built-in timer delays operation or release
Solid-state relay (SSR) No moving parts. Uses semiconductors (chapter 18)

6.6 Did you know?


6.7 Testing switches and relays

Switches (power off):

Relays:


6.8 How they fail

Failure Cause Symptom
Burned / pitted contacts Arcing, over-current, DC loads, inductive loads High resistance, heating, intermittent
Welded contacts Large inrush current fused the contacts together Switch or relay stuck ON
Dirty / oxidized contacts Age, low current (no wetting), environment Intermittent, needs several presses
Broken spring or actuator Mechanical wear Doesn't return, or doesn't click
Open relay coil Over-voltage, corrosion, broken fine wire Relay never clicks
Driver transistor dead Missing flyback diode Relay stops working after some uses
Contact bounce errors No debouncing Multiple counts per press
Relay chatters Coil voltage too low or unstable Rapid clicking, arcing

To reduce contact wear on inductive loads, add a snubber (a resistor + capacitor in series across the contacts) for AC loads, or a flyback diode across the load for DC loads.

7 — Fuses and circuit protection

Protection components sit quietly doing nothing until something goes wrong: a short, a surge, a reversed battery, a static spark. Then they sacrifice themselves, or divert the energy, so that wiring, equipment, and people aren't harmed.

The single most important idea: a fuse protects the wiring (and prevents fire). It doesn't make a faulty device work, and it isn't sized to the device's needs.


7.1 Fuses

How a fuse works

A fuse contains a thin metal element that heats as current passes (heat = I² × R). At its rated current it stays cool enough. At a significant overload it melts ("blows") and opens the circuit. The time it takes depends on how large the overload is: a dead short blows it in milliseconds, and a mild 50 % overload may take minutes or hours.

Fuse ratings

Spec Meaning
Current rating The current it carries continuously without blowing. Many fuses are designed to run at ≤ 75 % of this
Voltage rating The maximum voltage it can safely interrupt. It can be used at any lower voltage, but never higher
Breaking capacity (interrupting rating) The maximum fault current it can safely clear, e.g. 35 A (glass, "L") or 1,500 A (ceramic, "H")
Speed F / FF (fast / very fast): protect semiconductors. T (time-lag / slow-blow): tolerate inrush surges from motors, transformers, and capacitors
I²t (melting energy) How much energy it takes to blow. Used to match fuses to surge-sensitive parts
Fast fuses blow on brief surges; time-lag fuses ride through them.
Fast fuses blow on brief surges; time-lag fuses ride through them.

Reading a glass fuse cap: T3.15AL250V = time-lag, 3.15 A, low breaking capacity, 250 V.

Types of fuse

Type Description
5 × 20 mm cartridge Glass or ceramic tube. The electronics standard worldwide
6.3 × 32 mm (¼ × 1¼", "3AG") Larger cartridge, common in North American equipment and older automotive
Blade fuses (ATO/ATC, mini, micro, maxi) Color-coded by current. Automotive and DC power distribution
Midi / mega / ANL fuses Bolt-down fuses for very high DC current (battery banks, inverters)
SMD fuses Tiny chip fuses on PCBs
Thermal fuse (thermal cutoff) Opens at a set temperature rather than current. Found in motors, transformers, hair dryers, coffee makers. One-shot
Plug fuses (BS 1362) UK mains plugs contain a cartridge fuse (3, 5 or 13 A)
Semiconductor fuses Ultra-fast, for protecting power electronics

Sizing a fuse

  1. Find the wire's safe current (chapter 4). The fuse must blow below this.
  2. Find the circuit's normal maximum current and any inrush. The fuse must hold above this.
  3. Pick a rating between the two, choose slow-blow if there's inrush, and check the voltage and breaking capacity.
  4. Place the fuse as close to the power source as possible, on the positive (or live) side. Everything upstream of the fuse is unprotected.
  5. When one source feeds several wires of different sizes, fuse each branch for its own wire.
One fuse per branch, each sized for its own wire.
One fuse per branch, each sized for its own wire.

💡 A large power supply's own short-circuit protection doesn't protect thin wiring. A 20 A supply can happily push 15 A through a thin wire, and that's well within the supply's rating, while the wire overheats. Branch fuses solve this.


7.2 Resettable fuses (PTC / polyfuse)

A polymeric PTC is a small component (often a yellow disc or an SMD chip) containing a polymer loaded with carbon. At normal current it conducts. When overloaded it heats, the polymer expands, the carbon particles separate, and resistance jumps to a high value, limiting current to a trickle. Remove the fault and let it cool, and it resets.


7.3 Circuit breakers and mains protection

Device Protects against How
Circuit breaker (MCB) Overload and short circuit Thermal (a bimetal strip bends with heat, for slow overloads) plus magnetic (a coil trips instantly on a large fault). Resettable
GFCI (US) / RCD (elsewhere) Electric shock Compares current in the hot and neutral. If they differ by more than ~5 mA (GFCI) or 30 mA (RCD), current is leaking somewhere, possibly through a person, so it trips in milliseconds
AFCI Arcing faults (damaged cords, loose connections) Detects the electrical signature of arcing and trips. Prevents fires
Surge protector Voltage spikes MOVs divert spikes to ground (see below)

💡 A breaker or fuse protects wiring from fire. A GFCI/RCD protects people from shock. A person can be fatally shocked by a current far too small to blow a fuse.


7.4 Overvoltage and surge protection

Component How it works Speed Typical use
TVS diode A diode designed to avalanche at a set voltage and absorb large, brief surges Picoseconds–nanoseconds Data lines, USB, automotive transients, power inputs
ESD protection diode arrays Tiny, low-capacitance TVS diodes Very fast USB, HDMI, buttons, anything a person touches
Zener diode Conducts in reverse above its Zener voltage Fast, lower energy Clamping low-power signals
MOV (metal-oxide varistor) A disc whose resistance drops sharply above a threshold voltage Nanoseconds Mains surge suppression in power strips and supplies. Degrades with each large surge
GDT (gas discharge tube) A sealed gas gap that arcs over at high voltage Microseconds Telecom lines, antennas: large surges like nearby lightning
Crowbar circuit An SCR (chapter 18) that deliberately shorts the supply on overvoltage, blowing the fuse Fast Protecting expensive loads from a failed regulator

These are often layered: a GDT for the huge energy, a MOV for the mid-range, and a TVS diode for the fast final clamp.


7.5 Reverse-polarity protection

Connecting a battery backwards destroys many circuits in an instant. Options:

Method Voltage lost Notes
Series diode ~0.7 V (silicon) / 0.3–0.4 V (Schottky) Simple. Wastes power as heat at high current
Shunt diode + fuse None in normal use A reversed diode across the input shorts a reversed supply and blows the fuse
P-channel MOSFET Tiny (I² × Rds(on)) A MOSFET arranged so it only turns on with correct polarity. Very efficient
Ideal-diode controller IC Tiny A MOSFET plus a controller. Also blocks backfeeding
Keyed connectors None Prevents the mistake mechanically. The best first line

7.6 Inrush current limiting

When a device with large input capacitors is switched on, they briefly act like a short circuit, drawing a big current spike that can blow fuses, weld switch contacts, or trip breakers.


7.7 Electronic protection (eFuses and load switches)

Modern boards often use ICs instead of fuses:


7.8 Did you know?


7.9 Testing protection components

Component Test Good Bad
Fuse Continuity, removed or unpowered Beep, ~0 Ω OL (blown)
Fuse in a live circuit DC/AC volts across the fuse ~0 V Supply voltage across it = blown
Glass fuse (visual) Look at the element Intact Broken wire = overload; blackened or silvered glass = hard short
PTC Ω when cold Low (fractions of an ohm to a few ohms) High when cold = damaged
Thermal fuse Continuity Closed Open (tripped; replace and find the overheating cause)
TVS / Zener Diode test Normal diode reading one way (bidirectional TVS reads open both ways) Short both ways (a failed TVS usually fails short)
MOV Ω Very high (open) Low or shorted, or cracked and charred
Breaker / GFCI Press TEST (GFCI) Trips Doesn't trip: replace

7.10 How protection fails (and what it tells you)

Observation Meaning
Fuse blows immediately on power-up A short circuit downstream, or huge inrush. Never fit a larger fuse. Find the fault
Fuse blows after running for a while Sustained overload: a stalled motor, failing component, undersized fuse for real load
Fuse blows occasionally Inrush near the fuse's limit (use slow-blow), or an intermittent short
Fuse is fine but nothing works The fault is elsewhere, or the fuse holder contacts are corroded
TVS diode shorted It absorbed more than it could. There was a surge or a sustained over-voltage
MOV cracked or burnt Large surges, or a long over-voltage
PTC keeps tripping Real overload, or it has degraded after many trips
Device resets when plugged in Missing inrush limiting, or a weak supply

8 — Resistors

The resistor is the most common component in electronics. It resists current by a fixed, known amount, and that simple behavior does a remarkable number of jobs: limiting current, setting voltages, holding signals steady, measuring current, and setting the behavior of chips.


8.1 How it works

Resistance comes from electrons bumping into the atoms of the material they flow through. Every collision turns a little of their energy into heat. A resistor is a carefully controlled amount of a material that resists flow more than copper does.

A conductor's resistance depends on three things:

That's why resistors are made from thin films, fine wire, or carbon mixtures. It's also why wires themselves have (small) resistance.

A resistor obeys Ohm's law exactly: V = I × R. It has no polarity and works the same both ways round, with AC or DC. Whatever power it absorbs, P = I² × R, becomes heat.


8.2 Types of resistor

Type Construction Tolerance Strengths Weaknesses Typical use
Carbon composition Carbon powder and binder, molded ±5–20 % Survives brief high-energy pulses Drifts with age and humidity, noisy Vintage gear, surge/pulse duty
Carbon film Thin carbon film on a ceramic rod, spiral-cut to value ±2–5 % Cheap Moderate stability General-purpose through-hole (usually beige body)
Metal film Nickel-chromium film on ceramic, spiral-cut ±0.1–1 % Accurate, stable, low noise Less pulse-tolerant Precision through-hole (usually blue body)
Metal oxide Tin-oxide film ±1–5 % High temperature, good for power Less precise 1–5 W power resistors
Wirewound Resistance wire wound on a former ±0.1–5 % High power, very precise possible Has inductance (it's a coil) Power resistors, shunts, loads
Cement / ceramic power Wirewound or oxide in a white ceramic block ±5 % 5–20 W, cheap Bulky, hot Power supplies, dummy loads
Aluminum-housed Wirewound in a finned metal case ±1–5 % 10–100 W+ when bolted to a heatsink Needs a heatsink Load banks, braking resistors
Thick film SMD (chip) Resistive paste printed on a ceramic chip ±1–5 % Tiny, cheap, the default on modern boards Limited power Everything surface-mount
Thin film SMD Sputtered metal film ±0.01–1 % Precise, low drift Costlier Precision measurement
Current-sense (shunt) Very low value (mΩ), metal strip or foil ±0.5–1 % Accurate low resistance — Measuring current
Resistor network / array Several resistors in one SIP or SMD package, often sharing a common pin ±2 % Saves space Common-pin arrangement must match the need Pull-up banks, LED arrays
Zero-ohm resistor (jumper) A resistor-shaped link, one black band or "0" — Lets automated machines place jumpers — PCB links, configuration options
Fusible resistor Designed to open safely on overload ±5 % Acts as a fuse — Power supply inputs

8.3 Reading resistor values

Color code (through-hole)

Color Digit Multiplier Tolerance Temp. coefficient
Black 0 × 1 — 250 ppm/K
Brown 1 × 10 ±1 % 100 ppm/K
Red 2 × 100 ±2 % 50 ppm/K
Orange 3 × 1 k ±0.05 % 15 ppm/K
Yellow 4 × 10 k ±0.02 % 25 ppm/K
Green 5 × 100 k ±0.5 % 20 ppm/K
Blue 6 × 1 M ±0.25 % 10 ppm/K
Violet 7 × 10 M ±0.1 % 5 ppm/K
Grey 8 × 100 M ±0.01 % 1 ppm/K
White 9 × 1 G — —
Gold — × 0.1 ±5 % —
Silver — × 0.01 ±10 % —
None — — ±20 % —

Mnemonic for 0–9: Bad Beer Rots Our Young Guts But Vodka Goes Well.

Decoding 4-band and 5-band resistors.
Decoding 4-band and 5-band resistors.

SMD codes

Style Example Value
3-digit (5 % parts) 103 10 × 10³ = 10 kΩ
471 47 × 10 = 470 Ω
4R7 4.7 Ω (R marks the decimal point)
4-digit (1 % parts) 1002 100 × 10² = 10 kΩ
4991 499 × 10 = 4.99 kΩ
EIA-96 (1 %, tiny parts) 01C Code 01 = 100, C = × 100 → 10 kΩ (needs a lookup table)
Zero ohm 0 or 000 Jumper
Shunts R010 0.010 Ω = 10 mΩ

SMD sizes

Named by length × width in hundredths of an inch (imperial): 0201, 0402, 0603, 0805, 1206, 2512. 0805 (2.0 × 1.25 mm) and 1206 are hand-solderable. 0402 and smaller need a steady hand and magnification. Bigger packages handle more power (0603 ≈ 0.1 W, 1206 ≈ 0.25 W, 2512 ≈ 1 W).


8.4 The specs that matter

Spec Meaning Rule of thumb
Resistance Value in Ω Pick from standard series (below)
Tolerance How far the actual value may differ 1 % is the modern default and costs pennies
Power rating Heat it can shed at a stated ambient temperature Use at most half the rating for longevity. Through-hole: ⅛, ¼, ½, 1 W and up
Temperature coefficient (TCR) Change per °C, in ppm/K Matters for precision circuits
Maximum voltage Limit before arcing over the body ~200–500 V for common through-hole. Matters in mains and high-voltage dividers
Pulse rating Short-surge capability Carbon comp and wirewound excel
Noise Random electrical noise it adds Metal film is lowest

Standard values (E-series)

Resistors are made in logarithmically spaced "preferred values," so every value is within tolerance of its neighbors:

Each is multiplied by powers of 10: 4.7 Ω, 47 Ω, 470 Ω, 4.7 kΩ, 47 kΩ, 470 kΩ, 4.7 MΩ.


8.5 Combining resistors


8.6 What resistors are used for

Current limiting

Protects parts that would otherwise draw too much current, most famously LEDs: R = (V_supply − V_LED) ÷ I_LED (chapter 14). Also used on transistor bases (chapter 16), and in series with inputs to limit fault currents.

Voltage divider

Two resistors in series across a voltage produce a fraction of it at their junction:

V_out = V_in × R2 ÷ (R1 + R2) (R2 is the one to ground)

A voltage divider scaling 12 V down to 3 V.
A voltage divider scaling 12 V down to 3 V.

Pull-up and pull-down resistors

A digital input connected to nothing floats: it picks up stray charge and reads at random. A pull-up resistor ties it gently to the supply (reads HIGH by default), and a pull-down ties it to ground (reads LOW by default). A switch or open-drain output can then overpower the resistor to change the state.

A floating input versus one with a pull-up resistor.
A floating input versus one with a pull-up resistor.

Current sensing (shunts)

A small, known resistance in the current path develops a voltage proportional to the current: I = V ÷ R. A 0.1 Ω shunt carrying 2 A drops 0.2 V. Current-sense amplifier chips (e.g. INA219, INA226) read such shunts precisely. Keep shunts small so they don't waste voltage or power. Place them in the ground ("low side") or supply ("high side") path.

Setting chip behavior

Many ICs read a resistor to set a value: a charger's charge current, an LED driver's output current, a regulator's output voltage, a timer's period, or the USB-C "I'm a device" signal (5.1 kΩ on the CC pins).

Termination and damping

Small series resistors (22–470 Ω) on fast signal lines absorb reflections and ringing. Long transmission lines are terminated with a resistor matching the cable impedance (e.g. 120 Ω across the ends of an RS-485 or CAN bus).

Bleeder resistors

A high-value resistor across a large capacitor slowly discharges it after power-off, for safety.

Heaters and loads

Resistors are deliberately used as heaters (in 3D-printer beds, defrosters, incubators) and as dummy loads for testing power supplies.


8.7 Did you know?


8.8 Testing resistors

  1. Power off, and discharge any capacitors in the circuit.
  2. Multimeter on Ω. Probe across the resistor.
  3. Read the value and the unit (Ω, kΩ, MΩ).
  4. Compare with the marking, allowing for tolerance.

Tips:


8.9 How resistors fail

Failure Cause Symptom
Open circuit Overheated, cracked, film burned through Reads OL. The downstream circuit is dead
Value drift (usually upward) Age, heat, humidity; carbon comp especially Circuit works "wrong": dim LEDs, wrong voltages, timing off
Burned / charred Sustained overload Discolored body, burnt smell, cracked coating. Always find why: usually a shorted part downstream
Short Very rare in resistors themselves; usually a solder bridge Reads ~0 Ω
Intermittent Cracked SMD resistor (board flex) or cracked joint Works when pressed or warm

A burned resistor is almost always a symptom. Replacing it without finding the shorted transistor, capacitor, or diode that overloaded it usually burns the new one too.

9 — Potentiometers and resistive sensors

Some resistors are meant to change. Potentiometers change when you turn a knob. Thermistors, photoresistors, force sensors, and strain gauges change with temperature, light, pressure, or bending. They're among the simplest ways to connect the physical world to a circuit.


9.1 Potentiometers

How a pot works

A potentiometer ("pot") is a resistive track with a terminal at each end and a third terminal, the wiper, that slides along the track. Turning the shaft moves the wiper.

A potentiometer as a divider and as a variable resistor, plus linear vs audio taper.
A potentiometer as a divider and as a variable resistor, plus linear vs audio taper.

Pins are usually numbered 1, 2 (wiper, middle), 3. Swapping 1 and 3 reverses the direction of rotation.

Types of potentiometer

Type Description Use
Rotary panel pot Shaft through a panel, 270–300° rotation Volume, tone, user controls
Slide pot (fader) Linear sliding travel Mixing desks, equalizers
Trimmer (trimpot) Small, screwdriver-adjusted, set once Calibration: contrast, voltage set points
Multi-turn trimmer 10–25 turns end to end, often a blue rectangle with a brass screw Fine adjustments: adjustable power modules
Multi-turn precision pot 10-turn helical, with a counting dial Lab instruments
Dual-gang pot Two pots on one shaft Stereo volume
Pot with switch Clicks off at one end Old radios: volume + power
Motorized pot A pot a motor can turn Remote-controlled volume on audio gear
Digital potentiometer An IC with a resistor ladder and electronic switches, set via I²C/SPI Microcontroller-controlled gain or level
Membrane / soft pot Flat touch strip whose wiper is your finger Thin position sensors

Taper


9.2 Thermistors (temperature-dependent resistors)

A thermistor's resistance changes strongly with temperature.

Type Behavior Uses
NTC (negative temperature coefficient) Resistance falls as it warms Temperature measurement (10 kΩ at 25 °C is common), inrush limiters in power supplies, battery pack temperature sensing
PTC (positive temperature coefficient) Resistance rises sharply above a switching temperature Resettable fuses (chapter 7), self-regulating heaters, motor over-temperature sensing, degaussing in old CRT TVs

Related temperature-sensing resistors:


9.3 Photoresistors (LDRs)

A light-dependent resistor is made of cadmium sulfide (CdS). Its resistance drops as light increases, from mega-ohms in darkness to a few hundred ohms or kilo-ohms in bright light.


9.4 Force, flex and strain sensors

Sensor How it works Characteristics Uses
FSR (force-sensitive resistor) Conductive polymer layers; pressing brings particles into contact Resistance drops from >1 MΩ (no touch) to ~kΩ with pressure. Good for "how hard," poor for precise weight Touch pads, drum triggers, presence under a cushion
Flex sensor Conductive ink on a plastic strip; bending stretches the ink and raises resistance Maybe 25 kΩ flat to 100 kΩ bent Data gloves, bend detection
Strain gauge A fine metal foil zigzag bonded to a surface; stretching raises resistance by a tiny amount Changes of a fraction of a percent. Needs a Wheatstone bridge and an amplifier (e.g. HX711) Load cells in kitchen and bathroom scales, structural monitoring
Conductive rubber / velostat Pressure-sensitive sheet Cheap, DIY-friendly Pressure mats, wearable sensors

The Wheatstone bridge

Four resistors in a diamond, fed with voltage across two opposite corners. The voltage between the other two corners is zero when the bridge is balanced. It swings positive or negative as one resistor (the sensor) changes. The bridge turns tiny resistance changes into a small voltage that an amplifier can boost. It's the basis of load cells, many pressure sensors, and precision measurement generally.

A thermistor divider, and a Wheatstone bridge for strain gauges.
A thermistor divider, and a Wheatstone bridge for strain gauges.

9.5 Other resistive sensors


9.6 Did you know?


9.7 Testing

Part Test Good result
Pot Ω between the two outer pins Close to the marked value, constant as you turn
Pot wiper Ω from wiper to one end while slowly turning Smooth rise or fall, no jumps or open spots (a meter with a bar graph helps)
NTC thermistor Ω at room temperature, then warm it with your fingers Near R25, and falls when warmed
PTC Ω cold, then warm Low cold, rises sharply past its trip point
LDR Ω covered vs under a lamp Very high dark, low light
FSR Ω untouched vs pressed Open or very high → falls with pressure
Strain gauge Ω Its nominal value (often 120 Ω or 350 Ω)

9.8 How they fail

Failure Symptom Cause
Worn or dirty pot track Crackling audio, jumpy readings, dead spots Wear, dust, oxidation. Clean with contact cleaner or replace
Open wiper Output jumps to one extreme Worn contact
Drifted thermistor Temperature readings consistently off Age, overheating. Recalibrate or replace
Cracked thermistor bead Open circuit, wild readings Mechanical stress, thermal shock
LDR slow or insensitive Late response Aging, dirty window
Corroded moisture probe Readings drift, then fail Continuous DC powering. Pulse the power
FSR inconsistent Readings vary between presses Normal behavior. FSRs are qualitative, not precise

10 — Capacitors

A capacitor stores electrical energy in an electric field, and gives it back very quickly. It's a tiny, fast-acting reservoir of charge. Capacitors smooth power supplies, filter noise, set timing, pass audio signals while blocking DC, and supply sudden bursts of current. After resistors, they're the most common component.


10.1 How it works

A capacitor is two conductive plates separated by an insulator called the dielectric. Current can't flow through the dielectric. But when you apply a voltage, electrons pile up on one plate and are pushed off the other. The plates become charged, and energy is stored in the field between them.

Water analogy: a pipe blocked by a stretchy rubber membrane. Push water in and the membrane stretches, storing the push. No water passes through, but water moves on both sides while it stretches. Release the pressure and the membrane pushes the water back.

Consequences:

  1. A capacitor resists sudden changes in voltage. It has to charge or discharge first, which smooths out dips and spikes.
  2. It blocks steady DC once charged, but passes changes (AC, pulses, noise).
  3. It can deliver a burst of current faster than a distant power supply can.

Capacitance

Measured in farads (F). One farad is enormous, so practical values are:

1 µF = 1,000 nF = 1,000,000 pF.

Capacitance increases with larger plate area, thinner dielectric, and a dielectric with a higher permittivity. That's why high-value capacitors roll up long foils, or stack hundreds of thin ceramic layers.

Charging and the RC time constant

Charged through a resistor, a capacitor's voltage rises quickly at first and then more slowly, following a curve. The time constant τ = R × C (seconds, with R in ohms and C in farads):

Example: 10 kΩ × 100 µF = 1 second. Discharge follows the mirror-image curve.

Charging (solid) and discharging (dashed) through a resistor.
Charging (solid) and discharging (dashed) through a resistor.

Energy stored

E = ½ × C × V² (joules). A 1,000 µF capacitor at 50 V stores 1.25 J, enough to make a startling spark. A 1 F supercap at 5 V stores 12.5 J.

Capacitors and AC (reactance)

A capacitor "resists" AC less as frequency rises. Its reactance is X_C = 1 ÷ (2π × f × C). A 100 nF cap is about 1.6 kΩ at 1 kHz, but only 1.6 Ω at 1 MHz. That's why small ceramic caps are so good at shunting high-frequency noise to ground.


10.2 Types of capacitor

Type Range Polarized? Strengths Weaknesses Typical use
Ceramic (MLCC) 1 pF–100 µF No Tiny, cheap, very low ESR, fast Class 2 types lose capacitance with voltage and temperature; can crack; some "sing" (piezoelectric) Decoupling, filtering, timing (C0G)
Ceramic disc 1 pF–100 nF No Cheap, high-voltage versions available Class 2 variability Through-hole general use, safety caps
Aluminum electrolytic 0.1 µF–1 F Yes Large capacitance per dollar Dries out over years; higher ESR; limited life, worse when hot Power supply bulk and smoothing, audio coupling
Aluminum polymer 1 µF–2,000 µF Yes Very low ESR, long life, safe failure Lower voltages, costlier Motherboards, switching-regulator outputs
Tantalum 0.1 µF–1,000 µF Yes Small, stable Fails short, sometimes burning, when over-voltaged or reversed; needs derating (use ≤ 50 % of rating) Compact power filtering
Film (polyester/Mylar, polypropylene) 1 nF–100 µF No Stable, low loss, self-healing, tolerate high voltage Bulky Audio, timing, snubbers, motor-run caps, mains filtering
Mica (silver mica) 1 pF–10 nF No Extremely stable, precise Expensive, small values RF, oscillators
Supercapacitor (EDLC) 0.1–3,000 F Yes Huge capacitance, millions of cycles Low voltage (~2.7 V per cell), high self-discharge, stores much less energy than a battery Memory backup, burst power, energy harvesting
Variable / trimmer a few–hundreds pF No Adjustable Small values Radio tuning, oscillator trimming
Safety caps (X and Y class) nF range No Rated to fail safely on mains — X: across line and neutral. Y: line to ground (fails open, protects against shock)

Ceramic dielectric classes

Code Class Behavior Use
C0G / NP0 1 Almost no change with temperature or voltage Timing, filters, oscillators
X7R / X5R 2 ±15 % over temperature; loses capacitance under DC voltage General decoupling
Y5V / Z5U 2/3 Wildly variable (can lose 80 % of value) Cheap, non-critical bypass only

💡 DC-bias derating: a small 10 µF X5R capacitor rated 6.3 V might provide only 3–4 µF when it's actually sitting at 5 V. For critical values, choose a larger package and a higher voltage rating, or check the maker's DC-bias curves.


10.3 Reading capacitors

Ceramic, aluminum electrolytic and tantalum capacitors, and which end is which.
Ceramic, aluminum electrolytic and tantalum capacitors, and which end is which.

Ceramic codes (value in pF)

Two significant digits, then the number of zeros:

Code Value
22 or 220 22 pF
101 100 pF
102 1 nF
103 10 nF
104 100 nF = 0.1 µF (the most common capacitor)
105 1 µF
4n7 4.7 nF

A letter after the code is the tolerance: J = ±5 %, K = ±10 %, M = ±20 %, Z = +80/−20 %. So 104K = 100 nF ±10 %.

Electrolytics

Tantalum

SMD ceramics

Usually unmarked. Measure them, or keep them in labelled reels.


10.4 The specs that matter

Spec Meaning Rule of thumb
Capacitance Storage Often ±10–20 %. Don't rely on exact values unless precision types
Voltage rating Maximum continuous DC voltage Use ≥ 1.5–2× the working voltage (tantalum ≥ 2×)
ESR (equivalent series resistance) Internal resistance Low ESR matters for switching regulators and ripple current
Ripple current AC current it can carry without overheating Critical in power supplies
Temperature rating / lifetime e.g. 2,000 h at 105 °C Electrolytic life roughly doubles for every 10 °C cooler
Leakage current DC that sneaks through Matters in timing and low-power circuits
Tolerance / dielectric Stability C0G for precision, X7R for general use

10.5 Combining capacitors

Capacitors combine the opposite way to resistors:


10.6 What capacitors are used for

Decoupling (bypass) capacitors

Digital chips draw current in tiny, sharp spikes every time their transistors switch. The supply wiring can't respond fast enough, so the local voltage wobbles. A 100 nF ceramic placed right at the chip's power pins supplies those spikes locally. Every IC needs one, as close to its pins as possible. Many designs add a 1–10 µF cap nearby too.

A bulk capacitor near the load and a 100 nF decoupling capacitor at the chip.
A bulk capacitor near the load and a 100 nF decoupling capacitor at the chip.

Bulk capacitance

A larger electrolytic (10–1,000 µF+) near loads that draw sudden big currents (motors, LED strips, radio transmitters, amplifiers) covers the dip until the supply catches up. It prevents brownout resets and glitches.

Smoothing and filtering

Coupling (DC blocking)

A capacitor in series with a signal passes the AC part (audio, for example) while blocking any DC offset. That lets you connect amplifier stages sitting at different DC levels.

Timing

RC charging times set the frequency of oscillators, the length of 555 timer pulses (chapter 28), and power-on reset delays.

Energy storage and pulses

Camera flashes, defibrillators, spot welders, and coilguns dump a charged capacitor's energy in milliseconds. Supercapacitors keep clocks and memory alive during power cuts.

Snubbers and noise suppression

A capacitor (often with a resistor) across relay contacts, switches, or motor terminals absorbs arcs and electrical noise. A 100 nF ceramic across a brushed DC motor's terminals is standard practice.

Motor start and run capacitors

Single-phase AC motors (fans, compressors, pumps) use film or special electrolytic capacitors to create a phase-shifted current that makes them start and run. A failed start capacitor is a classic "motor hums but won't turn" fault.

Sensing

Capacitive sensing measures how a nearby finger, liquid, or object changes a capacitance. It's used in touchscreens, touch buttons, proximity sensors, and soil moisture and liquid level sensors (chapters 25, 26).


10.7 Did you know?


10.8 Testing capacitors

Safety first: discharge any capacitor over a few volts before handling. Use a resistor (e.g. 1 kΩ, 1–5 W for large caps) across the terminals for several seconds, not a screwdriver, which can pit the terminals and throw sparks. Then confirm ~0 V with a meter.

Test How Good Bad
Visual Look at the part Flat top, straight, no residue Domed or bulging top, leaking crust, swollen base, cracked ceramic, burnt tantalum
Capacitance Meter's capacitance mode, out of circuit Within tolerance (±20 % for electrolytics) Far below value (dried out), or reads nothing (open)
Short check Continuity or Ω Brief beep or rising reading as it charges, then open Steady beep, ~0 Ω = shorted
Resistance method (meters without capacitance mode) Ω mode on a larger cap Reading climbs as the cap charges from the meter Stays at 0 (short) or immediately OL (open, for large caps)
ESR ESR meter, often in-circuit Low (depends on value and voltage) High ESR = worn-out electrolytic, even if capacitance reads fine
In operation Scope or AC-mV across a supply cap Small ripple Large ripple = failing filter cap

10.9 How capacitors fail

Failure Cause Symptom
Dried-out electrolytic (high ESR, low capacitance) Age, heat, ripple current Power supply hum, ripple, devices that won't start or reboot randomly, amplifier hum. The #1 failure in old electronics
Bulged / vented electrolytic Over-voltage, reversed polarity, heat, bad electrolyte Visible dome, leaked residue
Shorted tantalum Over-voltage spike, reversed polarity, surge current Supply shuts down; the cap may burn or catch fire
Cracked ceramic Board flexing, thermal shock, rough soldering Intermittent, or a short (can overheat)
Open Broken lead or internal connection No filtering effect
Leaky Aging dielectric Timing circuits run wrong, battery drain
Reversed electrolytic Assembly mistake Heats, bulges, may pop within seconds to hours
Capacitance loss (class 2 ceramics) DC bias, aging Filters and timing drift

When replacing electrolytics: same capacitance, same or higher voltage, same or better temperature rating (105 °C), and low-ESR types in switching supplies.

11 — Inductors and transformers

An inductor is a coil of wire that stores energy in a magnetic field. A transformer is two or more coils sharing a magnetic core, transferring energy from one to the other. They're the reason switching power supplies are efficient, the reason AC can be sent across countries, and the reason switching off a relay can destroy a transistor.


11.1 How an inductor works

Any current through a wire creates a magnetic field around it. Coil the wire and the fields add up. Wind it around iron or ferrite and the field becomes far stronger. That field stores energy.

The key behavior: an inductor resists changes in current.

Water analogy: a heavy water wheel or turbine in the pipe. Start pushing and it takes time to spin up, so the current builds gradually. Once spinning, it has momentum. Try to stop the flow suddenly and it keeps pushing, hard, creating a pressure spike.

That last point is critical:

Interrupting the current through an inductor produces a voltage spike, often hundreds of volts from a 12 V circuit, as the collapsing magnetic field tries to keep the current flowing. This is called inductive kickback, flyback, or back-EMF.

Kickback is:

Switching off a coil without and with a flyback diode.
Switching off a coil without and with a flyback diode.

Inductance

Measured in henries (H). Practical values run from nH (RF) through µH (power converters) to mH and H (audio crossovers, mains filters). Inductance increases with more turns (it goes as the square of turns), larger coil area, and a magnetic core.

Inductors and AC

The opposite of a capacitor: an inductor passes DC easily and increasingly blocks AC as frequency rises. Its reactance is X_L = 2π × f × L. That makes inductors natural filters for keeping high-frequency noise out of a supply line.


11.2 Types of inductor

Type Description Use
Air core Just a coil of wire RF circuits, where cores would add loss
Ferrite core Ceramic magnetic material Switching power supplies, filters
Iron powder core Pressed iron particles Higher-current filters, less prone to saturation
Laminated iron core Stacked thin steel sheets Low-frequency (mains) chokes, transformers
Toroidal A doughnut-shaped core with wire wound around it Keeps the field contained, low interference, efficient
Drum / bobbin Wire wound on a small spool-shaped core Cheap power inductors
Shielded SMD power inductor Molded or enclosed, usually black blocks Buck and boost converters on modern boards
Ferrite bead A ferrite sleeve on a wire, or a tiny SMD part Blocks high-frequency noise while passing DC; the lump on USB and monitor cables
Common-mode choke Two windings on one core Blocks noise that appears on both wires of a pair (USB, mains filters, Ethernet)
RF chokes and coils Small, often color-coded like resistors Radio circuits
Variable inductor An adjustable core screws in and out Radio tuning

Key specs

Spec Meaning
Inductance The value, with tolerance (often ±20 %)
Saturation current (I_sat) Above this, the core can hold no more magnetism and inductance collapses, often catastrophically in a power supply
RMS / thermal current (I_rms) The current that heats it by a set amount (e.g. 40 °C)
DCR The DC resistance of the winding. Causes I²R losses
SRF (self-resonant frequency) Above this, it stops behaving like an inductor

Reading markings

SMD power inductors often use a 3-digit code in microhenries: 100 = 10 µH, 4R7 = 4.7 µH, 221 = 220 µH. Through-hole axial inductors may use the resistor color code in µH.


11.3 What inductors are used for


11.4 Transformers

How a transformer works

Two coils (the primary and the secondary) share a magnetic core. Changing current in the primary creates a changing magnetic field, which induces a voltage in the secondary. There's no electrical connection between the windings, only magnetic.

The turns ratio sets the voltage ratio.
The turns ratio sets the voltage ratio.

Types of transformer

Type Description Use
Laminated mains transformer Stacked steel core, 50/60 Hz, heavy Older linear power supplies, audio amps
Toroidal transformer Doughnut core, quieter and more efficient Audio amplifiers, medical equipment
High-frequency ferrite transformer Small, runs at tens or hundreds of kHz Inside every switching power supply and phone charger. Higher frequency means a much smaller transformer
Flyback transformer Stores energy and releases it on switch-off Small switching supplies; CRT TVs (tens of kV)
Autotransformer One tapped winding, no isolation Voltage adjustment; variac (variable autotransformer)
Isolation transformer (1:1) Same voltage in and out, isolated Safe servicing of mains equipment
Audio / signal transformer Matches impedance and isolates Microphones, guitar pickups, telephone lines
Current transformer (CT) A core clamped around a wire Measuring AC current non-invasively (energy monitors, clamp meters)
Pulse / gate-drive transformer Couples fast switching signals across isolation Driving power transistors
Center-tapped transformer Secondary with a middle connection Full-wave rectifiers, split (±) supplies
Ignition coil High turns ratio + kickback Car spark plugs (~20,000–40,000 V)
CCFL inverter transformer Steps a few volts up to ~1,000 V AC Backlights in older LCD screens

Reading transformer specs


11.5 Did you know?


11.6 Testing inductors and transformers

A basic multimeter can't measure inductance, but it catches most failures:

Test How Good Bad
Winding continuity Ω across each winding Low resistance: a fraction of an ohm (power inductors) to hundreds of ohms (small transformer primaries) OL = open winding
Winding to winding Ω between primary and secondary Open (OL). Isolation intact Any reading = insulation breakdown (dangerous in mains transformers)
Winding to core / frame Ω Open Short to core
Compare Measure the same winding on a known-good unit Similar value Much lower = shorted turns
Transformer output AC volts on the secondary, powered Near rated (higher with no load) Low or zero
Inductance LCR meter or component tester Near marked value Low = shorted turns or cracked core
Heat / smell / look — Normal warmth Burnt varnish smell, darkened windings, melted tape

⚠️ Shorted turns (a few turns touching through damaged insulation) barely change the DC resistance but make the part overheat. An LCR meter or a "ring tester" finds them.


11.7 How they fail

Failure Cause Symptom
Open winding Overheating, corrosion, broken fine wire No output, circuit dead
Shorted turns Insulation breakdown from heat or age Overheating, low output, blown fuses
Saturation Too much current for the core Sudden current spike, hot switching transistors, supply failure
Cracked ferrite core Mechanical shock Inductance drops, supply misbehaves or whines
Loose core / windings Vibration Buzzing or whining
Thermal fuse opened (many transformers have one inside) Overload Transformer dead. Primary reads open
Destroyed driver transistor Missing flyback diode on a coil Transistor fails short, often with a burn mark

12 — Crystals and oscillators

Every digital device needs a heartbeat, a steady clock signal that paces its operations. Watches, computers, radios, and microcontrollers get that heartbeat from a tiny sliver of quartz that vibrates at an extraordinarily precise frequency.


12.1 How a crystal works

Quartz is piezoelectric: squeeze it and it produces a voltage, and apply a voltage and it flexes. A thin, precisely cut piece of quartz, with metal electrodes on each side, has a natural mechanical resonant frequency, like a tuning fork. Placed in an amplifier circuit that keeps nudging it, it vibrates at exactly that frequency and produces an electrical signal at the same rate.


12.2 Types of timing component

Type What it is Accuracy Notes
Quartz crystal Just the resonator (2 pins, or 4 on some SMD parts where the extras are ground) ±10–50 ppm Needs an oscillator circuit (built into most microcontrollers) and two load capacitors
Ceramic resonator A cheaper piezoelectric ceramic, often with built-in capacitors (3 pins) ±0.1–0.5 % (1,000–5,000 ppm) Fine for many microcontrollers. Not for clocks or USB
Crystal oscillator module (XO) Crystal + oscillator circuit in one can (4 pins: power, ground, output, enable) ±10–100 ppm Outputs a ready-made clock signal
TCXO Temperature-compensated oscillator ±0.5–2 ppm GPS, precision radio
OCXO Oven-controlled: the crystal kept at constant temperature ±0.001–0.1 ppm Lab and telecom references
MEMS oscillator Silicon micro-mechanical resonator ±10–50 ppm Shock-resistant, programmable frequencies
RC / internal oscillator Resistor-capacitor circuit inside a chip ±1–10 % Many microcontrollers have one. Fine for simple tasks, too loose for precise timing or serial communication at high speed
Atomic clock Oscillator locked to an atomic transition (cesium, rubidium) Parts per trillion GPS satellites, national time standards

Common crystal frequencies


12.3 Using a crystal with a microcontroller

The standard hookup: the crystal connects between the chip's two oscillator pins (often labelled XTAL_IN/XTAL_OUT or OSC1/OSC2). Each of those pins also has a small capacitor to ground.

A crystal and its two load capacitors.
A crystal and its two load capacitors.

12.4 Did you know?


12.5 Testing

A multimeter can't confirm a crystal is good. It can only show that it isn't shorted (infinite Ω between pins is expected). Practical checks:


12.6 How they fail

Failure Cause Symptom
Cracked crystal Dropped device, mechanical shock, overheating during soldering Device won't start, or the clock stops
Wrong load capacitors Design error Frequency slightly off (clock drifts), or doesn't start reliably
Won't start Too much stray capacitance, poor layout, wrong drive level, contamination (flux, moisture) Intermittent boot, especially when cold or humid
Drift Aging, temperature RTC gains or loses minutes per month
Serial / USB errors Using an imprecise resonator or internal RC oscillator where a crystal was needed Garbled communication

13 — Diodes

A diode is a one-way valve for electric current. Current flows easily in one direction and is blocked in the other. From that single behavior come rectifiers that turn AC into DC, protection against reversed batteries, voltage references, surge suppressors, and, with the right materials, LEDs, laser diodes, and solar cells.


13.1 Semiconductors in one page

Pure silicon is a poor conductor. Adding tiny amounts of other elements (doping) changes that:

Put P-type and N-type together and you get a PN junction. Where they meet, electrons and holes cancel out, leaving a thin depletion region with no free carriers. That region is an insulating barrier.

Every diode, transistor, LED, and integrated circuit is built from junctions like this.


13.2 How a diode behaves

The diode's current–voltage curve, and how to read its band.
The diode's current–voltage curve, and how to read its band.

Power: a diode dissipates P = Vf × I. At 2 A and 0.8 V that's 1.6 W, enough to get hot.


13.3 Types of diode

Type Vf Key trait Typical parts Use
Rectifier (standard recovery) 0.7–1.1 V Blocks high voltage, slow 1N4001–1N4007 (1 A), 1N5400–5408 (3 A) Mains-frequency rectification, reverse-polarity protection
Fast / ultrafast recovery 0.9–1.7 V Quick turn-off UF4007, FR107, MUR160 Switching power supplies
Small-signal / switching ~0.7 V Tiny, very fast, low current (~200 mA) 1N4148, 1N914, BAV99 Logic, signal clamping, small flyback
Schottky 0.15–0.5 V Metal–semiconductor junction; very fast, low drop; higher leakage, lower voltage ratings 1N5817/18/19 (1 A), 1N5820–22 (3 A), SS14, SS34, SS54, BAT54 Low-voltage power paths, switching regulators, OR-ing
Zener Forward like a normal diode; reverse breakdown at a set voltage Conducts in reverse above its Zener voltage BZX55/BZX79 series, 1N47xx (1 W) Voltage references, simple regulators, clamping
TVS (transient voltage suppressor) — A robust Zener built to absorb big, brief surges SMBJ/SMAJ/P6KE series Surge and ESD protection
Bridge rectifier 2 × Vf Four diodes in one package DB107, KBP, GBU series AC to DC in power supplies
LED 1.2–3.5 V Emits light — Chapter 14
Photodiode — Produces current from light BPW34 Light sensing (chapter 14)
Varactor (varicap) — Capacitance changes with reverse voltage BB-series Electronic radio tuning
Silicon carbide (SiC) / GaN diodes ~1.3+ V Very high voltage, fast, hot-tolerant — EV chargers, industrial power
Germanium ~0.2–0.3 V Low drop, leaky, historic 1N34A Crystal radios, vintage effects pedals

Part-number decoding


13.4 Identifying diodes


13.5 What diodes are used for

Rectification (AC to DC)

A bridge rectifier with a smoothing capacitor, and the resulting output.
A bridge rectifier with a smoothing capacitor, and the resulting output.

Reverse-polarity protection

A diode in series with the supply blocks a backwards battery. It costs its forward drop, so Schottkys are preferred at low voltages. Alternatives are covered in chapter 7.

Flyback (freewheeling) diode

Placed across an inductive load (relay coil, solenoid, motor) with its cathode to the positive side, it does nothing in normal operation. When the driving transistor turns off, the coil's kickback voltage forward-biases the diode, and the current circulates harmlessly until it decays. Mandatory whenever a transistor switches a coil. 1N4007 for slow relays, 1N4148 for small ones, Schottky for fast PWM.

OR-ing (combining supplies)

Two sources, each through its own diode, feed one rail. Whichever is higher powers the load, and neither can backfeed the other. It's used for USB-or-battery power and redundant supplies.

Clamping and protection

Diodes from a signal line to the supply and to ground clamp the signal within the rails. Almost every IC pin has such clamp diodes built in (see §13.7).

Voltage reference (Zener)

A Zener in reverse, fed through a resistor, holds its breakdown voltage across itself: a simple shunt regulator. Choose the resistor so a few mA flows through the Zener even at maximum load. Dedicated reference ICs (e.g. TL431, chapter 28) are more precise.

Dropping voltage

Each series silicon diode drops ~0.7 V, a crude way to lower a supply slightly (e.g. to run a 3.6 V-max device from 4.2 V, or to shave a volt off a fan's supply).

Logic and signal jobs

Diode logic (simple AND/OR gates), steering signals, detecting AM radio (demodulation), and keyboard matrices (a diode per key prevents "ghost" keypresses; chapter 25).

Voltage multipliers

Chains of diodes and capacitors (the Cockcroft–Walton multiplier) build high DC voltages from AC. They're used in bug zappers, photocopiers, CRTs, and particle accelerators.


13.6 Did you know?


13.7 The diodes inside every chip

Most IC pins have protection diodes from the pin to the chip's supply and to ground. They guard against static and small overvoltages, but they also cause two common problems:

Rule: never drive a pin above its supply voltage or below ground unless the datasheet says it's tolerant. Use series resistors or level shifters (chapter 31).


13.8 Testing diodes

Use the meter's diode test mode, with power off.

Probe placement Silicon rectifier Schottky Zener LED
Red on anode, black on cathode (band) 0.5–0.7 V 0.15–0.35 V 0.6–0.7 V 1.5–3 V (may glow faintly)
Reversed OL OL (or a high reading if leaky) OL (the meter's test voltage is below most Zener voltages) OL

13.9 How diodes fail

Failure Cause Symptom
Short Overcurrent, surge, overheating Fuses blow; supply shuts down. In a bridge rectifier, the transformer hums loudly or the fuse blows
Open Extreme overcurrent (the bond wire melts) No output. A half-wave dropout in a bridge gives heavy 50/60 Hz ripple
Leaky Heat, age, reverse overstress Higher reverse current. Circuits drift, batteries drain
Degraded Zener Overheating Regulated voltage drifts
TVS shorted Absorbed a surge beyond its rating The protected line is stuck at ground or the fuse blows. The TVS did its job. Replace it and look for the surge source
Hot diode Undersized for current, or a silicon diode where a Schottky was needed Discoloration, board browning

14 — LEDs and optoelectronics

Optoelectronic components convert between electricity and light. LEDs and laser diodes make light. Photodiodes, phototransistors, and solar cells respond to it. Optocouplers pair the two to pass signals across an electrical gap. This chapter covers them all, starting with the humble indicator LED.


14.1 How an LED works

An LED is a diode (chapter 13) made from compound semiconductors such as gallium arsenide, gallium phosphide, or indium gallium nitride. When current flows forward across the junction, electrons fall into lower-energy "holes" and release the difference as a photon, a particle of light.

The crucial behavior: LEDs are current-driven

Below its forward voltage, an LED is off. Above it, current rises extremely steeply with only a small increase in voltage, and the forward voltage falls as the LED warms. Connected directly to a voltage source, it draws far too much current and burns out. You must limit the current, usually with a series resistor, or with a constant-current driver for high-power LEDs. Brightness follows current.


14.2 Colors and forward voltages

Color Wavelength Typical Vf Material
Infrared 850–940 nm 1.2–1.6 V GaAs, AlGaAs
Red 620–660 nm 1.8–2.2 V AlGaInP, GaAsP
Orange / amber 590–615 nm 2.0–2.2 V AlGaInP
Yellow 580–595 nm 2.0–2.2 V AlGaInP
Yellow-green (older "green") 565–575 nm 2.0–2.4 V GaP
True green 515–530 nm 2.8–3.4 V InGaN
Blue 450–475 nm 2.8–3.4 V InGaN
White broad 2.8–3.4 V Blue LED + yellow phosphor
Violet / UV 365–405 nm 3.0–4.0 V InGaN

Vf also rises with current and varies between batches. The datasheet gives it at a stated current (typically 20 mA).


14.3 Types of LED

Type Description Typical current
3 mm / 5 mm through-hole Classic domed indicator. Clear, diffused, or tinted lens 2–20 mA (20 mA max)
Straw-hat / flat-top Wide viewing angle ~20 mA
SMD indicator (0402–1206) Tiny rectangles on circuit boards 1–20 mA
SMD 3528 / 5050 / 2835 Common on LED strips. 5050s often contain three chips (RGB) 20–60 mA per package
High-power (1 W, 3 W) Mounted on a heat-sinking star board 350–700 mA+. Needs a heatsink and a constant-current driver
COB (chip-on-board) Many LED chips under one phosphor patch High power, floodlights
Filament LED A strip of LEDs imitating an old bulb filament Mains "vintage" bulbs
Bi-color / tri-color Two or three colors in one package Status indicators
RGB (4-lead) Separate red, green, blue in one package: common anode or common cathode Each channel ~20 mA
Flashing / color-cycling A tiny control chip inside. Just add power (and a resistor) Novelty, indicators
Addressable (WS2812 etc.) A controller chip in each LED Chapter 15
Infrared Invisible. Remotes, sensors, night vision 20 mA–1 A pulsed
UV Curing resin, detecting counterfeit banknotes, fluorescence ⚠️ Protect your eyes

Finding the polarity

Identifying LED legs, and the series resistor every LED needs.
Identifying LED legs, and the series resistor every LED needs.

14.4 Driving an LED

The resistor formula

R = (V_supply − Vf) ÷ I

Supply LED Current Calculation Use
5 V Red (2.0 V) 10 mA (5 − 2) ÷ 0.010 = 300 Ω 330 Ω
5 V Blue (3.1 V) 10 mA (5 − 3.1) ÷ 0.010 = 190 Ω 200–220 Ω
3.3 V Red (2.0 V) 5 mA (3.3 − 2) ÷ 0.005 = 260 Ω 270 Ω
12 V White (3.1 V) 20 mA (12 − 3.1) ÷ 0.02 = 445 Ω 470 Ω, ½ W check: 0.02² × 470 = 0.19 W
9 V Three reds in series (6.0 V) 15 mA (9 − 6) ÷ 0.015 = 200 Ω 220 Ω

Guidelines:

Constant-current drivers

High-power LEDs use drivers that regulate current rather than voltage: linear driver ICs, switching LED drivers (buck or boost), or simple transistor current sinks. LED strips usually run on 12 V or 24 V with small resistors built in for each group of LEDs.

From a microcontroller

Two ways to wire an LED to a pin.
Two ways to wire an LED to a pin.

Dimming


14.5 LED displays


14.6 Lasers

A laser diode is an LED with polished, mirrored ends that make light bounce back and forth until it emerges as a narrow, coherent beam.


14.7 Light detectors

Device How it works Speed Sensitivity Use
Photodiode Light frees charge at a reverse-biased junction; current ∝ light Very fast (ns–µs) Low current, needs amplification Light meters, fiber-optic receivers, precision sensing
Phototransistor A photodiode built into a transistor's base, so the current is amplified Moderate (µs) High Object detection, IR receivers, slotted sensors
Photoresistor (LDR) Resistance falls with light Slow (ms) High, imprecise Night lights (chapter 9)
Solar cell A large photodiode run as a generator (~0.5–0.6 V per silicon cell) — — Power generation, light sensing
Digital light sensor ICs Photodiode + ADC + interface — Calibrated in lux Screen brightness control (chapter 26)
Image sensors (CMOS/CCD) Millions of photodiodes in a grid — — Cameras

Reading a phototransistor: connect its collector to the supply through a pull-up resistor (e.g. 10 kΩ), and its emitter to ground. The collector voltage falls as light increases. Read it with an analog input, or a digital input for simple detection.

Infrared remote receivers

The 3-pin modules in TVs (e.g. TSOP382xx, VS1838B) contain a photodiode, amplifier, filter, and demodulator tuned to light flashing at ~38 kHz. They ignore sunlight and room lighting, and output a clean digital signal of the remote's code.

💡 You can see infrared LEDs with a phone camera. Many camera sensors pick up 850–940 nm as a purple-white glow. It's a quick way to check whether a TV remote works. (Some rear cameras filter IR, so try the front camera.)


14.8 Optocouplers (optoisolators)

An LED and a light detector sealed facing each other in one package, with no electrical connection between the two sides. Current through the LED turns on the detector, so a signal crosses a galvanic isolation barrier that can withstand thousands of volts.

An optocoupler passing a signal across an isolation barrier.
An optocoupler passing a signal across an isolation barrier.
Output type Examples Use
Phototransistor PC817, 4N25, 4N35 General isolation of digital signals, feedback in switching supplies
Darlington 4N33, 6N138 Higher gain
Logic-gate output (fast) 6N137, H11L1 High-speed data (MIDI, fast serial)
Photo-TRIAC MOC3021 / MOC3041 (zero-cross) Controlling mains loads through a TRIAC (chapter 18)
Photo-MOSFET (solid-state relay) — Switching AC or DC loads (chapter 18)

Key spec: CTR (current transfer ratio) = output current ÷ LED current, as a percentage. A PC817 with 50–600 % CTR gives 5–60 mA of output capacity per 10 mA through its LED. CTR drops as the LED ages.

Uses: isolating microcontrollers from mains-referenced circuits, breaking ground loops, reading 12/24 V industrial signals, MIDI inputs, and the voltage feedback in most phone chargers.

Photo-interrupters and reflective sensors


14.9 Did you know?


14.10 Testing optoelectronic parts

Part Test Good
LED Diode mode, red on anode 1.5–3 V, often glows faintly; reverse reads OL
LED (bright check) 3 V coin cell, or a supply through a 1 kΩ resistor Lights
IR LED Drive it, and view it through a phone camera Purple glow
7-segment Diode mode from the common pin to each segment (swap probes for common cathode vs anode) Each segment lights faintly
Photodiode Diode mode (normal diode reading), then in µA or mV mode in light Small current or voltage generated in light
Phototransistor Ω collector–emitter (red on collector for NPN) in dark vs light High in dark, dropping with light
Optocoupler Drive the LED side (e.g. 5 V through 330 Ω), and check the output side with Ω or continuity Output conducts only when the LED is driven
IR receiver module Power it (per its pinout), meter on the output, press a remote button Output idles high and flickers or dips when the remote is used

14.11 How they fail

Failure Cause Symptom
Dead LED (open) No resistor, over-current, static, reverse over-voltage No light; OL in diode mode both ways
Dim / discolored LED Over-driving over time, heat Early fading, color shift (whites go blue or yellow)
Flickering high-power LED Poor heatsinking, failing driver Flicker, dimming, cycling
One LED in a series string dead Overheating, a manufacturing defect The whole string goes out
Bright but short-lived Resistor too small Fails within weeks or months
Optocoupler weakens LED aging reduces CTR Output doesn't fully switch; errors after years
Photosensor always "sees" light Ambient IR (sun, halogen lamps), light leaks Shield it, filter it, or use modulated light

15 — Addressable LEDs

An addressable LED ("smart pixel," "NeoPixel") combines an RGB LED with a tiny controller chip. Instead of three wires per LED, hundreds or thousands can be chained on a single data line, each set to its own color. They're behind LED strips, holiday displays, ambient lighting, signs, and countless maker projects.


15.1 How they work

Each pixel has a data in (DIN) and data out (DOUT) pin, plus power and ground. The controller sends a stream of color data down the chain:

  1. The first pixel keeps the first 24 bits (8 each for red, green, blue) and forwards the rest out of its DOUT.
  2. The second pixel keeps the next 24 bits, forwards the rest, and so on down the line.
  3. When the data line stays idle for a short reset / latch time (tens to hundreds of µs), every pixel updates to its new color at once.
A typical addressable LED setup.
A typical addressable LED setup.

Because each pixel regenerates the signal, a long chain is really a series of short hops. Only the wire from the controller to the first pixel is critical. The downside: a failed pixel's DOUT breaks the chain for every pixel after it.


15.2 Common families

Family Wires Voltage Colors Notes
WS2812B Data only (single wire) 5 V RGB The classic "NeoPixel." 800 kHz, chip inside a 5050 LED
WS2811 Data only 12 V (common) or 5 V RGB The controller is a separate chip. Found in bullet/"string" pixels and 12 V strips, often driving 3 LEDs per chip. 400/800 kHz modes
SK6812 Data only 5 V RGB or RGBW (adds a true white LED) WS2812-compatible timing
WS2813 / WS2815 Data + backup data 5 V / 12 V RGB The backup line lets data skip one dead pixel. The WS2815 at 12 V needs less power injection
APA102 / SK9822 ("DotStar") Data + clock (SPI-like) 5 V RGB + 5-bit global brightness Not timing-critical, very fast refresh, high PWM rate (no flicker on camera)
WS2801 / LPD8806 Data + clock 5 V RGB Older clocked types
TM1814 / UCS1903 and others Data varies varies Various clones and alternatives

Form factors: flexible strips (30/60/144 LEDs per meter), bullet or seed strings, rings, matrices (8×8, 16×16), single pixels on breakout boards, and bare 5050 / 2020 packages.


15.3 The single-wire protocol (WS2812-style)

There's no clock line. Each bit is a pulse whose width encodes 0 or 1 (roughly: a short high then a long low = 0, a long high then a short low = 1), about 1.25 µs per bit at 800 kHz. Consequences:

Clocked types (APA102) have a separate clock wire, so timing isn't critical and they can be driven much faster.


15.4 Power

Current per pixel

Each color channel draws up to ~20 mA at full brightness, so a 5 V RGB pixel draws up to ~60 mA at full white. Real parts vary (often 35–50 mA, and some "WS2811" strings far less), so measure a few if it matters.

Power budget: pixels × current per pixel at full white × expected brightness.

Voltage drop and power injection

Thin strip copper and pixel wires have resistance. Every pixel's current flows through the copper before it, so voltage sags along the strip. The far end dims and shifts toward red/orange, because blue and green need more voltage (chapter 14.2). White turning peach is the telltale sign.

Voltage drop along a strip, and the fix: power injection.
Voltage drop along a strip, and the fix: power injection.

Power injection fixes it: run separate, heavier wires from the supply to several points along the strip, connecting both +V and ground.

Supplies, fuses and capacitors


15.5 The data line

Logic levels

A 5 V pixel typically needs its data HIGH above ~0.7 × its supply, i.e. ~3.5 V. A 3.3 V microcontroller's HIGH (3.3 V) is below spec. It often works on the bench, and then fails with longer wires, temperature changes, or a different batch.

Fixes, best first:

  1. A level shifter: a 74AHCT125 or 74HCT245 powered from 5 V accepts 3.3 V inputs as HIGH and outputs a full 5 V (chapter 31). Bidirectional MOSFET-type shifters are often too slow for pixel data.
  2. A "sacrificial pixel": power the first pixel through a diode (~4.3 V). Its threshold drops to ~3.0 V, so 3.3 V works, and it re-drives clean data to the rest at full level.
  3. Run the strip slightly below 5 V, which lowers the threshold. Sometimes enough, but marginal.

Wiring the data line


15.6 Did you know?


15.7 Testing and diagnosis

Symptom Likely cause Check
Nothing lights No power, no common ground, wrong data pin, connected to the DOUT end, wrong pixel type in code Voltage at the strip; arrow direction; ground continuity
First pixel random or flickering, rest fine Marginal data signal Level shifter, series resistor, shorter data wire
Random flicker or garbage along the strip Marginal data level, no ground wire with the data, electrical noise As above; add a ground alongside the data
Red and green swapped Color order Change GRB/RGB in code
Works up to pixel N, then dark or garbage Pixel N's DOUT or pixel N+1's DIN failed, or a broken joint or trace between them Bridge DIN→DOUT around the suspect pixel, or cut it out
Far end dim, or white looks pink/orange Voltage drop Measure 5 V at the end under full white. Add injection or thicker wire
Resets or glitches during bright scenes Power supply sagging, no bulk capacitor Measure the supply under load; add a capacitor; add supply capacity
Controller resets when strip lights up Strip and controller share an overloaded supply Separate or larger supply, bulk capacitor
Hot spots on the strip Current crowding near the injection point, or a short Thermal check; look for damage
One color missing on one pixel Failed LED die inside that pixel Replace the pixel

Meter checks:


15.8 How they fail

Failure Cause Symptom
First pixel killed Data applied while the strip is unpowered or its ground is disconnected (current flows through the data pin), hot-plugging, no series resistor on the data line First pixel dark or wrong color; the rest show garbage or nothing
One pixel's data output dead Static, a voltage spike at power-up, overheating Every pixel after it is dark or random
Single LED die failed Heat, manufacturing defect One color missing on one pixel
Many pixels dead at once Wrong supply (12 V on a 5 V strip), reversed power A whole section dead, often with burn marks
Cracked joint or trace Bending the strip at a pad or across a pixel, vibration, pulling on soldered wires A section goes dark or flickers when the strip is touched or flexed
Burned copper or melted connector Too much current through thin strip copper or a small connector, with no power injection Discolored strip near the input, melted plug, far end dim
Heat damage Strips run bright with no aluminum channel or airflow Colors shift, pixels fail early, adhesive lets go
Water damage Non-waterproof strip outdoors, or a split silicone sleeve Green corrosion on pads; pixels fail one by one

A strip that fails "from pixel N onward" almost always has a single bad pixel or joint at N. Cutting that pixel out and bridging the gap usually brings the rest back.

16 — Bipolar transistors (BJTs)

The transistor is the most important invention in electronics. It lets a small signal control a larger current: as a switch (on or off) or as an amplifier (a proportional copy). The bipolar junction transistor (BJT) was the first practical type and is still used everywhere for small switching and amplifying jobs.


16.1 Structure

A BJT is a sandwich of three semiconductor layers, forming two PN junctions:

The three terminals:

Terminal Role
Base (B) The control input. A small current here controls the transistor
Collector (C) Where the main current enters (NPN)
Emitter (E) Where the main current leaves (NPN). The schematic arrow is on the emitter and points in the direction of conventional current: out for NPN, in for PNP
The three layers of an NPN transistor, and its symbol.
The three layers of an NPN transistor, and its symbol.

16.2 How it works

For an NPN transistor: when a small current flows into the base and out of the emitter (which requires the base to be ~0.6–0.7 V above the emitter), the transistor allows a much larger current to flow from collector to emitter.

Water analogy: a large valve in the main pipe (collector → emitter) whose handle is pushed open by a small side stream (the base current). More side flow opens the valve further.

The ratio is the current gain, called hFE or β (beta):

I_C ≈ hFE × I_B

With hFE = 100, a 1 mA base current allows up to 100 mA of collector current. hFE varies enormously between parts, even of the same type (often 100–400), and changes with temperature and current. Good circuits don't depend on its exact value.

Three operating regions

Region Condition Behavior Used for
Cutoff No base current (V_BE below ~0.5 V) Off. Almost no collector current Switch OFF
Active Moderate base current I_C proportional to I_B. Acts as an amplifier Amplifiers
Saturation More base current than needed Fully on. Only a small V_CE(sat) of ~0.1–0.3 V remains Switch ON

16.3 The BJT as a switch

The most common hobby use: letting a microcontroller pin (which can supply only a few mA) turn on a relay, buzzer, motor, lamp, or group of LEDs.

Low-side NPN switch

An NPN transistor switching a 12 V load from a logic pin.
An NPN transistor switching a 12 V load from a logic pin.

Sizing the base resistor

To guarantee saturation, supply about one tenth of the load current as base current (a "forced beta" of 10), regardless of the transistor's actual hFE:

I_B = I_load ÷ 10 and R_B = (V_control − 0.7) ÷ I_B

Load Control I_B R_B Standard
50 mA buzzer 5 V pin 5 mA (5 − 0.7) ÷ 0.005 = 860 Ω 820 Ω–1 kΩ
70 mA relay coil 3.3 V pin 7 mA (3.3 − 0.7) ÷ 0.007 = 370 Ω 330–390 Ω
20 mA LED group 3.3 V pin 2 mA 1.3 kΩ 1.2 kΩ

If the required base current is more than the pin can supply (see the chip's limits), use a Darlington, a MOSFET (chapter 17), or a driver IC.

A pull-down resistor (e.g. 10–100 kΩ) from base to emitter keeps the transistor firmly off when the control pin is floating (during boot, for example).

High-side PNP switch

A PNP sits between the positive supply and the load, and turns on when its base is pulled low (about 0.7 V below its emitter). A PNP whose emitter is at a higher voltage than the controlling microcontroller can't be turned fully off by the pin. Add a small NPN to pull its base down, or use a P-channel MOSFET with a driver.

Heat

A saturated switch dissipates P = V_CE(sat) × I_C: small (e.g. 0.2 V × 0.5 A = 0.1 W). A transistor that isn't saturated has volts across it and heats rapidly. A hot switching transistor usually needs more base current.


16.4 The BJT as an amplifier (the basics)

In the active region, small changes in base current produce proportionally larger changes in collector current. With a collector resistor, that becomes a larger voltage swing: an amplified copy of the input.

The classic common-emitter amplifier uses:

Other configurations:

Today most amplification is done with op-amp ICs (chapter 28), but they're built from exactly these transistor stages.


16.5 Special configurations

Configuration What it is Why
Darlington pair Two transistors, the first driving the second's base. Gains multiply (hFE of 1,000–30,000) Switch large currents with tiny base current. Downside: ~1–1.5 V drop when on, so more heat
Darlington arrays Seven or eight Darlingtons with flyback diodes in one chip: ULN2003, ULN2803 Driving relays, small stepper motors, LED arrays from logic pins
Sziklai pair NPN+PNP complementary Darlington Lower on-drop than a Darlington
Push-pull (complementary) pair An NPN and a PNP sharing an output Audio amplifier output stages, gate drivers
Current mirror Two matched transistors copying a current Inside ICs, constant-current LED drivers
Differential pair Two transistors comparing two inputs The input stage of every op-amp
Phototransistor Light acts as base current Chapter 14

16.6 Packages and common parts

Package Look Power
TO-92 Small black half-cylinder, 3 legs ~0.5–0.6 W
SOT-23 Tiny 3-pin SMD ~0.2–0.35 W
SOT-223 / SOT-89 SMD with a tab ~1 W
TO-126 Flat, with a mounting hole ~1–12 W with heatsink
TO-220 Flat with a metal tab and hole (the tab is usually the collector) ~50–100 W with a heatsink
TO-247 / TO-3P Larger power package 100 W+
TO-3 Metal "diamond" can (the case is the collector) Classic high-power
Part Type Max I_C Max V_CE Notes
2N3904 / 2N3906 NPN / PNP 200 mA 40 V The small-signal classics
2N2222A / 2N2907A NPN / PNP 600–800 mA 40 V General-purpose switching
BC547 / BC557 (BC548, BC549…) NPN / PNP 100 mA 45 V European small-signal. Note: pinout C-B-E
S8050 / S8550 NPN / PNP 500 mA–1.5 A (datasheets vary) 25 V Common in Asian-made kits and modules
2SC1815 / 2SA1015 NPN / PNP 150 mA 50 V Japanese small-signal (marked C1815 / A1015)
BD139 / BD140 NPN / PNP 1.5 A 80 V Medium power, TO-126
TIP31 / TIP32 NPN / PNP 3 A 40–100 V TO-220 power
TIP120 / TIP125 NPN / PNP Darlington 5 A 60 V Easy high-current switching. High on-drop
2N3055 / MJ2955 NPN / PNP 15 A 60 V Classic TO-3 power transistor
MMBT3904 / MMBT2222 NPN as through-hole versions SOT-23 SMD equivalents

⚠️ TO-92 pinouts are not standardized. With the flat face toward you and the legs down, the 2N3904 is E-B-C, the BC547 is C-B-E, and the 2SC1815 is E-C-B. Even one part number can vary: onsemi's PN2222A is E-B-C, but its P2N2222A is C-B-E. Check the datasheet for the exact part, or use a component tester or the diode-test method below. More pinouts are in Appendix D.

Three common TO-92 pinouts.
Three common TO-92 pinouts.

16.7 Did you know?


16.8 Testing a BJT

A BJT looks like two diodes sharing the base: base–emitter and base–collector.

Diode-test mode, NPN:

Red probe Black probe Expected
Base Emitter 0.6–0.7 V
Base Collector 0.6–0.7 V (usually slightly lower than B–E)
Emitter or collector Base OL
Collector Emitter (both ways) OL

PNP: the same with black on the base (the diodes point the other way).

Identifying unknown pins: find the pin that conducts to both others with the same probe on it. That's the base. If that probe is red, it's NPN; if black, PNP. The junction with the slightly higher reading is usually base–emitter.

Many meters have an hFE socket that measures gain directly. It's a rough value, but it confirms the type and pin order.


16.9 How BJTs fail

Failure Cause Symptom
Collector–emitter short Over-current, over-voltage (often from a missing flyback diode), overheating Load stuck ON; transistor may be hot. Reads near 0 between C and E
Open junction Extreme over-current Load never turns on
Leaky Heat stress Load partly on when it should be off; drifting amplifier bias
Overheating while "on" Not saturated: base current too low Hot transistor, voltage drop across C–E, dim or weak load
Thermal runaway Rising temperature raises current, which raises temperature Transistor destroys itself. Emitter resistors and heatsinks prevent it
Wrong pinout fitted Assumed pin order Circuit doesn't work, or works strangely

17 — MOSFETs and other FETs

The field-effect transistor (FET) controls current with voltage instead of current. Its best-known form, the MOSFET, is the most manufactured device in human history. Every microchip contains billions of them, and individual power MOSFETs switch everything from LED strips to electric cars.


17.1 How a MOSFET works

A MOSFET has three terminals:

Terminal Role BJT equivalent
Gate (G) The control input Base
Drain (D) Main current terminal Collector
Source (S) Main current terminal (the reference for the gate voltage) Emitter

The gate is a metal (or polysilicon) electrode separated from the silicon underneath by an extremely thin layer of insulating oxide. Putting a voltage on the gate creates an electric field that pulls charge carriers into the region beneath it, forming a conductive channel between drain and source. No voltage, no channel.

Cross-section of an N-channel MOSFET.
Cross-section of an N-channel MOSFET.

Key consequences:


17.2 Types

Enhancement vs depletion

N-channel vs P-channel

N-channel P-channel
Turns on when Gate is above source (positive Vgs) Gate is below source (negative Vgs)
Typical position Low side: between the load and ground (source to ground) High side: between the supply and the load (source to supply)
Performance Lower Rds(on), cheaper, more choice ~2–3× higher Rds(on) for the same size and price
Schematic arrow Points in toward the channel Points out

N-channel low-side switching is the easiest and most common.

Other members of the FET family

Device Description Use
JFET (junction FET) Gate is a reverse-biased PN junction. Normally on, pinched off by negative gate voltage (N-channel) Low-noise audio preamps, guitar pedals, high-impedance inputs (e.g. J201, 2N5457)
IGBT A MOSFET-driven bipolar output stage High voltage and high current: motor drives, induction cookers, EV inverters, welders
GaN FET Gallium nitride transistor Very fast, efficient. Compact USB-C chargers
SiC MOSFET Silicon carbide High voltage and temperature: EV and solar inverters
Dual MOSFETs Two in one package (N+N, P+P, or N+P) H-bridges, battery protection circuits
Load-switch ICs / smart high-side switches MOSFET + driver + protection Switching power to subsystems

17.3 Reading a MOSFET datasheet

Spec Meaning What to watch
V_DS (max) Maximum drain–source voltage Choose ≥ 1.5–2× your supply (inductive spikes add more)
I_D (max) Maximum continuous drain current Often quoted with an ideal heatsink at 25 °C. Real-world limit is heat, far below this
R_DS(on) On-resistance Specified at a given Vgs. Check it at your gate voltage
V_GS(th) Gate threshold voltage Where it just begins to conduct (e.g. 250 µA). Not fully on
V_GS (max) Maximum gate–source voltage Often ±20 V, but sometimes ±8–12 V. Exceeding it punctures the gate oxide
Q_g (gate charge) Charge needed to switch it Higher charge = slower switching or more drive current needed
Body diode ratings The built-in reverse diode Matters in H-bridges and inductive loads
Thermal resistance (R_θJA, R_θJC) °C of temperature rise per watt Used to calculate heatsinking
SOA (safe operating area) Allowed voltage/current/time combinations Matters for linear (non-switching) use

Logic-level MOSFETs: the big trap

The threshold voltage is not the turn-on voltage. A MOSFET with Vgs(th) = 2–4 V may need 10 V on the gate to reach its rated Rds(on). Driven from a 3.3 V or 5 V microcontroller, it's only partly on: high resistance, heat, and possible failure.

For direct microcontroller drive, choose a "logic-level" MOSFET whose datasheet specifies Rds(on) at Vgs = 4.5 V (for 5 V logic) or 2.5 V (for 3.3 V logic).

Part Type V_DS Logic-level? Notes
2N7000 / BS170 N 60 V Marginal (~200 mA) TO-92. Small signals and level shifting
BSS138 N 50 V Yes, small SOT-23. Bidirectional level shifters
AO3400 N 30 V Yes (2.5 V) SOT-23, ~5 A. Excellent small switch
AO3401 P −30 V Yes SOT-23 P-channel companion
IRLZ44N N 55 V Yes (the "L") TO-220. Popular hobby power switch
IRLB8721 N 30 V Yes TO-220, very low Rds(on) at 4.5 V
IRF540N / IRFZ44N N 100 / 55 V No: needs ~10 V Commonly misused with microcontrollers
IRF9540N P −100 V No TO-220 P-channel
Si2302 / Si2301 N / P 20 V Yes SOT-23

💡 The "L" in IRL-series part numbers means "logic level." IRLZ44N works from a 5 V pin, and its near-twin IRFZ44N doesn't.


17.4 Driving a MOSFET

Low-side N-channel and high-side P-channel switches.
Low-side N-channel and high-side P-channel switches.

N-channel low-side switch (the standard circuit)

Gate drivers

Driving a MOSFET fast (PWM at tens of kHz or more) means charging its gate capacitance quickly, which needs amps of peak current. A microcontroller pin can't provide that, so the MOSFET switches slowly, spends time half-on, and heats up. Gate driver ICs (e.g. TC4420, UCC27517, or half-bridge drivers like the IR2110) supply the current and can also shift the gate voltage up to 10–12 V. For slow switching (on/off, low-frequency PWM), a direct connection to a logic-level part is fine.

P-channel high-side switch

This circuit is used to switch power to a whole subsystem (sensors, radio modules) in battery devices.

Reverse-polarity protection with a MOSFET

A P-channel MOSFET in the positive lead (or an N-channel in the ground lead), wired so its body diode conducts in the correct direction, turns fully on when the battery is connected correctly and stays off when reversed. It's far more efficient than a series diode.

Bidirectional level shifting

A single N-channel MOSFET (typically BSS138) with pull-up resistors on both sides translates open-drain signals like I²C between 3.3 V and 5 V in both directions (chapter 31).


17.5 The body diode

Power MOSFETs contain a built-in body diode from source to drain (for N-channel). It conducts whenever the drain goes below the source, whether the gate is on or not.


17.6 Heat and heatsinking

Conduction loss is P = I² × Rds(on). Switching loss adds to it at high PWM frequencies. Estimating temperature:

Temperature rise = P × thermal resistance

Example: a TO-220 MOSFET with R_θJA ≈ 62 °C/W (no heatsink) dissipating 1 W rises ~62 °C above ambient. That's already hot. With a heatsink, total thermal resistance might fall to ~10 °C/W. Keep junction temperatures well under the 150–175 °C maximum, ideally below ~100 °C.

Rules of thumb for through-hole packages without a heatsink: TO-92 ≤ ~0.5 W, TO-220 ≤ ~1–1.5 W. In SMD packages, the PCB copper is the heatsink.


17.7 Did you know?


17.8 Testing a MOSFET

N-channel enhancement, diode-test mode (power off):

  1. Discharge the gate first: briefly short gate to source (touch them together, or with the probe tips).
  2. Red on source, black on drain: the body diode reads ~0.4–0.7 V.
  3. Red on drain, black on source: OL (off).
  4. Turn it on: touch red to the gate and black to the source for a moment. The meter's test voltage charges the gate.
  5. Now red on drain, black on source: it reads low (near 0 or a small value). The channel is on. (Low-threshold parts turn on fully. Higher-threshold ones may only partly turn on with a meter's ~3 V test voltage.)
  6. Short gate to source again: drain–source goes back to OL.

For P-channel, reverse the probe polarities.

Bad signs:

A component tester identifies MOSFETs, their type, pinout, and threshold, which is useful for unmarked parts.


17.9 How MOSFETs fail

Failure Cause Symptom
Drain–source short Over-voltage spike (missing flyback diode), overheating, over-current Load stuck ON, often with a blown fuse
Gate punctured Static discharge, exceeding Vgs(max), gate-voltage spikes Gate leaks to drain/source; erratic behavior
Overheating Not logic-level (partly on), too slow switching, too little heatsinking Hot part, reduced output, eventual failure
Random turn-on at startup Floating gate (no pull-down) Load flashes or twitches at power-up
Oscillation / ringing No gate resistor, long gate wiring Heat, EMI, whining
Avalanche failure Inductive energy above its rating Sudden short

When a MOSFET fails shorted, check the driver and gate resistor too. A failing MOSFET often takes the gate driver or the microcontroller pin with it.

18 — Thyristors, TRIACs and solid-state relays

Thyristors are latching semiconductor switches. Once triggered, they stay on by themselves until the current through them drops to nearly zero. That makes them natural switches for AC mains power, where the current passes through zero many times per second. They're the heart of light dimmers, motor speed controls, and solid-state relays.

⚠️ Most of these parts are used at mains voltage. Read chapter 33 before building mains circuits, and prefer ready-made, certified modules when in doubt.


18.1 The SCR (silicon-controlled rectifier)

How it works

A four-layer (PNPN) device with three terminals: anode, cathode, and gate.

Uses

Common parts: C106, 2N6504, TYN612, BT151.


18.2 The TRIAC

A TRIAC is effectively two SCRs back to back sharing one gate. It conducts in both directions once triggered, making it a switch for AC.

Phase-angle control: the TRIAC passes only part of each half-cycle.
Phase-angle control: the TRIAC passes only part of each half-cycle.

Common parts: BT136 (4 A), BT137, BT138 (12 A), BTA16 (16 A, insulated tab), Q4008.

💡 BTA vs BTB: in ST's naming, BTA parts have an insulated mounting tab. BTB tabs are connected to MT2, which is at mains voltage.


18.3 The DIAC

A DIAC is a two-terminal trigger device. It blocks until the voltage across it (in either direction) reaches its breakover voltage (~30 V), then suddenly conducts. Paired with an RC network, it produces sharp trigger pulses for a TRIAC. That's the classic simple light dimmer: a potentiometer + capacitor sets the delay, and the DIAC fires the TRIAC.


18.4 Optotriacs

An optotriac (e.g. MOC3021, MOC3041) is an optocoupler whose output is a small TRIAC. A microcontroller lights the internal LED (~10–15 mA), which triggers a power TRIAC safely isolated from mains.


18.5 Solid-state relays (SSRs)

An SSR does the job of an electromechanical relay (chapter 6) with no moving parts. A low-voltage input drives an internal LED, which controls output semiconductors across an isolation barrier.

What's inside an AC solid-state relay.
What's inside an AC solid-state relay.
Type Output device Switches Notes
AC SSR (zero-cross) TRIAC or back-to-back SCRs AC only Turns on near zero crossing; low noise. The most common, e.g. "SSR-25DA" (DC control, AC load)
AC SSR (random turn-on) TRIAC/SCR AC only For phase control
DC SSR MOSFET or transistor DC only e.g. "SSR-25DD." An AC SSR won't turn off a DC load: with no zero crossing, it stays latched
AC/DC (MOSFET) SSR / PhotoMOS Back-to-back MOSFETs Both Low-current signal switching, very low leakage

SSR pros and cons

Advantages Disadvantages
Silent, no contact wear, very long life Voltage drop (~1–1.6 V) makes heat. Needs a heatsink above a few amps
Fast, no bounce Leakage current when off (mA). Can keep small loads such as LED bulbs glowing faintly
Resistant to vibration Usually fails shorted (ON), a safety concern
Low control current Sensitive to voltage spikes (use MOVs/snubbers)
Zero-cross types reduce electrical noise Many cheap SSRs are counterfeits or overrated. Derate generously

⚠️ Heatsink rule: an SSR carrying 10 A with a 1.5 V drop dissipates 15 W. That's far too much without a proper heatsink. Budget-module "25 A" ratings assume a large heatsink and good airflow.


18.6 Did you know?


18.7 Testing

⚠️ Unplug mains circuits and discharge capacitors before testing.

Part Test Good
SCR Diode mode, gate (red) to cathode (black) A diode-like reading (~0.5–0.8 V). Reverse typically OL or a lower-resistance reading (some have an internal gate resistor)
SCR / TRIAC Anode/MT2 to cathode/MT1, both directions OL (not shorted)
SCR latching test Meter in diode or Ω mode, red on anode, black on cathode; briefly touch gate to anode Reading drops and stays low (latched) for sensitive-gate types. Larger SCRs may need more current than a meter supplies
TRIAC Ω between MT1 and gate Low-ish (tens to hundreds of Ω), both ways
SSR Power the input (e.g. 5 V through its rated input) and check the output Input LED lights. With a real load (e.g. a lamp in series on AC), the load switches. Meters alone can't test AC SSRs, which need load current and AC
Optotriac Diode test on the LED pins ~1.1–1.3 V forward

18.8 How they fail

Failure Cause Symptom
Shorted TRIAC/SCR Over-current, voltage spike, overheating Load permanently ON (a dimmer stuck at full brightness)
Won't trigger Gate damaged, driver failed Load never turns on
False triggering Missing snubber, fast transients, inductive loads Load turns on randomly or won't turn off
Half-wave operation One direction of a TRIAC damaged Motor runs rough, lamp dim and flickering
SSR stuck on Common failure mode Load can't be turned off. Why critical loads need a mechanical cutoff too
SSR overheating Inadequate heatsink Thermal failure, often shorted
Load glows when "off" SSR leakage current Add a bleeder resistor across the load, or use a mechanical relay

19 — Batteries

A battery converts stored chemical energy into electricity. Choosing one means balancing voltage, capacity, current capability, size, weight, cost, rechargeability, and safety. Lithium cells in particular demand respect: they pack enough energy to start a fire if abused.


19.1 How a battery works

A cell has two electrodes of different materials (the anode and cathode) in an electrolyte, with a separator between them. The chemistry "wants" to move electrons from one electrode to the other but can only do so through the external circuit. That push is the cell's voltage, set by the chemistry. In a rechargeable cell, charging forces the reaction backwards.

A battery, strictly speaking, is several cells connected together, although the word is used for single cells too.

Internal resistance

A real cell behaves like an ideal voltage source with a resistor inside it. Drawing current drops some voltage internally:

V_terminal = V_open-circuit − I × R_internal

This voltage sag is why a weak battery reads fine on a meter (no load) but collapses when something draws current. Internal resistance rises as a cell ages, gets cold, or runs low.


19.2 Capacity, energy and current

Term Meaning
Capacity (mAh, Ah) How much charge it delivers. 2,000 mAh = 2 A for 1 hour, or 200 mA for 10 hours (ideally)
Energy (Wh) Capacity × voltage. Use this to compare batteries of different voltages
C-rate Current as a multiple of capacity. For a 2,000 mAh cell, 1C = 2 A, 0.5C = 1 A, 2C = 4 A
Max continuous discharge The highest current it's designed to supply without damage or overheating
Nominal voltage The "average" voltage during discharge
Cutoff (end) voltage The voltage at which it's considered empty
Self-discharge How fast it loses charge sitting idle
Cycle life Number of charge/discharge cycles before capacity falls to ~80 %
Energy density Wh per kg (or per liter)

Capacity isn't fixed. It shrinks at high discharge currents, in the cold, and with age. Rated capacity is usually measured at a gentle rate (e.g. 0.2C).

Runtime estimate: hours ≈ capacity (Ah) ÷ average current (A), or Wh ÷ W. Derate by 20–30 % for real-world conditions.


19.3 Chemistries

Primary (non-rechargeable)

Chemistry Nominal V Traits Common forms
Zinc–carbon ("heavy duty") 1.5 V Cheapest, low capacity, leaks readily AA, AAA, C, D, 9 V
Alkaline 1.5 V Good capacity, poor at high current, can leak corrosive potassium hydroxide when old or dead AA, AAA, C, D, 9 V, LR44
Lithium iron disulfide (Li-FeS₂) 1.5 V Light, excellent in cold and at high current, long shelf life, doesn't leak AA, AAA ("lithium AA")
Lithium manganese dioxide (Li-MnO₂) 3 V Coin cells (CR series), camera batteries (CR123A, CR2) CR2032, CR2025, CR123A
Lithium thionyl chloride (Li-SOCl₂) 3.6 V Very high energy, 10–20 year life, very low self-discharge, poor at high current Utility meters, alarm sensors, trackers
Silver oxide 1.55 V Flat voltage curve Watches (SR series)
Zinc–air 1.4 V Very high energy. Activated by removing the tab, then lasts weeks Hearing aids

Secondary (rechargeable)

Chemistry Nominal V per cell Full / empty Traits Uses
Lead-acid (flooded, AGM, gel/SLA) 2.0 V 2.1–2.4 / ~1.75–1.9 V Heavy, cheap, robust, high surge current. Must be stored charged, or it sulfates Cars (6 cells = 12 V), UPS, alarm panels
NiCd 1.2 V 1.4 / 1.0 V Robust, high current. "Memory effect." Cadmium is toxic Older power tools
NiMH 1.2 V 1.4–1.45 / 1.0 V Safe, AA/AAA replacement. Low-self-discharge types (e.g. Eneloop) hold charge for a year Household rechargeables
Li-ion (NMC, NCA, LCO) 3.6–3.7 V 4.20 / 2.5–3.0 V High energy density, no memory. Needs protection and precise charging Phones, laptops, power tools, EVs, 18650 cells
LiPo (lithium polymer) 3.7 V 4.20 / 3.0 V Li-ion in a flexible pouch; thin, light, high current. Swells when abused Drones, RC, wearables, phones
LiFePO₄ (LFP) 3.2 V 3.60–3.65 / 2.5 V Very safe, 2,000–6,000 cycles, flat voltage. Lower energy density Solar storage, RVs, 12 V lead-acid replacements (4 cells = 12.8 V)
LTO (lithium titanate) 2.4 V 2.8 / 1.5 V Extreme cycle life, fast charging, cold-tolerant, low energy Specialist, buses
Li-ion "1.5 V" AA 1.5 V (regulated) Constant 1.5 V until empty Li-ion cell + tiny buck converter inside Drop-in AA replacement

Supercapacitors vs batteries

Supercaps (chapter 10) store far less energy but charge in seconds and last millions of cycles. They complement batteries for burst power and backup.


19.4 Sizes and naming

Cylindrical cells

Name Size (mm) Typical chemistries
AAA 10.5 × 44.5 Alkaline, NiMH, lithium
AA 14.5 × 50.5 Alkaline, NiMH, lithium
C / D 26 × 50 / 34 × 61 Alkaline, NiMH
10440 / 14500 AAA / AA size Li-ion at 3.7 V. ⚠️ Fits AA holders but is 2.5× the voltage
16340 / CR123A 16 × 34 Li-ion (16340) / lithium primary (CR123A)
18650 18 × 65 Li-ion. The standard for laptops, flashlights, EVs, DIY packs
21700 21 × 70 Li-ion. Higher capacity (Tesla Model 3, power tools)
26650 / 32650 larger Li-ion, LiFePO₄

Cylindrical Li-ion names encode size: 18650 = 18 mm diameter × 65.0 mm long.

Coin and button cells

The 9 V battery

A rectangular battery containing six small 1.5 V cells in series (some alkaline brands use six AAAA-size cells inside). About 500 mAh alkaline. Great for smoke alarms, poor for motors.


19.5 Discharge curves

How cell voltage falls as capacity is used.
How cell voltage falls as capacity is used.

Li-ion resting voltage vs charge (approximate)

Voltage (at rest) State of charge
4.20 V 100 %
4.0 V ~80 %
3.85 V ~60 %
3.75 V ~40 % (good storage voltage)
3.6 V ~20 %
3.4 V ~5 %
3.0 V empty

Measure at rest (after the load has been off for a while). Voltage under load reads lower, and it bounces back afterwards. Low-battery detection needs hysteresis so it doesn't flip on and off.


19.6 Series and parallel packs

Notation Meaning Example
xS x cells in series: voltages add 3S Li-ion = 11.1 V nominal, 12.6 V full
yP y cells in parallel: capacity and current capability add 2P doubles mAh
xSyP Both 4S2P = 8 cells, 14.8 V, double capacity
Series adds voltage; parallel adds capacity.
Series adds voltage; parallel adds capacity.

Rules:


19.7 Charging

Chemistry Method Termination
Li-ion / LiPo CC/CV: constant current (typically 0.5–1C) until 4.20 V, then constant voltage while the current tapers When current falls to ~C/10–C/20. Never float-charge; never exceed 4.20 V per cell (4.35 V for "HV" cells)
LiFePO₄ CC/CV to 3.60–3.65 V per cell Current taper
NiMH Constant current Detect a small voltage drop (−ΔV), a temperature rise, or a timer. Slow trickle charging is tolerated at low rates
Lead-acid CC → absorption (constant voltage ~14.4–14.7 V for 12 V) → float (~13.5–13.8 V) Float can be held indefinitely
Primary cells Never charge Risk of leakage or explosion
The CC/CV charge profile for lithium-ion cells.
The CC/CV charge profile for lithium-ion cells.

Common Li-ion charger ICs and modules: TP4056 (single cell, 1 A, linear), MCP73831 (small, 500 mA), BQ-series (TI) chargers with power-path and fuel gauging, and multi-cell balance chargers for RC packs.


19.8 Protection and the BMS

A Li-ion protection circuit (built into "protected" cells, pack BMS boards, and many charger modules) disconnects the cell on:

A classic small protection circuit is a DW01 controller plus a dual MOSFET (FS8205). Multi-cell BMS boards add balancing. Protection is a safety net, not a charger: it should rarely have to act.


19.9 Safety


19.10 Did you know?


19.11 Testing batteries

Test How What it tells you
Open-circuit voltage DC volts across the terminals, no load, after resting State of charge (compare with the tables above); deeply discharged cells
Loaded voltage Voltage while the device (or a test resistor) draws current Sag reveals high internal resistance: an old or weak battery
Internal resistance (V_no-load − V_loaded) ÷ load current, or a dedicated IR tester Health. Rising IR = aging. Compare with a new cell
Capacity test Discharge at a known current to the cutoff voltage and time it, or use a hobby charger/analyzer True remaining capacity
Self-discharge Charge fully, rest a week, re-measure Cells that drop noticeably are defective
Visual Swelling, leaks, corrosion, dents, damaged wraps Retire damaged cells
Temperature Feel or measure during charge/discharge A cell much warmer than its neighbors is faulty

⚠️ Never measure a battery with the meter in current (amps) mode. That's a direct short through the meter.


19.12 How batteries fail

Failure Cause Symptom
Capacity fade Normal aging, heat, high charge voltage, deep cycles Shorter runtime
High internal resistance Age, cold, sulfation (lead-acid) Device shuts off under load while voltage looks OK at rest
Swelling (LiPo/Li-ion) Over-charge, over-discharge, heat, age Puffy pack. Retire immediately
Won't charge / charger rejects it Over-discharged below protection cutoff; protection circuit tripped 0 V at terminals (the protection circuit has disconnected the cell)
Leakage Alkaline cells left in devices, especially when dead White or blue crust, corroded contacts (clean with vinegar or lemon juice for alkaline, then dry)
Sulfation (lead-acid) Left discharged Low capacity, high resistance
Imbalanced pack No balancing, mismatched cells Pack cuts off early. One group reads much lower than others
Memory effect (NiCd) Repeated partial discharges Apparent capacity loss. A full discharge/charge cycle may restore some

20 — Voltage regulators

Electronic circuits need a steady, specific voltage (3.3 V, 5 V, 12 V), no matter how the supply varies or how much current the load draws. A voltage regulator provides it. There are two fundamentally different approaches: linear regulators burn off excess voltage as heat, and switching regulators convert it efficiently using an inductor or capacitors.


20.1 Linear regulators

How they work

A linear regulator is a transistor acting as an automatically adjusted resistor between input and output. An internal circuit compares the output with a precise reference voltage and continuously adjusts the transistor to hold the output exactly on target.

The same job done by a linear and a switching regulator.
The same job done by a linear and a switching regulator.

Key specs

Spec Meaning
Output voltage Fixed (3.3, 5, 12 V…) or adjustable
Max output current e.g. 100 mA, 1 A, 1.5 A. Often limited by heat long before this
Dropout voltage Minimum V_in − V_out needed to regulate. Classic regulators: ~2 V. LDOs (low-dropout): 0.1–0.5 V
Quiescent current (I_q) Current the regulator itself uses. Matters hugely for battery devices (from ~1 µA to several mA)
Max input voltage Absolute limit
PSRR / ripple rejection How well it blocks input noise
Thermal resistance Heat rise per watt; sets how much power the package can shed
Stability capacitors Many LDOs need a specific output capacitor type or ESR range to avoid oscillating. Follow the datasheet

Common parts

Part Type Output Dropout Notes
78xx (7805, 7812…) Fixed positive 1–1.5 A ~2 V The classic TO-220 regulator. 7805 = 5 V, 7812 = 12 V
79xx Fixed negative 1 A ~2 V Pinout differs from the 78xx
78Lxx Small 78xx 100 mA ~1.7 V TO-92
LM317 Adjustable positive 1.5 A ~2 V V_out = 1.25 × (1 + R2 ÷ R1). Typical R1 = 240 Ω
LM337 Adjustable negative 1.5 A ~2 V
AMS1117 / LM1117 LDO, fixed or adjustable 800 mA–1 A ~1.1 V On countless dev boards (AMS1117-3.3)
LM2940 LDO 1 A ~0.5 V Automotive-tolerant
MCP1700 / HT7333 / XC6206 Ultra-low-I_q LDO 150–250 mA 0.2–0.3 V Battery devices: I_q of ~1–8 µA
AP2112 / MIC5219 / LP2985 Low-noise LDO 150–600 mA ~0.25 V General small boards
TL431 Shunt regulator / adjustable reference — — Precision references, power supply feedback (chapter 28)
Zener + resistor Shunt regulator Small — The simplest regulator (chapter 13)

Heat math

A 7805 fed 12 V supplying 500 mA wastes (12 − 5) × 0.5 = 3.5 W. A bare TO-220 package (~50–65 °C/W) would rise ~200 °C, so it needs a heatsink or, better, a switching regulator. Rule of thumb without a heatsink: TO-220 ≤ ~1 W, SOT-223 ≤ ~0.5–1 W (with copper area), SOT-23 ≤ ~0.2–0.3 W.

Most linear regulators have thermal shutdown. When too hot they turn off, cool, and restart, which shows up as a device that cuts out after running a while.

When linear is the right choice


20.2 Switching regulators

How they work

A switching regulator ("switcher," "SMPS," "DC-DC converter") rapidly switches a transistor fully on and off, typically 100 kHz–3 MHz, and uses an inductor and capacitors to store and release energy in controlled bursts. The ratio of on-time to off-time (the duty cycle) sets the output voltage, and a feedback loop adjusts it continuously.

Because the transistor is always fully on or fully off, it wastes little power. Efficiency is typically 80–95 %, regardless of the voltage ratio.

Power in ≈ power out ÷ efficiency. So:

Topologies

Type Does How (simply) Examples
Buck (step-down) V_out < V_in The switch feeds the inductor in pulses; the inductor smooths them LM2596, MP1584, XL4015, MP2307, TPS5430, "mini-360" modules
Boost (step-up) V_out > V_in The inductor charges from the input, then releases its energy stacked on top of the input voltage MT3608, XL6009, TPS61xxx, SX1308
Buck-boost / SEPIC Either up or down Combination topologies TPS63xxx, LTC3780, XL6019 (SEPIC)
Inverting Negative output from positive input Buck-boost variant Op-amp supplies
Charge pump Doubles, inverts, or halves voltage using only capacitors Switches capacitors between configurations. Low current ICL7660 (inverter), LM2664, MAX232 (internal)
Flyback Isolated, any ratio Transformer stores energy, then releases it Phone chargers, wall adapters
Forward / half-bridge / full-bridge Isolated, higher power Transformer-coupled PC power supplies, industrial
Buck and boost converters and their current paths.
Buck and boost converters and their current paths.

Key specs

Spec Meaning
Input voltage range e.g. 4.5–28 V
Output current For a boost, the switch current limit is often quoted, and the real output current is much lower at high step-up ratios
Efficiency curve Efficiency varies with load. Often poor at very light loads
Switching frequency Higher = smaller inductor and caps, but more switching loss
Output ripple Small residual wobble (tens of mV typical)
Quiescent current Idle draw; matters for battery devices
Synchronous vs non-synchronous Synchronous converters use a second transistor instead of a diode, which gives higher efficiency
PFM / PWM / light-load mode How it behaves at small loads: "burst" modes save power but add ripple
Enable pin Turn the regulator on/off from logic
Soft-start, current limit, thermal shutdown Protection features

Using switching modules well

Noise and layout

The fast switching produces electrical noise (EMI) and output ripple:


20.3 Choosing a regulator

Situation Choose
Small drop, low current (< ~200 mA), noise-sensitive LDO
Battery device with long sleep times Ultra-low-I_q LDO or buck with low I_q
Large drop or high current (e.g. 12 V → 5 V at 2 A) Buck
Battery voltage below what's needed (1 cell Li-ion → 5 V) Boost
Battery crosses the needed voltage (Li-ion 4.2 → 3.0 V, need 3.3 V) Buck-boost
Need a small negative rail Charge-pump inverter or inverting converter
Isolation from mains Isolated flyback/forward supply (usually buy a certified module)

20.4 Did you know?


20.5 Testing regulators

Test How Good
Input voltage DC volts from input to ground Within spec, and above V_out + dropout
Output voltage DC volts output to ground, no load then loaded Within ~1–3 % of nominal, barely changing under load
Enable pin Voltage on EN At the "on" level (per datasheet)
Ripple Oscilloscope (AC-coupled) or meter's AC mV mode on the output Small (tens of mV). Large or rising ripple = failing output capacitor
Temperature Touch carefully or use a thermometer Warm is fine. Too hot to touch means overload or wrong input voltage
Current draw with no load Meter in series with the input Small (µA–mA). Large = internal short or damaged part
Feedback divider (adjustable) Measure the resistors, power off Correct values; the FB pin at its reference voltage (e.g. 0.8 V or 1.25 V) when running

20.6 How regulators fail

Failure Symptom Cause
Output 0 V, input OK Device dead Regulator failed open, enable pin low, thermal shutdown, short on the output
Output equals input Downstream parts see full input voltage (often destroying them) Linear regulator or buck switch failed shorted: the worst-case failure
Output low under load Resets, brownouts Input too low (dropout), overheating, overloaded module, current limit
Output oscillates or is noisy Erratic behavior Wrong or failed output capacitor (ESR out of range), poor layout
Cuts out after minutes Works when cool Thermal shutdown: too much power dissipated
Whining Audible noise Light-load burst mode, loose inductor; usually harmless
Boost output wildly high Damaged loads Trimmer set wrong, broken feedback resistor
Very hot switcher Low efficiency Inductor saturating (overload), wrong inductor, failing diode or MOSFET

21 — Power supplies and USB power

Every circuit needs a source of power. This chapter covers where it comes from (wall adapters, bench supplies, USB, and power banks), how to plan how much you need, how to distribute it, and how to recognize the most common power-related fault: the brownout.


21.1 Types of power supply

Type How it works Traits
Linear (transformer) supply Mains transformer → rectifier → large capacitor → linear regulator Heavy, inefficient, very low noise. Old wall "bricks" and some audio gear
Unregulated "wall wart" Transformer + rectifier only Output voltage is much higher with no load (a "12 V" one may read 16–18 V unloaded)
Switch-mode power supply (SMPS) Rectify mains → switch at high frequency through a small transformer → rectify and regulate Light, efficient, universal input (100–240 V). Almost all modern chargers and adapters
Open-frame / enclosed industrial supply SMPS on a metal chassis with screw terminals Fixed voltages (5, 12, 24, 48 V), high current, an output trim pot. Some have a 115/230 V selector switch: check it before powering on
DIN-rail supply SMPS that snaps onto a 35 mm rail Control panels
ATX (PC) supply Multiple rails (12 V, 5 V, 3.3 V, 5 V standby). The green PS_ON wire to ground turns it on Cheap high current, but the rails are designed around PC loads
Bench (lab) power supply Adjustable constant voltage (CV) and constant current (CC) The best tool for development: set a current limit so faults don't burn things
Battery / power bank Chapter 19 Portable
Solar + charge controller Panel → controller (PWM or MPPT) → battery Off-grid

Reading a power adapter label

Ratings are maximums

A supply provides the current the load draws, up to its rating. A 5 V 10 A supply powering a 1 A device delivers 1 A. Using a bigger supply is safe as long as the voltage is right. The voltage must match. The current rating only needs to be enough.

Derate for continuous use: plan for ≤ 80 % of the rated current, and less in hot, enclosed spaces.


21.2 USB power

Source Voltage Current
USB 2.0 port 5 V 500 mA
USB 3.x port 5 V 900 mA
USB Battery Charging (BC 1.2) dedicated charger 5 V Up to 1.5 A (the charger signals this by shorting the data lines)
Proprietary "fast" chargers (Apple, Samsung) 5 V 2–2.4 A, via resistor signalling on D+/D−
USB-C (default, no negotiation) 5 V 1.5 A or 3 A, advertised by resistors on the CC pins
USB Power Delivery (PD) 5, 9, 15, 20 V (SPR); up to 28, 36, 48 V (EPR) Up to 3 A; 5 A with an e-marked cable. Up to 100 W (SPR) / 240 W (EPR)
PD PPS (programmable power supply) 3.3–21 V in 20 mV steps Used for direct fast charging of phones
Quick Charge (QC 2/3) 5–12 V (or 3.6–20 V in steps) Proprietary. Negotiated over D+/D−

How USB-C decides what to deliver

A USB-C charger keeps its output off until something is connected. The CC (configuration channel) pins do the negotiating:

The CC resistors that tell a USB-C charger a device is connected.
The CC resistors that tell a USB-C charger a device is connected.

Cables matter


21.3 Power banks

A power bank is a lithium battery + charger + boost converter + (often) a PD controller.


21.4 Power budgets

Before choosing a supply, list every load:

Load Voltage Typical current Peak current
Microcontroller with Wi-Fi 3.3 V 80 mA 400 mA (radio transmit bursts)
LED strip (60 pixels) 5 V 0.6 A 3.6 A (full white)
Servo × 2 5 V 20 mA 1.4 A (both stalled)
Display 3.3 V 20 mA 30 mA

Then:

  1. Sum the peaks per rail, since they can coincide.
  2. Add margin (≥ 20–25 %).
  3. Account for converter efficiency when rails come from a common source.
  4. Size wiring and fuses for each branch (chapters 4, 7).
  5. Battery runtime ≈ Wh ÷ average W.

21.5 Distributing power


21.6 Brownouts

A brownout is a dip in supply voltage that's brief or partial, not a full outage. Digital chips may reset, freeze, corrupt data, or behave strangely. Microcontrollers often have a brown-out detector (BOD) that deliberately resets the chip below a threshold voltage to prevent erratic operation.

A supply dip resetting a microcontroller, and the same event with a bulk capacitor.
A supply dip resetting a microcontroller, and the same event with a bulk capacitor.

Common causes:

Diagnosis: measure the supply at the affected chip's pins while the event happens. Use a meter's MIN/MAX capture, or better, an oscilloscope triggered on the dip.

Fixes, roughly in order:

  1. Shorter, thicker power wiring; fewer connectors.
  2. Bulk capacitance at the load (100–1,000 µF), plus 100 nF at each chip.
  3. Separate supplies or regulators for the heavy load, with a common ground.
  4. A larger supply, or a battery with lower internal resistance.
  5. Soft-start for motors and large capacitive loads.

21.7 Grounding and noise


21.8 Did you know?


21.9 Testing power supplies

Test How Good
No-load output DC volts at the output At rated voltage (regulated), or somewhat higher (unregulated)
Loaded output DC volts with a real load or a test resistor Within ~5 % of rated
Ripple AC mV range, or an oscilloscope, on the output under load Tens of mV. Hundreds of mV or 50/60/100/120 Hz ripple = failing capacitors
Polarity DC volts, red on the barrel center Positive reading for center-positive supplies
USB USB power meter Voltage stays above ~4.75 V at the expected current; PD negotiates as expected
Current limit (bench supply) Short the output through the meter's 10 A range or a load Current held at the limit set
Visual / smell Bulging capacitors, scorched areas, burnt smell None

⚠️ Don't open mains-powered supplies unless you know what you're doing. Their primary capacitors can hold dangerous charges after unplugging.


21.10 How power supplies fail

Symptom Likely cause
Dead, no output Blown internal fuse (often from a failed switching transistor), failed startup circuit
Output cycles on and off ("hiccup") Overload or short on the output; protection engaging; failing capacitor
Voltage low or sagging under load Aging capacitors, overload, damaged cable
High ripple, hum, device misbehavior Dried-out output capacitors: the most common failure in older supplies
Whining or squealing Light load, failing capacitors, loose inductor
Intermittent Broken wires inside the cable near the plug or strain relief: very common. Wiggle test
USB-C device won't charge from C-to-C Missing 5.1 kΩ CC resistors in the device
Power bank turns off Load too small, triggering auto-off

22 — Motors and actuators

Motors and actuators turn electricity into motion. They're also the most electrically demanding parts in most projects. They draw large surges, generate electrical noise, and produce voltage spikes, so the driver and power supply matter as much as the motor itself.


22.1 The basic principle

A current-carrying wire in a magnetic field feels a force. Wind the wire into coils, arrange magnets around them, and switch the current at the right moments, and that force becomes continuous rotation. Every electric motor is a variation on this idea. Run in reverse (spin the shaft), most motors become generators.


22.2 Brushed DC motors

How it works

The spinning part (rotor or armature) carries coils. The stationary part (stator) has permanent magnets. Brushes (carbon or metal contacts) rub against a segmented ring on the shaft (the commutator), which switches current between the coils as the rotor turns so that the push always continues in the same direction.

Behavior

Types and variants

Type Notes
Small hobby motors (130, 180, 260 size) Cheap, fast (thousands of RPM), low torque. Toys
Gear motors A motor + gearbox trading speed for torque. N20 micro gear motors, "TT" yellow robot motors, metal gearboxes
Coreless motors No iron in the rotor. Very fast response, small drones
Vibration motors (ERM) An off-center weight on a small motor. Phones, controllers
Linear resonant actuators (LRA) A mass on a spring vibrated at resonance. Crisp haptics
Universal motors Brushed motors that run on AC or DC. Drills, blenders, vacuums

Driving brushed motors

An H-bridge running a motor forward and in reverse.
An H-bridge running a motor forward and in reverse.

H-bridge input logic (typical two-input driver):

IN1 IN2 Result
0 0 Coast (free-wheel)
1 0 Forward
0 1 Reverse
1 1 Brake (motor terminals shorted, stops quickly)

Speed is set with PWM on one input.

Driver Type Motor voltage Current Notes
L298N Bipolar dual H-bridge 5–35 V 2 A per channel Classic but inefficient: ~2–4 V lost in the driver, so it runs hot
L293D Bipolar dual H-bridge 4.5–36 V 0.6 A Small motors; built-in diodes
DRV8833 MOSFET dual H-bridge 2.7–10.8 V ~1.5 A Efficient, small. Has a sleep pin
TB6612FNG MOSFET dual H-bridge 2.5–13.5 V 1.2 A (3.2 A peak) Popular robotics driver
DRV8871 / VNH5019 / BTS7960 MOSFET, single high current up to ~40 V 3.6 A / 12 A / 40 A+ Bigger motors
ULN2003 / ULN2803 Darlington arrays up to 50 V 500 mA per channel One-direction loads, small unipolar steppers

Taming motor noise

  1. A 100 nF ceramic capacitor directly across the motor terminals. Many also add one from each terminal to the motor's metal case.
  2. Twist the motor leads together.
  3. A bulk capacitor (100–1,000 µF) at the driver's supply input.
  4. Separate power for motors and logic, with a common ground.
  5. Keep motor wiring away from sensor and signal wiring.

22.3 Brushless DC motors (BLDC)

How it works

The permanent magnets are on the rotor, and the coils are on the stator. With no brushes, something must switch the coil currents in sequence. That's an electronic controller (ESC, electronic speed controller) or driver IC, using either Hall-effect sensors or the back-EMF of the un-driven coil (sensorless) to know the rotor position.

Hobby ESCs take a servo-style PWM signal (1–2 ms pulses at 50 Hz, or faster digital protocols) and need to be armed (a minimum throttle signal at power-up) before they'll run.

PC fans: 2-wire (power only), 3-wire (+ tachometer output), 4-wire (+ PWM speed control input at ~25 kHz).


22.4 Stepper motors

How it works

A stepper's rotor moves in fixed angular steps as the driver energizes its coils in sequence. A typical 1.8° stepper takes 200 steps per revolution. The controller counts steps to know the position, with no feedback sensor needed, as long as the motor doesn't skip.

Types

Type Wires Notes
Bipolar 4 Two coils; needs an H-bridge per coil. More torque. NEMA 17 in 3D printers
Unipolar 5 or 6 Center-tapped coils, simpler to drive (e.g. 28BYJ-48 with ULN2003 board)
Hybrid / permanent-magnet / variable-reluctance — Construction variants. Hybrid is the common precision type

NEMA sizes (NEMA 8, 11, 14, 17, 23, 34) describe the faceplate dimension (NEMA 17 ≈ 42 mm square), not the power.

Driving steppers

Identifying coil pairs

On a 4-wire stepper, pairs of wires with low resistance between them (a few ohms) are one coil. Wires from different coils read open. Shorting a coil pair makes the shaft noticeably harder to turn by hand.


22.5 Servo motors

Hobby (RC) servos

A small DC motor + gearbox + a potentiometer on the output shaft + a control board, in one case. The board compares the requested position with the pot's reading and drives the motor until they match. That's closed-loop control.

Pulse width sets a hobby servo's angle.
Pulse width sets a hobby servo's angle.

Industrial servos

Closed-loop motors (often brushless) with encoders and dedicated drives. They're used in CNC machines and robotics, where precise speed and position are both controlled.


22.6 Other actuators

Actuator How it works Notes
Solenoid A coil pulls an iron plunger Door locks, valves, pinball flippers. Needs a flyback diode. Can use high "pull-in" current then a lower "hold" current (PWM)
Solenoid valve A solenoid operating a valve Water and air control. Normally-closed or normally-open
Linear actuator A motor + leadscrew Push/pull rods. Often with built-in limit switches
Voice coil actuator A coil in a magnet gap, like a speaker Hard-drive heads, precision positioning
Piezo actuator A crystal that flexes with voltage Tiny, fast, precise movements; ultrasonic motors
Shape-memory alloy (Nitinol) wire Contracts when heated by current Silent, small motions
Electromagnet A coil + iron core Holding, lifting, locks
Peristaltic / diaphragm pumps A motor driving a pump Liquid dosing, air

22.7 Encoders and feedback

To know the actual speed or position of a motor:


22.8 Did you know?


22.9 Testing motors and actuators

Part Test Good Bad
Brushed DC motor Ω across the terminals, rotating the shaft slowly A few Ω, steady-ish OL at some positions = worn brushes or a broken winding; 0 Ω = shorted
Brushed DC motor Run from a bench supply with a current limit Smooth, current near the spec High current at no load = binding or shorted turns
Motor as generator Spin the shaft by hand with the meter on DC mV/V A voltage appears Nothing = open circuit
BLDC motor Ω between each pair of the three wires Three equal low readings Unequal readings = damaged winding
Stepper Ω between wire pairs Equal coil resistances; no reading between coils Open coil
Servo Hz/% mode on the signal wire ~50 Hz, 5–10 % duty No signal = code or wiring issue
Servo Measure current while moving Surges on movement, low when idle Constant high current = stalled or damaged
Solenoid / coil Ω Matches the rated coil resistance Open or shorted
Driver chip Voltage at the outputs while commanded Near the supply voltage and ground No output: check enable/sleep pins and the supply

22.10 How motors fail

Symptom Likely cause
Won't start, hums or draws high current Mechanical jam, seized bearing, dead spot on the commutator, failed start capacitor (AC)
Runs weakly or slowly Worn brushes, weak supply, voltage drop in the wiring, failing magnets, a driver with a high voltage drop (L298N)
Runs hot Overload, stalled, too much current (steppers set too high), poor ventilation
Intermittent Worn brushes, broken lead at the motor terminal, bad connector
Electronics reset when the motor starts Brownout from inrush current. Add capacitance, separate supplies, soft-start
Radio or sensor interference Brush noise. Add a capacitor across the terminals, twist the leads, use ferrites
Driver chip hot or shutting down Over-current, stall, inadequate heatsinking, thermal protection
Stepper skips steps Too fast acceleration, too little current, too much load, supply voltage too low
Servo jitters Noisy power, weak supply, poor signal ground, electrical noise on the signal wire
Driver transistor dies Missing flyback protection

23 — Sound: speakers, buzzers, amplifiers and microphones

Sound is vibration traveling through air, a rapid rise and fall in pressure. Humans hear roughly 20 Hz to 20,000 Hz (the upper limit falls with age). Electronics makes sound by moving a surface in that pattern, and hears it by catching the pattern with a membrane.


23.1 Speakers

How a dynamic speaker works

A voice coil (a coil of fine wire) is attached to a cone or dome and sits in the gap of a permanent magnet. Audio current flowing through the coil makes it an electromagnet, which pushes and pulls against the permanent magnet. The cone moves in and out, pushing air. A flexible surround and spider center the cone and let it move.

Cross-section of a dynamic speaker.
Cross-section of a dynamic speaker.

Key specs

Spec Meaning
Impedance (Ω) Its "AC resistance," nominally 4 Ω or 8 Ω (sometimes 2, 16, 32 Ω, or higher for headphones). The DC resistance measures somewhat lower (an 8 Ω speaker often reads 6–7 Ω)
Power rating (W) The continuous power it can handle without damage
Sensitivity (dB SPL at 1 W / 1 m) How loud it is per watt. 3 dB more sensitivity = the same loudness from half the power
Frequency response The range it reproduces usefully. Small speakers can't reproduce deep bass
Size Larger cones move more air and produce more bass

Types

Type Use
Full-range driver Small devices, one speaker covering everything
Woofer / subwoofer Bass
Midrange Voices, instruments
Tweeter Treble. A small dome or horn
Micro speakers Phones, toys, small modules (often 8 Ω 0.5–3 W, or 4 Ω 3 W)
Exciters / transducers Attach to a surface (a window or panel) and make it a speaker
Headphone drivers 16–300 Ω+
Piezo speakers / tweeters High-pitched and efficient, poor bass

Enclosures

A bare speaker sounds thin, because the sound from the back of the cone (which is inverted) wraps around and cancels the sound from the front at low frequencies. Mounting it in a sealed box, a ported box, or a large baffle keeps front and back apart and dramatically improves bass. Even a small closed box helps a tiny speaker.

Wiring speakers together


23.2 Buzzers and piezo sounders

Type Inside How to drive Sound
Active buzzer Sounder + built-in oscillator Apply DC → it beeps at a fixed pitch One tone
Passive buzzer (magnetic) A small coil and a metal diaphragm Needs an AC or square-wave signal at the desired frequency Any pitch: melodies
Piezo disc A brass disc with a piezoelectric ceramic layer A square wave. Loudest near its resonant frequency (~2–4 kHz) Any pitch. Also works as a knock/vibration sensor
Piezo siren / alarm A piezo element with a driver circuit DC Very loud (85–120 dB)

Tips:


23.3 Amplifiers

A microcontroller pin or audio DAC produces only a weak signal. An amplifier boosts it enough to move a speaker.

Amplifier classes

Class How it works Efficiency Traits
A Output transistors always conducting ~25 % max Clean, simple, very hot
B A push-pull pair, each handling half the waveform ~78 % max "Crossover distortion" at the handover
AB Push-pull with a little bias ~50–70 % The traditional hi-fi compromise (e.g. LM386, TDA2030, LM1875)
D Switches the output transistors on and off at high frequency (PWM), filtered by the speaker or an LC filter 85–95 % Cool, small, battery-friendly. Most modern amplifier modules

Common amplifier chips and modules

Part Class Input Output Notes
LM386 AB Analog ~0.3–1 W The classic small amp. Easy, noisy
PAM8403 D Analog stereo 2 × 3 W (4 Ω, 5 V) Tiny, cheap modules
PAM8302 D Analog mono 2.5 W Small
MAX98357A D I²S digital 3.2 W (4 Ω, 5 V) Digital audio straight from a microcontroller
TPA3116 / TPA3118 D Analog 2 × 50 W Larger speakers, 12–24 V supply
TDA2030 / LM1875 AB Analog 15–30 W Classic DIY hi-fi

Bridged (BTL) outputs

Many small class-D and some class-AB amplifiers use a bridge-tied load: both speaker terminals are actively driven, in opposite directions. This quadruples the power available from a low supply voltage.

In a bridged amplifier, both speaker wires are driven.
In a bridged amplifier, both speaker wires are driven.

⚠️ Never connect either speaker terminal of a bridged amplifier to ground, or to the terminal of another channel. That shorts an output stage. Each speaker connects only to its own two output pins.

Filterless class D

Small class-D chips rely on the speaker's own inductance to filter the switching frequency. Keep speaker wires short, or add ferrite beads or an LC filter to reduce radio interference.


23.4 Audio signal levels

Level Typical voltage Example
Microphone 1–100 mV Needs a preamp
Instrument 100 mV–1 V Guitar pickups
Consumer line ~0.3 V RMS (−10 dBV) Phones, computers, RCA outputs
Pro line ~1.2 V RMS (+4 dBu) Mixing desks
Speaker Several to tens of volts Amplifier outputs

Decibels (dB) express ratios on a logarithmic scale: +3 dB ≈ double the power, +6 dB ≈ double the voltage, and +10 dB sounds roughly "twice as loud."


23.5 Audio playback modules


23.6 Microphones

Type How it works Output Notes
Dynamic A coil on a diaphragm moving in a magnet: a speaker in reverse Low-level analog Rugged, no power needed. Stage vocal mics
Condenser A diaphragm forms one plate of a capacitor. Sound changes the capacitance Analog. Needs power ("phantom power," 48 V) Studio quality
Electret A condenser with a permanently charged diaphragm and a built-in JFET preamp Small analog signal. Needs a bias voltage (2–10 V through a ~2.2–10 kΩ resistor) Cheap. Two-lead metal cans in countless devices. The output is AC-coupled through a capacitor
MEMS analog Silicon micro-diaphragm with a preamp Analog Tiny. In phones
MEMS digital (I²S / PDM) MEMS + built-in ADC Digital audio stream (e.g. INMP441, SPH0645, ICS-43434) Direct to a microcontroller, immune to analog noise pickup
Piezo contact mic A piezo disc picking up vibrations Analog, high impedance Instruments, knock detection

Electret polarity: the lead connected to the metal case is ground (negative). The other lead is the output and bias input.

Biasing an electret microphone.
Biasing an electret microphone.

Sound-sensor modules (electret + comparator, with a digital output and a sensitivity pot) detect "loud noise," like a clap, but aren't suitable for recording audio.


23.7 Noise in audio circuits

Audio amplifies everything, including electrical noise:

Noise Sounds like Common cause Fix
Hum (50/60 Hz and harmonics) Low drone Ground loops, mains pickup, poor power supply filtering Single ground path, shielded cable, better filtering, isolation transformer
Buzz (120 Hz, harsh) Rough drone Rectifier ripple, ground current in the signal path Separate power and signal grounds; bigger filter capacitors
Whine (varying pitch) High whistle that changes with activity Digital noise, switching regulators, PWM Separate or clean supply, ferrites, keep digital lines away
Hiss Steady "shhh" Amplifier gain too high, noisy preamp, cheap modules Lower gain, better parts, correct gain staging
Clicks / pops At power on/off DC offset charging coupling capacitors Mute or soft-start circuits, a speaker delay relay
Periodic ticking/buzzing Rhythmic Radio transmitters (Wi-Fi, GSM bursts) coupling in Shielding, filtering, distance

23.8 Did you know?


23.9 Testing audio parts

Part Test Good Bad
Speaker Ω across the terminals Slightly below nominal (e.g. 6–7 Ω for 8 Ω) OL = open voice coil
Speaker (quick) Briefly touch a 1.5 V battery across it A scratchy click, cone moves Silence = dead. Scraping = rubbing voice coil
Speaker (visual) Gently push the cone evenly Smooth travel Scraping = damaged voice coil. Torn cone or surround
Active buzzer Apply rated DC Beeps Silent
Passive buzzer Ω A few Ω to tens of Ω (magnetic); open for piezo Open (magnetic type)
Electret mic DC volts at the output lead with bias applied Roughly half the bias supply 0 V or full supply = dead or shorted JFET
Amplifier output DC volts across the speaker terminals, no signal Near 0 V (under ~50 mV) Large DC = failed amp (can destroy speakers)
Amplifier Feed a known signal (a phone headphone output) Clean, loud output Distortion, noise, or nothing

23.10 How audio parts fail

Symptom Likely cause
Distorted sound at volume Overdriven amplifier (clipping), supply sagging, damaged speaker cone or coil
No sound, amp OK Open voice coil, broken lead, speaker disconnected
One channel dead Failed amplifier channel, broken wire, bad connector
Crackling when turning volume Dirty potentiometer (chapter 9)
Hum or buzz Ground loops, power supply ripple, shielding. See §23.7
Amp cuts out Over-temperature (inadequate heatsinking), overload (impedance too low), short in speaker wiring
Buzzer silent Driven with DC when passive (or vice versa), polarity reversed, too little current

24 — Displays

Displays turn data into light (or into reflected light) that people can see. Understanding the technology tells you a display's strengths and quirks: why OLEDs have perfect black, why LCDs need a backlight, why e-paper is slow, and why a laptop screen needs a separate controller board.


24.1 Display technologies compared

Technology How it makes an image Backlight? Strengths Weaknesses
LED segments / matrices Individual LEDs No (self-lit) Bright, robust, simple Low resolution
Character LCD Liquid-crystal cells forming 5×8 dot characters Usually (LED) Cheap, readable, low power Text only, limited contrast and viewing angle
Graphic / TFT LCD Liquid-crystal pixels, each switched by a thin-film transistor Yes Color, high resolution, cheap Needs a backlight. Black isn't truly black
OLED Each pixel is a tiny organic LED No (self-lit) True black, high contrast, wide viewing angle, fast Burn-in over time, costlier in large sizes
E-paper (e-ink) Charged black/white (or colored) particles moved by electric fields No (reflective) Readable in sunlight, holds the image with zero power Slow refresh (0.3–15 s), ghosting, limited colors
VFD (vacuum fluorescent) Phosphor segments glow under electron bombardment in a vacuum No (self-lit) Bright, distinctive blue-green glow High voltage needed, fragile, aging
Nixie tube Neon glow around number-shaped cathodes No Beautiful, retro ~170 V DC needed, obsolete (new-old stock)
CRT Electron beam scanning a phosphor screen No Historic Heavy, very high voltage (tens of kV)

24.2 LED segment and matrix displays

Seven-segment naming, and the digit 4.
Seven-segment naming, and the digit 4.

24.3 Character LCDs (HD44780-compatible)

The ubiquitous 16×2 and 20×4 text displays.

💡 The classic first-power-up mystery: a row of solid blocks, or nothing visible with the backlight on. It's almost always the contrast setting. Turn the trimmer until text or blocks appear. A row of blocks with contrast correct means the display is powered but not initialized: check the wiring, the I²C address, and the code.


24.4 Graphic LCDs and TFTs


24.5 OLED displays


24.6 E-paper (e-ink)


24.7 Laptop and monitor panels

A full-size LCD panel is really three subsystems:

  1. The panel (glass, liquid crystal, and row/column drivers). Its timing controller (TCON) accepts pixel data over a high-speed interface: - LVDS (low-voltage differential signalling): common in panels from the late 1990s to the 2010s. Several differential pairs, single- or dual-channel, 6-bit or 8-bit color, with two bit-mapping conventions (VESA and JEIDA). A mismatch produces wrong colors. - eDP (embedded DisplayPort): modern laptops. - MIPI DSI: phones and small displays.
  2. A controller / scaler board (for reusing panels): converts HDMI, VGA, or DisplayPort into the panel's native interface and timing, and provides an on-screen menu. Controller boards are matched to specific panel models, since resolution, interface, voltage, and bit mapping must all agree.
  3. The backlight: - CCFL (cold-cathode fluorescent lamp): thin fluorescent tubes in older panels. They need an inverter producing ~500–1,500 V AC. ⚠️ Dangerous voltage, and the lamps contain a little mercury. - LED: strings of white LEDs driven by a boost converter (~20–60 V DC). Modern panels. - Dimming is usually PWM on an enable or dim input.
The layers of an LCD panel.
The layers of an LCD panel.

Diagnosing a dark laptop screen: shine a flashlight at the screen at an angle. If you can faintly see the image, the panel and video signal are fine, and the backlight (lamp, LEDs, or inverter/driver) has failed.


24.8 Touchscreens

Type How it works Notes
Resistive Two conductive layers pressed together at the touch point; measured as a voltage divider Works with a stylus or gloves. Needs pressure. Single touch. Needs calibration
Capacitive (projected) A grid of electrodes senses a finger's capacitance Multi-touch, smooth, no pressure. Needs a bare finger or a special stylus. Every smartphone
Infrared IR beams across the screen surface are interrupted by a finger Large displays, kiosks
Surface acoustic wave Ultrasonic waves on the glass Kiosks

24.9 Did you know?


24.10 Testing and diagnosing displays

Symptom Likely cause Check
Nothing at all, no backlight No power, wrong wiring Voltage at the display's power pins
Backlight on, no image Contrast (character LCD), not initialized, wrong driver or address Adjust contrast; I²C scan; check the controller type in code
Garbled characters Wiring error, loose data line, timing, wrong mode (4/8-bit) Continuity on each data line
Image shifted with a stripe of noise SH1106 driven as SSD1306 Change the driver
Wrong or swapped colors RGB/BGR order setting, LVDS bit mapping (VESA/JEIDA), wrong color depth Change the setting in code or the controller menu
Mirrored or rotated image Rotation setting Change it in code
Faint image visible only with a flashlight Backlight failed Backlight voltage, LED string, inverter, fuse
Flickering Loose ribbon cable, backlight PWM too slow, failing inverter or lamp Reseat cables; check PWM frequency
Lines or dead columns Damaged ribbon, failed column/row driver, cracked glass Reseat the connector; press gently near the edges (a connection issue if it changes)
E-paper ghosting Too many partial refreshes Full refresh
E-paper doesn't update BUSY not handled, cold temperature, SPI wiring Check BUSY; test at room temperature
Touch inaccurate Needs calibration (resistive), or electrical noise (capacitive) Calibrate; improve grounding

Meter checks: supply voltage at the module, backlight voltage (LED strings sometimes use tens of volts), and I²C/SPI lines idling at the expected levels (chapter 30).


24.11 How displays fail

Failure Cause Symptom
Backlight LED string open Age, overcurrent, one LED in the series string failing Image only visible with a flashlight shone on the screen
Backlight inverter or CCFL lamp worn out (older LCDs) Aging lamps and inverter capacitors Backlight comes on for a few seconds, then shuts off
Cracked glass Impact, twisting, uneven pressure when mounting Ink-like blot that spreads, lines radiating from a point
Flex cable or connector fault Repeated folding (laptop hinges), cracked flex, loose latch Lines, flicker, or colors that change when the cable or lid moves
Row or column driver failure Heat, flexing of the bonded driver chip on the glass edge Permanent vertical or horizontal lines, dead bands
OLED burn-in Static content (logos, status bars) at high brightness for long periods A ghost of the static image that never fades
OLED uneven aging Blue emitters wear faster than red and green Colors shift toward yellow over years; overall dimming
LCD overheated Direct sun or heat above the liquid crystal's limit Display goes dark or blotchy; often recovers when it cools
Polarizer damage Heat, UV, age Haze, yellowing, bubbles, or a peeling front film
E-paper damaged by constant voltage Driver left powered instead of put to sleep after a refresh Permanent ghosting or faded areas
Stuck or dead pixels Manufacturing defect, pressure point One sub-pixel always lit or always dark
Touch layer worn or cracked Scratches (resistive), cracked cover glass (capacitive) Dead zones or phantom touches

Most "dead" displays have a live panel and a failed backlight, cable, or supply. Check those before replacing the panel.

25 — Input devices

Input devices let people tell a circuit what to do: buttons, knobs, keypads, joysticks, touch pads. Most are simple switches or resistors (chapters 6 and 9). The interesting part is reading them reliably, with pull-ups, debouncing, scanning, and decoding.


25.1 Reading a button

Pull-ups and pull-downs

A digital input connected to nothing floats and reads randomly. Every button input needs a defined default state:

For long wires, noisy environments, or battery devices, choose external resistors deliberately: smaller values (1–10 kΩ) resist noise better, and larger values (47–100 kΩ) use less current while the button is held.

Debouncing

Mechanical contacts bounce, making and breaking several times over 1–20 ms (chapter 6). Without debouncing, one press may register as several.

Common patterns


25.2 Rotary encoders

A rotary encoder is a knob that turns endlessly and reports steps and direction rather than an absolute position.

Mechanical incremental (quadrature) encoders

Two internal switches, A and B (often labelled CLK and DT), open and close as the shaft turns, 90° out of phase with each other. Which one changes first tells you the direction. Many encoders also have a push switch in the shaft (SW).

Quadrature signals: which channel changes first gives the direction.
Quadrature signals: which channel changes first gives the direction.

Other encoder types

Type How Use
Optical incremental A slotted disc and an LED/photosensor pair Motors, precise positioning, high PPR
Magnetic incremental A magnet and Hall sensors Motors, robust
Absolute Reports the exact angle (Gray code, or digital like AS5600) Knowing position at power-up
Potentiometer An analog absolute position over limited rotation Chapter 9

💡 Gray code: absolute encoders use a binary sequence in which only one bit changes between neighboring positions, so a reading taken mid-transition is never wildly wrong.


25.3 Keypads and key matrices

Wiring every key to its own pin is impractical for more than a few keys. A matrix places keys at the crossings of rows and columns:

Scanning a key matrix row by row.
Scanning a key matrix row by row.

Ghosting and masking

Press three keys at three corners of a rectangle, and current can flow backwards through them, making the fourth corner appear pressed (ghosting). Remedies:

Other keypad types


25.4 Joysticks and analog controls


25.5 Capacitive touch

A capacitive touch sensor detects the small extra capacitance a finger adds to a metal pad (chapter 10).

Touchscreens are covered in chapter 24.


25.6 Other input devices

Device Principle Notes
Slide / DIP switches Mechanical Read at boot for configuration
Reed switch + magnet Magnetic Door/lid detection (chapter 6)
Hall-effect switch Magnetic field sensor, digital output Contactless buttons, lid detection, wheel counting
Tilt switch Rolling ball Orientation or shake detection
Force-sensitive pads Chapter 9 Pressure-sensitive input
IR remote receiver Chapter 14 Remote-control input
Gesture sensors (e.g. APDS-9960) IR reflections Hand swipes
Microphone Clap/sound detection Chapter 23

25.7 Did you know?


25.8 Testing and diagnosis

Symptom Likely cause Check
Button reads pressed all the time Wired across permanently joined pins (4-pin tactile switch), short, wrong active level in code Continuity across the switch
Random presses Floating input (no pull-up), long unshielded wires, noise Enable pull-ups; add a capacitor; shorter wires
One press counts as several Bounce Debounce in software or hardware
Encoder counts erratically or backwards A/B swapped, bounce, too slow polling, wrong steps-per-detent Swap A/B; use a proper decoder or library
Wrong keys in a matrix Row/column mapping error, ghosting Map by scanning each key; add diodes
Joystick drifts Center not calibrated, worn pots Calibrate; dead zone
Touch pad unresponsive Touched during power-up calibration, too thick an overlay, pad too small Power-cycle without touching; thinner cover; bigger pad
Touch triggers by itself Noise, moisture, sensitivity too high Grounding, filtering, adjust threshold

Meter tests: continuity across switches (pressed vs released), resistance across pots while turning, and voltage on the input pin (it should swing cleanly between ~0 V and the logic supply).


25.9 How input devices fail

Failure Cause Symptom
Worn or oxidized switch contacts Age, humidity, very low switching current (no "wetting" current to clean the contacts) Needs a harder press, works intermittently
Bounce getting worse Contact wear Double presses that didn't happen when the switch was new
Worn encoder contacts Wear, dust Skipped or extra steps, the count jumping backwards
Worn pot track (joysticks, knobs) Wear, dirt Drift, jumpy or scratchy readings, dead spots
Cracked membrane-keypad trace Repeated flexing of the ribbon tail A whole row or column stops responding
Contamination Spills, dust Keys stick, or register as permanently pressed
Broken panel-mount joints Twisting a knob or encoder that has no mounting nut Works only when the knob is pushed sideways
Capacitive pad degraded Overlay lifting (air gap), moisture ingress, corroded pad Sensitivity drops or touches register by themselves
Input pin damaged by static Discharge through a touched button or long wire to an unprotected pin Input stuck HIGH or LOW, or reads erratically; other pins still work

Buttons and connectors that people touch are the main path for static into a circuit. A series resistor and a TVS diode at the connector (chapter 31) prevent most of these failures.

26 — Sensors

A sensor converts a physical quantity (temperature, light, distance, motion, pressure, current, gas) into an electrical signal. This chapter surveys the common families, how each one "sees" the world, and where each works well or misleads you.


26.1 How sensors deliver readings

Output Description Read with
Analog voltage A voltage proportional to the quantity ADC input
Resistive A resistance that changes (thermistor, LDR, FSR) A voltage divider + ADC (chapter 9)
Digital on/off A threshold output (PIR, reed switch, sensor modules with comparators) Digital input
Pulse / frequency A pulse width or frequency encodes the value (ultrasonic echo time, some humidity sensors) Timer input
Digital bus The sensor has its own ADC and sends numbers over I²C, SPI, UART, or 1-Wire The matching interface (chapter 30)

Modules vs bare sensors: breakout modules usually include a voltage regulator, pull-up resistors, and sometimes level shifting. Check whether a module's logic runs at 3.3 V or 5 V, and whether its pull-ups go to the voltage your microcontroller expects.


26.2 Temperature

Sensor Type Range Accuracy Notes
NTC thermistor Resistive −40 to ~125 °C ±0.5–2 °C (after calibration) Cheap, non-linear (chapter 9)
RTD (Pt100/Pt1000) Resistive −200 to 600 °C ±0.1–0.5 °C Accurate. Needs a converter (e.g. MAX31865)
Thermocouple (K, J, T types) Two dissimilar metals generate a small voltage (~41 µV/°C for type K) −200 to 1,250 °C+ ±1–2 °C Very high temperatures. Needs an amplifier with cold-junction compensation (MAX31855, MAX6675)
Analog IC (TMP36, LM35) Voltage ∝ temperature (10 mV/°C) −40 to 125 °C ±1–2 °C Simple analog output
DS18B20 Digital, 1-Wire bus −55 to 125 °C ±0.5 °C Many on one wire, each with a unique ID. Waterproof probe versions. Needs a 4.7 kΩ pull-up
Digital I²C (TMP117, MCP9808, LM75) Digital varies ±0.1–0.5 °C Precise
Environmental combos (BME280, SHT3x, AHT20, DHT22) Temperature + humidity (+ pressure) −40 to 85 °C ±0.3–1 °C See §26.3
IR thermometer (MLX90614), thermal arrays (AMG8833, MLX90640) Senses infrared radiation from a surface Non-contact ±0.5–2 °C Measures surface temperature at a distance. Shiny surfaces read wrong (low emissivity)
The chip's own diode Internal — Rough Many MCUs report their die temperature

⚠️ Self-heating: sensors mounted near a regulator, processor, or LED read warm. Put air temperature sensors away from heat sources, or on a short cable, and don't run them continuously at a high rate.


26.3 Humidity, pressure and air quality

Sensor Measures Interface Notes
DHT11 / DHT22 (AM2302) Temperature + humidity Proprietary single-wire Cheap. DHT11 is crude. Slow (1 reading every 1–2 s)
SHT3x/SHT4x, AHT20, HTU21D Temperature + humidity I²C More accurate and faster
BMP280 Temperature + pressure I²C/SPI Barometer and altitude. Not humidity (often confused with the BME280)
BME280 Temperature + humidity + pressure I²C/SPI Popular all-in-one
BME680 / BME688 + a gas (VOC) sensor I²C/SPI Air quality index
SCD30 / SCD40 / SCD41 True CO₂ (NDIR or photoacoustic) I²C Real CO₂ in ppm
SGP30 / SGP40, CCS811 VOCs, "equivalent CO₂" (estimated) I²C Estimated, not true CO₂
MQ-series (MQ-2, MQ-7, MQ-135…) Various gases Analog (heated element) Heater draws ~150 mA; needs burn-in and calibration. Rough indication only
PMS5003 / SDS011 Particulates (PM2.5, PM10) UART Laser particle counter with a fan

Pressure → altitude: air pressure falls about 12 Pa per meter near sea level. A good barometer detects height changes of under a meter, but weather changes pressure too.


26.4 Light and color

Sensor Notes
LDR (photoresistor) Cheap, slow, imprecise (chapter 9)
Photodiode / phototransistor Fast, analog (chapter 14)
BH1750, TSL2561/TSL2591, VEML7700 Digital lux meters, calibrated to human vision
TCS34725, APDS-9960 Color (RGB) sensing. The APDS-9960 also does proximity and gesture
UV sensors (VEML6070, GUVA-S12SD, LTR390) UV index

26.5 Distance and proximity

Ultrasonic ranging measures the time of an echo.
Ultrasonic ranging measures the time of an echo.
Sensor Principle Range Strengths Weaknesses
Ultrasonic (HC-SR04, JSN-SR04T) Times an ultrasonic echo (sound travels ~343 m/s) 2 cm–4 m Cheap, works on most solid surfaces, color-blind Soft or angled surfaces absorb or deflect sound; wide beam; affected by air temperature
IR triangulation (Sharp GP2Y0A series) Measures a reflected IR spot's angle 10–80 cm (varies by model) Simple analog output Non-linear, affected by surface color
Time-of-flight laser (VL53L0X, VL53L1X, VL6180X) Times the round trip of an invisible laser pulse Up to ~2–4 m Small, accurate, narrow beam Sunlight reduces range; dark or glossy surfaces; cover glass causes crosstalk
LiDAR modules (TF-Luna, TFmini) ToF, longer range Up to ~8–12 m Long range Cost
IR reflective (TCRT5000) Reflected IR intensity Millimeters–cm Line following, simple detection Color and ambient-light dependent
Capacitive proximity Field changes Short Senses through plastic Humidity affects it
Inductive proximity Coil field disturbed by metal mm–cm Detects metal only, very robust Metal only

26.6 Motion and presence

Sensor Principle Detects Notes
PIR (HC-SR501, AM312) Passive infrared: detects changes in heat pattern across a segmented Fresnel lens Moving warm bodies Cheap, low power. Can't detect a person sitting still. Warm-up period at power-on (~30–60 s)
Microwave Doppler (RCWL-0516) Radio waves reflected by moving objects Motion Sees through thin walls and plastic. Very sensitive
mmWave radar (e.g. LD2410, 24 GHz / 60 GHz modules) Radar that detects tiny motions, even breathing Presence, including stationary people Distance zones configurable. Can "see" through thin walls. Fans and curtains cause false detections
Break-beam (IR emitter + receiver) Beam interrupted Something passing Doorways, counters

26.7 Orientation and movement (IMUs)

Sensor Measures Examples
Accelerometer Acceleration, including gravity (1 g at rest, pointing down) → tilt, vibration, impacts, free fall ADXL345, LIS3DH, MMA8452
Gyroscope Rotation rate (degrees per second) L3GD20
Magnetometer Magnetic field → compass heading QMC5883L, LIS3MDL
IMU (6- or 9-axis) Combinations of the above MPU6050 (accel + gyro), ICM-20948, BNO055 / BNO085 (with on-chip sensor fusion outputting orientation directly)
The principle behind a MEMS accelerometer.
The principle behind a MEMS accelerometer.

26.8 Magnetic, position and rotation sensing


26.9 Current and voltage sensing

Method Examples Notes
Shunt resistor + amplifier INA219, INA226, INA260 (I²C, measure current, voltage, and power) Accurate DC measurement. Low-side or high-side
Hall-effect current sensor ACS712, ACS723, ACS758 Isolated. Works for AC and DC. Offset drift; measure the zero point
Current transformer (CT) SCT-013 clamp AC only. Non-invasive (clips around one wire of a cord, not both)
Voltage divider → ADC Resistors Simple DC voltage measurement (chapter 8)
Isolated AC voltage sensing ZMPT101B (small transformer), optocoupler Mains monitoring ⚠️

26.10 Force, weight and pressure


26.11 Liquids and environment

Sensor Notes
Resistive soil / water probes Corrode quickly if powered continuously. Power only during readings
Capacitive soil moisture No exposed metal, far longer life
Float switches Tank level on/off
Ultrasonic level sensing Distance to the liquid surface
Water flow sensors A turbine with a Hall sensor → pulses per liter
Rain sensors Resistive grid, or optical
pH, TDS, turbidity probes Analog, need calibration solutions

26.12 Location, ID and other sensors


26.13 Good practice with sensors

  1. Bring up one sensor at a time, and confirm it before adding the next.
  2. I²C scan first (chapter 30) to confirm the address.
  3. Check voltage and logic levels (3.3 V vs 5 V modules).
  4. Calibrate against a known reference: a thermometer, a tape measure, a known weight.
  5. Filter: average several readings, reject outliers, and add hysteresis to thresholds so readings near a limit don't flap.
  6. Mounting matters as much as the sensor: airflow, heat sources, vibration, line of sight, enclosure windows.
  7. Read the datasheet's timing: warm-up times, conversion times, and minimum intervals between readings.

26.14 Did you know?


26.15 Testing and diagnosis

Symptom Likely cause
Sensor not found on the bus Wiring, power, address, pull-ups, level mismatch (chapter 30)
Reads a constant or impossible value Not initialized, wrong register or driver, sensor damaged, wrong variant (BMP280 vs BME280)
Readings noisy Power supply noise, long analog wires, no filtering, nearby motors or radios
Readings drift slowly Self-heating, temperature effects, sensor warm-up, aging
Works on the bench, fails in the enclosure Heat buildup, blocked airflow or line of sight, cover window, electrical noise
PIR false triggers Heat sources, sunlight, drafts, power supply noise
Distance sensor wrong Target material or angle, sunlight, cross-talk between sensors, cover glass
Stuck after a microcontroller reset The sensor's own state wasn't reset. Re-initialize at startup, or power-cycle it
Load cell drifts Warm-up, temperature, mechanical creep, loose mounting

Meter checks: supply voltage at the sensor, analog output voltage changing with the stimulus, digital output pins switching, and bus lines idling HIGH.


26.16 How sensors fail

Failure Cause Symptom
Contaminated sensing element Silicone or solvent vapors, dust, smoke on humidity and gas sensors Readings drift or stick; slow response
Condensation Humidity sensor soaked by condensing moisture Reads ~100 % for hours; may carry an offset afterward (some datasheets give a drying/reconditioning procedure)
Gas sensor heater burned out Age, overvoltage on the heater Output stuck near zero; sensor stays cold
MEMS element damaged A drop onto a hard floor, ultrasonic cleaning (it can shake the tiny structures apart) Stuck axis, constant offset, or no response
Soldering damage Too much heat on humidity, pressure, or optical sensors Calibration offset, cracked window
Broken probe cable Flexing at the point where a waterproof probe's cable meets the housing Open circuit: impossible readings or "device not found"
Overloaded load cell Weight far above its rating, or a shock load Zero point permanently shifted; non-linear readings
Dirty or scratched optical window Dust, fingerprints, scratches on distance, light, or PIR lenses Short or wrong distances, reduced sensitivity
Demagnetized magnet Heat near a Hall sensor's magnet Weaker signal; switches trip late or not at all
Corroded contacts Outdoor or damp mounting without sealing Intermittent readings that worsen over time

💡 Some values are "error codes" in disguise. A DS18B20 temperature sensor reads 85 °C at power-up before its first conversion, so a steady 85 °C usually means a power or timing problem. Many software libraries report −127 °C when no sensor answers at all.

27 — Integrated circuits and digital logic

An integrated circuit (IC) is a complete circuit (from a handful of transistors to tens of billions) fabricated on a single piece of silicon and sealed in a package. This chapter covers how to identify and handle ICs, and the building blocks of digital logic: gates, flip-flops, shift registers, multiplexers, and buffers.


27.1 Packages

Package Description Pin spacing Hand-solderable?
DIP / DIL (dual in-line) Two rows of through-hole pins 2.54 mm (0.1") ✅ Fits breadboards
SIP A single row of pins 2.54 mm ✅
SOIC / SO Surface-mount, gull-wing leads on two sides 1.27 mm ✅ With practice
SSOP / TSSOP / MSOP Shrunk SOIC 0.5–0.65 mm ⚠️ Fine work
QFP / TQFP / LQFP Leads on all four sides 0.4–0.8 mm ⚠️ Drag soldering
QFN / DFN Leadless: pads underneath and on the edges, often a big thermal pad 0.4–0.65 mm ⚠️ Hot air or reflow
BGA Solder balls in a grid underneath 0.4–1.27 mm ❌ Needs reflow and inspection
SOT-23 / SOT-223 / SC-70 Small 3–8 pin packages 0.65–0.95 mm ✅
TO-92 / TO-220 Transistor-style packages (regulators, references) — ✅
PLCC Square, J-leads, often socketed 1.27 mm Socket

Finding pin 1

Pin 1 is marked by a notch at one end of the package, a dot or dimple near one corner, a bevelled edge, or a stripe. Viewed from the top, pins are numbered counter-clockwise starting at pin 1. (Viewed from underneath, as when working on the solder side of a board, they run clockwise. A common source of errors.)

DIP pin numbering from the top.
DIP pin numbering from the top.

Inserting a chip backwards usually swaps its power and ground, which often destroys it quickly and makes it hot.

Sockets and breakouts


27.2 Universal IC rules


27.3 Logic levels and families

Digital circuits represent 1 and 0 as voltage ranges. Different families define those ranges differently.

Family Supply Input HIGH ≥ Input LOW ≤ Notes
TTL (74xx, 74LS) 5 V 2.0 V 0.8 V Original bipolar logic. Power-hungry. Largely historic
CMOS 4000 series (CD40xx) 3–15 V (18 V max) 0.7 × VDD 0.3 × VDD Wide supply range, slow, low power
74HC 2–6 V ~0.7 × VCC (3.5 V at 5 V) ~0.3 × VCC Fast CMOS. At 5 V it won't reliably see 3.3 V as HIGH
74HCT / 74AHCT 5 V (4.5–5.5) 2.0 V (TTL levels) 0.8 V Accepts 3.3 V logic as HIGH and outputs 5 V: a simple 3.3 → 5 V level shifter
74AC / 74ACT 2–6 V / 5 V as HC / HCT Faster, stronger outputs
74LVC / 74LVX 1.65–3.6 V ~0.7 × VCC Inputs tolerate 5 V even when powered at 3.3 V: 5 → 3.3 V level shifting
74LV / AUP / others Low voltage Battery and portable devices

Part numbers follow the pattern [maker prefix] 74 [family] [function] [package], e.g. SN74AHCT125N = Texas Instruments, AHCT family, function 125 (quad buffer), N = DIP package. The function number means the same thing across families (a 74HC125 and a 74AHCT125 have the same pinout and logic).


27.4 Logic gates

Gate Output is HIGH when… Truth (inputs A, B → out) Common chip
NOT (inverter) Input is LOW 0 → 1, 1 → 0 74HC04 (hex inverter)
AND All inputs HIGH 00→0, 01→0, 10→0, 11→1 74HC08
OR Any input HIGH 00→0, 01→1, 10→1, 11→1 74HC32
NAND Not all inputs HIGH 00→1, 01→1, 10→1, 11→0 74HC00
NOR No input HIGH 00→1, 01→0, 10→0, 11→0 74HC02
XOR Inputs differ 00→0, 01→1, 10→1, 11→0 74HC86
XNOR Inputs match 00→1, 01→0, 10→0, 11→1 74HC266
Buffer Input is HIGH (copies it, with more drive) 0 → 0, 1 → 1 74HC125 / 74HC244
Gate symbols and truth tables.
Gate symbols and truth tables.

💡 NAND and NOR are "universal": any logic function can be built from NAND gates alone (or NOR gates alone). The Apollo Guidance Computer was built almost entirely from NOR gates.

Schmitt-trigger inputs

A Schmitt trigger has two thresholds: it switches HIGH at a higher voltage and LOW at a lower one (hysteresis). Slow or noisy signals, like debounced buttons, RC delays, and long cables, come out as clean, fast edges. Chips: 74HC14 (inverting), 74HC132 (NAND), 74LVC1G17 (buffer).


27.5 Beyond gates: common logic building blocks

Function What it does Common chips Typical use
Flip-flop (D-type) Stores one bit; captures its input on a clock edge 74HC74 Synchronizing signals, frequency division
Latch Stores bits; follows the input while enabled 74HC373/573 Holding data on a bus
Counter Counts clock pulses 74HC393, CD4017 (decade counter / "LED chaser"), CD4040, CD4060 (with oscillator) Timers, dividers, sequencers
Shift register, serial-in parallel-out Converts a serial stream into 8 parallel outputs 74HC595 Adding outputs to a microcontroller (LEDs, 7-segment) with 3 pins, chainable
Shift register, parallel-in serial-out Reads 8 inputs into a serial stream 74HC165 Adding many button inputs
Multiplexer / demultiplexer Routes one of several signals to one line (or vice versa) 74HC151, CD4051/74HC4051 (analog 8:1), 74HC4067 (16:1) Reading many analog sensors with one ADC
Decoder Turns a binary number into one active output 74HC138 (3-to-8) Chip selects, address decoding
Buffer / line driver (3-state) Drives signals with more current; outputs can be disabled (high-impedance) 74HC125/126, 74HC244/245 Sharing buses, level shifting (AHCT), driving long lines
Transceiver (bidirectional) Buffer that works in either direction 74HC245, 74LVC245 Data buses
Open-drain buffers Can only pull LOW 74HC07, 74LVC1G07 Wired-OR lines, level shifting
Analog switch Electronically controlled switch for analog or digital signals CD4066, 74HC4066 Switching audio or sensors
I/O expander Adds GPIO pins over I²C/SPI PCF8574, MCP23017 More pins for a microcontroller
Darlington / transistor array Drives higher-current loads ULN2003, ULN2803 Relays, steppers, lamps
LED driver Constant-current or multiplexed LED control MAX7219, TLC5940, PCA9685 (16-ch PWM) Displays, many LEDs or servos
A 74HC595 turning three microcontroller pins into eight outputs.
A 74HC595 turning three microcontroller pins into eight outputs.

Output types


27.6 Programmable logic


27.7 Did you know?


27.8 Testing and diagnosing ICs

A multimeter can't test an IC's function directly, but it can find most causes of failure:

Check How Good Bad
Power at the pins DC volts between the VCC and GND pins, on the chip itself Correct supply Missing or low supply is the most common "dead chip"
Orientation Pin 1 matches the board marking Aligned Backwards (often hot)
Output states DC volts on outputs Switch as expected Stuck HIGH/LOW = dead output, missing input, or the output held by something else
Inputs DC volts At defined levels Floating (between levels) = missing pull-up/down or a broken trace
Shorted pin Diode mode, red on GND, black on the pin (power off) ~0.4–0.7 V (the internal protection diode) ~0 V = pin shorted internally or on the board
Temperature Touch or thermometer Cool to warm Hot logic chip = shorted output, reversed, or overvoltage
Clock / activity Hz mode or oscilloscope Expected frequency No clock = the oscillator isn't running
Substitution Swap a socketed chip with a known-good one Works Confirms a bad chip

For logic, a logic probe or logic analyzer (chapter 3) shows activity that a meter can't.


27.9 How ICs fail

Failure Cause Symptom
Destroyed by reversal Chip inserted backwards, or supply reversed Very hot within seconds; often permanently dead
Output stage burned Output shorted to a rail, driving an LED without a resistor, two outputs fighting over one line One output dead or stuck; chip warm
Latch-up A signal applied to an input before the chip is powered, or a spike above the supply or below ground Chip suddenly draws large current and gets hot until power is removed; may be permanent
Static damage Handling without grounding, discharge into an exposed pin Dead, or a leaky input that loads the signal down
Overvoltage Supply above the absolute maximum (e.g. 5 V on a 3.3 V-only chip) Hot, dead, or subtly wrong afterward
Cracked joints or poor socket contact Thermal cycling, vibration, oxidized sockets Works intermittently; pressing on the chip changes behavior
Package cracked during reflow Moisture absorbed by the plastic turning to steam ("popcorning") Dead or intermittent after soldering

Problems that look like a failed chip but aren't:

Symptom Real cause
Erratic behavior, extra current, warm chip Floating unused CMOS inputs sitting halfway between levels
Random glitches Missing decoupling capacitor, noise, slow edges on non-Schmitt inputs
Wrong logic levels between chips Family mismatch (HC vs HCT) or 3.3 V vs 5 V (chapter 31)

28 — Analog ICs: op-amps, comparators, timers and references

Analog ICs handle continuously varying signals: amplifying a sensor's millivolts, comparing a voltage against a threshold, generating a timed pulse, or holding a precise reference voltage. This chapter covers the most useful ones: the op-amp, the comparator, the 555 timer, and voltage references.


28.1 The operational amplifier (op-amp)

What it is

An op-amp is a high-gain amplifier with two inputs and one output:

On its own it amplifies the difference between its inputs by an enormous amount (100,000× or more). That's far too much to use directly. Instead, negative feedback (connecting the output back to the − input through resistors) sets a precise, stable gain determined only by the resistors.

The two golden rules (with negative feedback)

  1. The output does whatever it takes to make the two inputs equal in voltage.
  2. The inputs draw (almost) no current.

With these two rules you can work out almost any op-amp circuit.

The classic circuits

Circuit Gain Description
Voltage follower (buffer) 1 Output tied to the − input, signal into +. Copies a voltage with high input impedance and strong output drive. Used to buffer voltage dividers and sensors
Non-inverting amplifier 1 + (Rf ÷ Rg) Signal into +. Feedback divider from the output to − (Rf) and from − to ground (Rg). Rf = 9 kΩ, Rg = 1 kΩ gives ×10
Inverting amplifier −(Rf ÷ Rin) Signal through Rin into −, and + to ground (or a mid-supply reference). Output inverted
Summing amplifier — Several inputs into − through resistors. Mixes signals (audio mixers)
Difference amplifier — Amplifies the difference between two signals. Used for current-sense shunts and bridges
Instrumentation amplifier — A precise difference amplifier (e.g. INA128, AD620) for strain gauges and medical signals
Integrator / differentiator — A capacitor in the feedback path. Filters, waveform shaping
Active filters — Low-pass, high-pass, band-pass with sharp responses (Sallen-Key, multiple-feedback)
Transimpedance amplifier — Converts a photodiode's tiny current into a voltage (resistor in the feedback path)
The three op-amp circuits you'll use most.
The three op-amp circuits you'll use most.

Key specs

Spec Meaning Watch for
Supply range e.g. 3–32 V single / ±1.5–16 V split Some need ≥ 5 V or more
Rail-to-rail input / output (RRIO) Can the inputs and output reach the supply rails? Older op-amps can't. The LM358's output only reaches ~1.5 V below its positive supply. On a 5 V supply it can't output 5 V
Gain-bandwidth product (GBW) Gain × frequency is roughly constant A 1 MHz GBW op-amp at gain 100 works to ~10 kHz
Slew rate How fast the output can change (V/µs) Limits large, fast signals
Input offset voltage A small built-in error Matters when amplifying tiny DC signals
Input bias current Current the inputs actually draw Matters with high-value resistors and sensors
Noise nV/√Hz Audio and precision
Output current Typically 10–40 mA Not a power amplifier

Common op-amps

Part Traits
LM358 / LM324 (dual / quad) Cheap, single-supply, inputs work down to ground. Not rail-to-rail output. Slow (~1 MHz)
TL072 / TL074 JFET inputs, low noise, audio favorite. Needs split or higher supplies. Inputs must not approach the negative rail
NE5532 Low-noise audio
MCP6002 / MCP6004 Rail-to-rail, 1.8–6 V, low power. Great for 3.3 V microcontroller circuits
OPA2340 / TLV2372 / TLV9002 Rail-to-rail, single supply
LM741 Historic classic. Obsolete for new designs (needs ±supplies, poor performance)
OPA series / AD8xx Precision and high-speed families

28.2 Comparators

A comparator compares two voltages and outputs HIGH or LOW depending on which is larger. It's essentially an op-amp designed to run without feedback and switch fast between its output states.

A noisy input with and without hysteresis.
A noisy input with and without hysteresis.

Common parts: LM393 (dual), LM339 (quad), TLV3201 and MCP6541 (push-pull, rail-to-rail). Many "sensor modules" (light, sound, soil moisture) are a sensor plus an LM393 with a sensitivity potentiometer.


28.3 The 555 timer

Introduced in 1972, the 555 is one of the most successful chips ever made. It generates precise timing pulses and oscillations with just a few resistors and capacitors.

Pins (DIP-8)

Pin Name Function
1 GND Ground
2 TRIG Starts a timing cycle when pulled below ⅓ VCC (output goes HIGH)
3 OUT Output. Sources/sinks ~100–200 mA (bipolar version)
4 RESET Active-low reset. Tie to VCC if unused
5 CTRL Access to the internal ⅔ VCC threshold. Usually a 10 nF capacitor to ground
6 THR Ends the HIGH phase when it rises above ⅔ VCC
7 DIS Discharge: shorts to ground to empty the timing capacitor
8 VCC Supply: 4.5–16 V (NE555); 2–15 V for CMOS versions

Modes

The classic 555 blinker.
The classic 555 blinker.

Uses: LED flashers, tone generators, PWM motor and LED dimmers, delays, missing-pulse detectors, sirens, the classic "Atari Punk Console" synthesizer.

Variants


28.4 Voltage references

A voltage reference provides a precise, stable voltage for ADCs, calibration, and regulator feedback, much more accurate than a regulator's output.

Part Type Notes
TL431 Adjustable shunt reference (2.5–36 V) Acts like a precise programmable Zener. It's in the feedback loop of almost every phone charger. Two resistors set the voltage: V = 2.5 × (1 + R1 ÷ R2)
LM4040 Shunt reference, fixed voltages Zener-like, precise
REF30xx, LM4050, MAX6xxx, ADR series Series references Low drift, low noise; output a fixed voltage like a small regulator
Zener diode Crude reference Temperature-sensitive, noisy (chapter 13)
Bandgap reference Inside most chips ~1.2 V, the basis of nearly every regulator and ADC

28.5 Other common analog ICs

Type Examples Use
Audio amplifiers LM386, PAM8403, TPA3116 Chapter 23
ADCs ADS1115 (16-bit, I²C), MCP3008 (10-bit, SPI), HX711 (24-bit load cell) Better analog inputs for microcontrollers
DACs MCP4725 (12-bit I²C), PCM5102 (audio I²S) Producing analog voltages or audio
Current-sense amplifiers INA219, INA226, INA180 Measuring current via shunts
Analog switches / multiplexers CD4066, CD4051, 74HC4051 Routing analog signals
Digital potentiometers MCP41xxx, X9C103 Software-controlled resistance
Voltage supervisors / reset ICs TPS3839, MCP100, APX803 Hold a processor in reset until the supply is stable
Function generators XR2206, AD9833 (DDS) Sine/square/triangle signal generation
Opto and isolation amplifiers — Measuring across isolation barriers

28.6 Did you know?


28.7 Testing and diagnosis

Symptom Likely cause
Op-amp output stuck at a rail No feedback (open loop), input outside the input range, wrong supply, oscillation, or simply amplifying an offset
Output won't reach full supply Not a rail-to-rail op-amp (e.g. LM358 on 5 V)
Output oscillates / hot op-amp Capacitive load, long feedback wiring, missing decoupling, unstable at low gain
Distortion on large signals Slew-rate limit, clipping at the rails, insufficient supply
Comparator output chatters No hysteresis, noisy input
Comparator output never goes HIGH Missing pull-up on an open-collector output
555 doesn't oscillate RESET not tied high, wrong capacitor, trigger/threshold wiring
555 frequency wrong Capacitor tolerance (electrolytics can be off by ±20 %), leakage, CMOS vs bipolar differences

Meter checks: supply pins; the DC voltages at the + and − inputs (with negative feedback, they should be equal); the output DC level; Hz/% mode on a 555 output.


28.8 How analog ICs fail

Failure Cause Symptom
Input damaged Inputs driven beyond the supply rails with no series resistor, static Output stuck at a rail, a large new offset, or an input that loads the signal
Input stage stressed by large differential voltage Using an op-amp with internal input-protection diodes as a comparator; the diodes conduct heavily Input current far higher than expected; gradual or sudden failure
Output burned Output shorted at high supply voltage for a long time (short-circuit protection limits current but the chip overheats) Hot chip; output dead or weak
Latch-up Signal present before the supply, or a spike past the rails, on CMOS parts Chip draws heavy current and heats up until power-cycled
Supply reversed or too high Wiring error, exceeding the maximum total supply (e.g. ±18 V parts on 40 V) Dead, often visibly cracked
555 output killed Driving a relay or motor without a flyback diode, or drawing more than the output rating (±225 mA absolute maximum for the NE555) Output stuck HIGH or LOW
Timing drift (not the chip) Electrolytic timing capacitor aging and losing capacitance 555 frequency creeps upward over the years
Voltage reference shifted Board flexing, soldering heat, long-term drift Every measurement off by the same small percentage

Op-amps rarely fail on their own. When one does, look for what reached its pins: a signal from outside the board, a missing supply at startup, or a load it couldn't drive.

29 — Microcontrollers and single-board computers

A microcontroller (MCU) is a complete small computer on one chip: processor, program memory, working memory, and peripherals (timers, analog inputs, serial ports) wired to physical pins. It's the "brain" of most modern gadgets. A single-board computer (SBC) like a Raspberry Pi is a full computer running an operating system. This chapter focuses on the electrical side: what the pins can and can't do.


29.1 Microcontroller vs single-board computer

Microcontroller Single-board computer
Examples Arduino (ATmega328P), ESP32, RP2040/RP2350 (Raspberry Pi Pico), STM32, nRF52, SAMD21, ATtiny Raspberry Pi 4/5, BeagleBone, Orange Pi
Runs One program ("firmware") directly on the hardware A full operating system (usually Linux)
Boot time Milliseconds Tens of seconds
Timing Real-time: precise, predictable Not real-time: the OS can delay your code
Power Microwatts (sleep) to under 1 W Several watts
Power loss Just restarts Should be shut down cleanly (SD card corruption risk)
Best for Sensors, control, timing, battery devices Networking, video, heavy computation, complex software

Many projects combine both: the SBC does the "thinking" and talks over USB or serial to an MCU that handles real-time I/O.


29.2 What's inside a microcontroller

Block Role
CPU core Executes instructions (AVR 8-bit, ARM Cortex-M, RISC-V, Xtensa)
Flash memory Stores the program. Survives power loss
RAM (SRAM) Working memory. Lost at power-off. Often small (2 KB–520 KB)
EEPROM / NVS Small persistent storage for settings
Clock Internal RC oscillator and/or external crystal (chapter 12)
GPIO General-purpose input/output pins
ADC / DAC Analog input / output
Timers / PWM Precise timing, PWM outputs, input capture
Communication peripherals UART, I²C, SPI, I²S, USB, CAN (chapter 30)
Radio (some) Wi-Fi, Bluetooth, Zigbee/Thread, LoRa
Watchdog timer Resets the chip if the program hangs
Brown-out detector Resets the chip when the supply dips too low
The main blocks inside a microcontroller.
The main blocks inside a microcontroller.

Dev boards

Development boards (Arduino Uno/Nano, ESP32 DevKit, Pico, etc.) add a USB connector, a USB-to-serial chip (CH340, CP2102, FT232) or native USB, a voltage regulator, reset and boot buttons, a status LED, and pin headers.


29.3 Logic levels

MCU family Logic voltage 5 V tolerant inputs?
ATmega328P (Arduino Uno/Nano) 5 V (also runs at 3.3 V) Yes, at 5 V supply
ESP32 / ESP8266 3.3 V No
RP2040 / RP2350 3.3 V No (RP2040)
STM32 3.3 V Many pins are ("FT" pins); check the datasheet
nRF52, SAMD21 3.3 V (or lower) No
Raspberry Pi GPIO 3.3 V No

29.4 GPIO pins: what they can do

As outputs

A GPIO output is a small push-pull transistor pair, and it can only supply a limited current:

Family Per-pin (recommended / absolute max) Total for the chip
ATmega328P 20 mA / 40 mA ~200 mA
ESP32 ~20 mA / 40 mA (configurable drive strength) Keep the total modest
RP2040 2–12 mA (configurable; 4 mA default) ~50 mA total
STM32 ~8–20 mA / 25 mA ~120 mA
Raspberry Pi ~16 mA / keep total under ~50 mA —
A simplified GPIO pin: output driver, pull-up, input buffer and clamp diodes.
A simplified GPIO pin: output driver, pull-up, input buffer and clamp diodes.

A GPIO can drive: an indicator LED (with resistor), a transistor base, a MOSFET gate, and logic inputs. It can't drive: motors, relays, speakers, buzzers (beyond tiny ones), LED strips, or anything needing more than a few tens of mA. Use a transistor, MOSFET, or driver chip (chapters 16, 17, 31).

The output voltage also sags under load. A pin supplying 20 mA may only reach ~2.8 V (on 3.3 V) or ~4.2 V (on 5 V).

As inputs

Pins with special jobs (the traps)

Always check the board's pinout and the chip's datasheet before assigning pins.


29.5 Analog input (ADC)

MCU Resolution Range Notes
ATmega328P 10-bit (0–1023) 0 to the reference (default = VCC) The reference is the supply, so a drooping supply shifts readings. Internal 1.1 V reference available
ESP32 12-bit ~0.1–3.1 V (with attenuation) Non-linear near the ends, noisy. Calibrate in software
RP2040 12-bit 0–3.3 V Fair. A few channels
STM32 12-bit 0–VREF Generally good

Tips:


29.6 PWM and timers


29.7 Programming and boot modes

Method How
USB bootloader + serial (Arduino, ESP32) The USB-serial chip toggles reset (and boot) lines automatically. If that fails: hold BOOT, tap RESET, release BOOT
UF2 drag-and-drop (RP2040, many SAMD/nRF boards) Hold BOOTSEL/BOOT while connecting (or double-tap reset). A USB drive appears, and you copy the firmware file onto it
SWD / JTAG A debug probe connected to dedicated pins. Programs and allows step-by-step debugging
ISP (AVR) A programmer on the SPI pins, for bare chips or for replacing bootloaders
OTA (over the air) Wi-Fi-capable chips update firmware over the network

Upload troubles are usually: a charge-only USB cable, a missing USB-serial driver, the wrong board/port/baud rate selected, something connected to the serial or boot pins, or the board needing a manual boot-mode entry or a power cycle.


29.8 Power and sleep

State Typical current (radio MCU)
Active with Wi-Fi transmitting 100–500 mA peaks
Active, CPU only 10–80 mA
Light sleep ~0.5–2 mA
Deep sleep ~5–150 µA (chip)

The chip's sleep current is not the board's. Dev boards often draw 1–20 mA even when the chip is in deep sleep, because of the voltage regulator's quiescent current, the USB-serial chip, and power LEDs. For battery projects, choose boards designed for low power, or remove LEDs and use low-I_q regulators.

Wake sources: timers, pin changes, touch, and sensor interrupts. Many chips keep a small RTC memory alive during deep sleep.

Radio bursts cause brownouts. Wi-Fi transmission spikes need a solid supply and bulk capacitance near the module (chapter 21).


29.9 Memory limits

Small microcontrollers have little RAM (the ATmega328P has only 2 KB). Running out doesn't produce an error message. It produces corruption and random crashes. Keep constant strings in flash (e.g. Arduino's F() macro), avoid large buffers, and watch memory reports at compile time.


29.10 Did you know?


29.11 Testing and diagnosis

Symptom Likely cause Check
Board completely dead No power, dead regulator, short Voltage on the 5V/VIN and 3V3 pins. 5 V present but 0 V on 3V3 = dead regulator
Powers up but no USB port appears Charge-only cable, missing driver, damaged USB chip, board in bootloader mode Try a known data cable; check the device manager
Won't upload Wrong port or board, boot pins, a device on the serial pins, needs manual boot mode Disconnect peripherals; use the boot button
Random resets Brownout (radio bursts, motors, LEDs), watchdog, stack overflow Measure the supply during the event; add capacitance; check memory use
Won't boot after wiring something new Strapping pin pulled the wrong way Disconnect the new wiring; move it to another pin
Pin doesn't work Input-only pin, reserved pin, wrong pin numbering (GPIO number vs board label vs physical pin) Check the pinout
Analog readings wrong Reference voltage, ADC non-linearity, high source impedance, radio conflict Calibrate against a meter
Serial output is garbage Baud rate mismatch Match the monitor to the code
Chip gets hot Short on an output, over-voltage on a pin, reversed power Power off; inspect
Peripheral works alone, not with others Pin conflicts, shared timers, power limits Add parts one at a time

Meter checks: supply pins (5V, 3V3, GND), reset/enable pin level (it should be high when running), GPIO outputs switching, and current draw (active vs sleep).


29.12 How microcontrollers fail

Failure Cause Symptom
Single GPIO pin dead 5 V on a pin that isn't 5 V-tolerant, output shorted to a rail, an LED or motor with no current limit, static That pin is stuck or reads wrong; the diode test shows a short or leak to GND; the rest of the chip works (move to another pin)
Whole chip dead or hot Reversed power, overvoltage on the supply, 5 V fed into a 3.3 V pin Board draws heavy current; chip hot to the touch
On-board regulator dead Too much load on the 3V3 pin, too high a VIN, a short downstream 5 V present but no 3.3 V; board otherwise looks fine
USB connector or USB-serial chip damaged Connector levered off its pads, static, a faulty cable or charger No serial port appears; board may still run from other power
Flash or EEPROM worn out Writing settings in a loop (typical endurance 10,000–100,000 writes per cell) Saved settings lost or corrupted; program still runs
Corrupted storage Power removed during a write (common with SD cards on single-board computers) Won't boot; file system errors
"Bricked" by configuration Fuse or option bits set wrongly (e.g. clock source set to a crystal that isn't fitted), one-time eFuses burned Chip seems dead and won't program; often recoverable with a special programmer or by supplying the expected clock
Clock failure Cracked crystal, wrong load capacitors (chapter 12) Won't start, or runs only on its internal oscillator

Most "dead microcontroller" boards turn out to be a dead regulator, a charge-only cable, or a configuration problem. The chip itself is usually the last suspect.

30 — Communication interfaces

Chips and modules talk to each other over a handful of standard interfaces (buses). Each is a set of wires plus rules about what the voltages mean and when. Most "module not working" problems come down to one of a few mistakes per bus, which this chapter lists.


30.1 Concepts that apply to every bus

Differential signalling cancels noise that hits both wires.
Differential signalling cancels noise that hits both wires.

30.2 Summary table

Interface Wires (plus GND) Clock? Topology Typical speed Typical distance
UART (TTL serial) TX, RX No (baud) Point to point 9,600–1,000,000+ baud < ~1–2 m
RS-232 TX, RX (+ handshake) No Point to point up to ~115 kbaud ~15 m
RS-485 A, B (differential pair) No Multi-drop bus (32+ devices) up to 10 Mbit/s Up to 1,200 m
I²C SDA, SCL Yes Bus, addressed (up to ~100+ devices) 100 k / 400 k / 1 Mbit/s < ~1 m (on-board)
SPI SCK, MOSI, MISO, CS per device Yes Bus with chip-selects 1–80+ Mbit/s Short (on-board)
I²S BCLK, LRCLK/WS, DATA (+ MCLK) Yes Point to point Audio rates (MHz clocks) Short
1-Wire DQ (data + power) No (timed) Bus with 64-bit IDs ~16 kbit/s Tens of meters (with care)
CAN CANH, CANL (differential) No Multi-drop bus with priority 125 k–1 Mbit/s (CAN FD faster) ~40 m at 1 Mbit/s, longer at lower speed
USB D+, D− (+ VBUS, and CC on USB-C) Embedded Host with hubs 1.5 Mbit/s–40 Gbit/s 3–5 m
Ethernet 2 or 4 twisted pairs Embedded Switched network 10 M–10 Gbit/s 100 m
PS/2 CLK, DATA Yes Point to point ~10–17 kHz Short
LVDS / HDMI / DisplayPort Differential pairs Yes Point to point Hundreds of Mbit/s to Gbit/s per pair Short to a few m

30.3 UART (serial)

UART wiring, and one byte on the wire.
UART wiring, and one byte on the wire.

RS-232

The original PC serial standard uses ±3 to ±15 V (inverted: negative = 1). ⚠️ Never connect RS-232 directly to a microcontroller pin. Use a converter such as the MAX3232. Common on DB9 connectors in older and industrial equipment.

RS-485

Differential, multi-drop, long-distance serial, used industrially (Modbus, DMX lighting). Transceivers like the MAX485 convert UART to RS-485. Terminate the two ends of the bus with 120 Ω resistors, and use twisted pair.


30.4 I²C (Inter-Integrated Circuit)

An I²C bus with pull-ups and three addressed devices.
An I²C bus with pull-ups and three addressed devices.

Typical addresses

Device Address
SSD1306 / SH1106 OLED 0x3C / 0x3D
PCF8574 LCD backpack 0x27 (PCF8574A: 0x3F)
BME280 / BMP280 0x76 / 0x77
MPU6050 0x68 / 0x69
DS3231 RTC 0x68
ADS1115 0x48–0x4B
BH1750 0x23 / 0x5C
VL53L0X 0x29
INA219 0x40–0x4F
PCA9685 0x40 (+ others)

7-bit vs 8-bit notation: some datasheets quote the address shifted left with the read/write bit included (e.g. 0xD0 for a 7-bit 0x68). If a datasheet address doesn't work, try half of it.

Troubleshooting I²C

  1. Run an I²C scanner sketch. It lists every responding address.
  2. SDA and SCL should idle HIGH (~3.3 V or 5 V). 0 V means a missing pull-up or a device holding the bus low.
  3. Check for swapped SDA/SCL, power, and ground.
  4. Too many pull-ups: every breakout board adds its own. Many in parallel can be too strong for weak devices. Remove extras.
  5. Level mismatch: 5 V modules pulling the lines up to 5 V on a 3.3 V bus (chapter 31).
  6. Bus too long or too capacitive: lower the speed, use stronger pull-ups, or use bus extenders (P82B715) or differential I²C.
  7. A hung bus (SDA stuck low after a reset mid-transaction) can often be freed by toggling SCL nine times.

30.5 SPI (Serial Peripheral Interface)

Signal Also called Direction
SCK SCLK, CLK Controller → peripheral clock
MOSI COPI, SDI, DIN, SDA (on some displays!) Controller → peripheral data
MISO CIPO, SDO, DOUT Peripheral → controller data
CS SS, CE, NSS Chip select, active LOW, one per device
An SPI bus with two devices.
An SPI bus with two devices.

30.6 I²S (Inter-IC Sound)


30.7 1-Wire


30.8 CAN bus


30.9 USB


30.10 Other wired interfaces

Interface Notes
PS/2 Legacy keyboard/mouse. Open-collector CLK and DATA with pull-ups. The device generates the clock (10–17 kHz)
MIDI Musical instruments. 31,250 baud serial over a current loop, opto-isolated at the receiver
DMX512 Stage lighting. RS-485 at 250 kbaud
SDIO / SD (SPI mode) Memory cards
JTAG / SWD Chip programming and debugging
LVDS / eDP / MIPI DSI & CSI Displays and cameras (chapter 24)
HDMI / DisplayPort Video. They also carry an I²C channel (DDC) that reads the monitor's EDID identification
Ethernet Networking. Modules like the W5500 (SPI) or ENC28J60 add it to MCUs. PoE delivers power over the same cable

30.11 Wireless interfaces

Technology Frequency Range (typical) Data rate Power Use
Wi-Fi (802.11) 2.4 / 5 / 6 GHz 30–50 m indoors Mbit/s–Gbit/s High Internet, networks
Bluetooth Classic 2.4 GHz ~10 m ~2–3 Mbit/s Medium Audio, serial links
Bluetooth Low Energy (BLE) 2.4 GHz 10–50 m+ ~1–2 Mbit/s Very low Wearables, sensors, beacons
Zigbee / Thread (802.15.4) 2.4 GHz 10–30 m (mesh extends it) 250 kbit/s Low Smart-home mesh networks
ESP-NOW (Espressif) 2.4 GHz Up to ~100 m+ Small packets Low Direct device-to-device, no router
LoRa / LoRaWAN 433 / 868 / 915 MHz Kilometers 0.3–50 kbit/s Very low Long-range sensors
Sub-GHz ASK/OOK (433/315 MHz) 433 MHz 10–100 m Low Low Remote sockets, doorbells, weather stations
nRF24L01 2.4 GHz 10–100 m+ up to 2 Mbit/s Low Simple radio links
NFC / RFID 13.56 MHz / 125 kHz cm Low The reader powers the tag Payments, access cards
Infrared Light, ~38 kHz modulated Line of sight, ~10 m Low Low TV remotes
Cellular (LTE-M, NB-IoT, 4G) Various Kilometers Varies Medium–high Remote devices

Antenna tips: keep a module's antenna clear of metal, batteries, and ground planes; orient it sensibly; and use an external antenna (via U.FL/SMA) for range. Radio transmit bursts draw large current spikes (chapter 21).


30.12 Did you know?


30.13 Testing and diagnosis

Check How
Idle levels UART TX idles HIGH. I²C SDA/SCL idle HIGH. SPI CS idles HIGH. A line stuck LOW means something is holding it
Continuity Every wire from pin to pin, power off
Activity Meter Hz mode on a clock line shows it's running. A logic probe shows pulsing
Decode A logic analyzer (with protocol decoders) shows the actual bytes: the single most useful tool for bus problems
Isolation Test the device alone, then add others one at a time

The universal "device not responding" checklist

  1. Power at the device (measured at its pins).
  2. Common ground.
  3. Wires crossed correctly (UART), not swapped (I²C), correct direction (SPI).
  4. Code uses the pins actually wired.
  5. Address (I²C) or chip select (SPI) correct.
  6. Baud rate (UART) matches.
  7. Pull-ups present (I²C, 1-Wire), and not too many.
  8. Logic levels compatible.
  9. Mode switches or jumpers on the module set correctly (before power-up).
  10. Bus length, speed, and termination suitable.

30.14 How interfaces fail

Failure Cause Symptom
Transceiver blown (RS-485, CAN, RS-232) Ground-potential differences between distant equipment, surges or lightning on outdoor runs, a data line wired to power Node dead, or it drags the whole bus down; the bus lines show low resistance to ground
Bus pin damaged by static Discharge into an exposed connector with no ESD protection That port stuck HIGH or LOW; other buses still work
I²C bus stuck LOW A device reset in the middle of a transfer keeps holding SDA low Every transaction fails until power-cycled, or until 9 clock pulses on SCL free it
Broken conductor inside a cable Flexing, strain at the plug Works until the cable moves; continuity test fails when wiggled
Worn or loose connector Repeated plugging (especially micro-USB), levered joints Connection drops when touched
Corroded contacts Outdoor or damp locations, no sealing Errors that rise over weeks; green deposits on pins
USB port shut down Device drew too much current; the host's current limit or polyfuse tripped Port stops working until unplugged, or until the host reboots
Radio output stage damaged Transmitting with no antenna or the wrong one (on higher-power modules), static on the antenna pin Range drops to a few meters; module otherwise works

31 — Interfacing and level shifting

Interfacing means connecting things that don't naturally agree: a 3.3 V microcontroller and a 5 V sensor, a logic pin and a 12 V motor, a microcontroller and a mains-powered appliance. This chapter collects the standard techniques in one place.


31.1 Connecting different logic voltages

The two directions

Direction Risk Typical solution
5 V output → 3.3 V input Damage. Current flows through the input's protection diode into the 3.3 V rail Divide, clamp, or buffer down
3.3 V output → 5 V input Unreliable. 3.3 V may fall below the 5 V input's HIGH threshold Buffer up (HCT/AHCT logic) or a MOSFET shifter

Check the receiving chip's V_IH (minimum input HIGH) in its datasheet. Many 5 V chips accept ≥ 2.0 V (TTL levels) and are fine with 3.3 V. CMOS-level parts (74HC, WS2812 LEDs) may need ≥ 3.5 V.

Level-shifting methods

Method Direction Speed Best for
Resistor divider (e.g. 1 kΩ + 2 kΩ) 5 V → 3.3 V only Moderate (slows edges) A single input: UART RX from a 5 V device, sensor outputs
Series resistor (1–10 kΩ) 5 V → 3.3 V Fair Quick fix relying on the input's clamp diode to limit current. Not ideal, but common
74LVC-family buffer (powered at 3.3 V, 5 V-tolerant inputs) 5 V → 3.3 V Fast Several lines down
74HCT / 74AHCT buffer (powered at 5 V) 3.3 V → 5 V Fast Addressable LED data, driving 5 V logic
BSS138 MOSFET bidirectional shifter (the common 4-channel module) Both Moderate (~up to 400 kHz–a few MHz) I²C and other open-drain lines
TXS0108E / TXB0108 (auto-direction translators) Both Fast Mixed buses. Can be finicky with pull-ups and long wires
Dedicated translators (TXU, SN74LVC1T45 with a DIR pin) Both (direction-controlled) Fast Push-pull buses such as SPI
Open-drain + pull-up to the receiver's voltage Both Moderate If the device only pulls low and has no pull-ups of its own, pull up to the lower voltage
Optocoupler Either, isolated Slow–moderate When isolation is needed too
A resistor divider for 5 V → 3.3 V, and a bidirectional MOSFET shifter.
A resistor divider for 5 V → 3.3 V, and a bidirectional MOSFET shifter.

💡 Choose the shifter for the bus type. One-way buffers (HCT/AHCT) are wrong for I²C or PS/2, where both ends drive the line. MOSFET bidirectional shifters are too slow and weak for fast one-way signals like LED data or fast SPI.


31.2 Driving loads from a logic pin

A GPIO provides a few milliamps at 3.3 V or 5 V. For anything more:

Load Driver Notes
Indicator LED Direct, with a resistor ≤ ~10 mA
Several LEDs / small loads (< ~300 mA) NPN transistor (2N2222, S8050) Base resistor ~1 kΩ. Chapter 16
Larger DC loads (LED strips, heaters, pumps) Logic-level N-MOSFET (AO3400, IRLZ44N) Gate resistor + pull-down. Chapter 17
High-side switching P-MOSFET + small NPN, or a high-side switch IC Chapter 17
Relays Transistor + flyback diode, or a relay module Chapter 6
DC motors (bidirectional) H-bridge driver IC Chapter 22
Steppers Stepper driver Chapter 22
Many outputs Shift registers (74HC595), I/O expanders, ULN2803 Chapter 27
Servos Signal pin direct (3.3 V usually works), separate power Chapter 22
Mains loads Relay module, SSR, or optotriac + TRIAC Chapter 18 ⚠️

Always connect the grounds of the logic and load supplies (unless the driver is isolated), and add a flyback diode to every inductive load.


31.3 Reading external signals

Signal Method
Switch or button Pull-up/pull-down + debounce (chapter 25)
5 V logic into a 3.3 V MCU Divider or level shifter (§31.1)
12 V / 24 V digital signal (industrial sensor, car signal) Divider with a clamp (Zener or the MCU's diode + series resistor), or better, an optocoupler
Analog voltage above the ADC range Voltage divider (chapter 8), plus a buffer op-amp for high-impedance sources
Small analog signal (mV) Op-amp amplifier, instrumentation amp, or an external high-resolution ADC (chapter 28)
Current Shunt + amplifier, or a Hall sensor (chapter 26)
Mains presence (is it on?) Optocoupler with a suitable resistor, or an isolated detection module ⚠️
Open-collector sensor outputs (Hall switches, many industrial sensors) Pull-up resistor to the MCU's logic voltage
Long cables Lower-value pull-ups, RC filtering, Schmitt-trigger inputs, TVS protection, or differential signalling (RS-485)

31.4 Isolation

Galvanic isolation means no direct electrical connection between two circuits, while signals or power still cross the gap by light, magnetism, or capacitance.

Why isolate:

Isolator Crosses the gap by Use
Optocoupler Light Digital signals, feedback, low speed
Digital isolator ICs (ISO77xx, ADuM series, Si86xx) Capacitive or magnetic coupling Fast data (I²C, SPI, UART)
Isolated DC-DC converter (B0505S and similar modules) Transformer Powering the isolated side
Transformer Magnetism Power, audio, Ethernet
Relay Mechanical Switching loads
Fiber optics / radio Light / radio Complete separation

Remember that the isolated side needs its own power: an isolated DC-DC module, a battery, or a separate supply.


31.5 Protecting inputs

Inputs that connect to the outside world (long wires, connectors, other equipment) need protection:


31.6 Did you know?


31.7 Testing and diagnosis

Meter and scope checks:

Symptom Likely cause
5 V device's output reads fine, but the 3.3 V MCU behaves oddly or gets warm Overvoltage through the input clamp. Shift down
Device works "sometimes" with 3.3 V signals Marginal HIGH level. Shift up (HCT/AHCT)
I²C fails through a level shifter Wrong shifter type (unidirectional), missing pull-ups on one side, too slow for the speed
LED strip data unreliable through a shifter MOSFET bidirectional shifter too slow. Use a 74AHCT125/HCT245
Load doesn't switch No common ground, a non-logic-level MOSFET, missing base resistor current, relay module input polarity (many are active-low)
Transistor or MOSFET dies when a relay or motor switches off Missing flyback diode
MCU resets when a load switches Shared supply sagging, ground bounce. Separate supplies, bulk capacitance
Noise on readings from long cables Pull-ups too weak, no filtering, ground loop. Isolate or use differential signalling

31.8 How interface parts fail

Failure Cause Symptom
Input pin damaged by clamp current A higher-voltage signal pushed through the input's protection diode for long periods Pin leaky or stuck; the lower-voltage chip runs warm
Back-powering Signals applied while the receiving chip is unpowered, feeding its supply through the input diodes Chip half-runs when it should be off; won't reset properly; can be damaged
Level-shifter channel dead Static, overvoltage on one side One line stuck HIGH or never pulled up
Optocoupler weakened The LED inside dims with age, especially at high current and temperature Signals that once worked become marginal over years
TVS diode shorted Absorbed a surge larger than its rating (it fails shorted, protecting what's behind it) Line stuck at 0 V; diode reads ~0 Ω both ways
Series resistor burned open A fault voltage on a long cable Input floats; readings random
Isolated DC-DC module failed Overload, short on the isolated side Everything on the isolated side dead
Driver transistor dead Relay or motor switched with no flyback diode Load stuck on or never switches

32 — Soldering and prototyping

A circuit is only as reliable as its connections. This chapter covers the tools and techniques for building circuits: solderless breadboards for experiments, perfboard and stripboard for permanent one-offs, printed circuit boards for anything repeatable, and the soldering skills that hold it all together.


32.1 Solderless breadboards

A breadboard is a plastic block of spring-clip contacts on a 2.54 mm (0.1") grid.

Which breadboard holes are connected.
Which breadboard holes are connected.

32.2 Permanent prototyping boards

Type Description Best for
Perfboard (pad-per-hole) Holes with isolated copper pads Free-form layouts, wiring with bare wire or solder bridges
Stripboard (Veroboard) Parallel copper strips along the rows Circuits laid out like a breadboard. Cut strips with a drill bit or cutter where needed
Breadboard-layout PCBs Copper matching a solderless breadboard's pattern Moving a breadboard design to solder with no redesign
Double-sided plated-through boards Pads on both sides, connected through holes Stronger joints, more flexible routing
Dead-bug / Manhattan style Parts glued upside-down or on small pads over a copper ground plane RF and analog circuits
Wire-wrap Thin wire wrapped around square posts Historic, dense digital prototypes

32.3 Printed circuit boards (PCBs)


32.4 Soldering: tools and materials

The iron

Solder

Type Melting point Notes
63/37 tin-lead (eutectic) 183 °C Melts and freezes at once: the easiest to use
60/40 tin-lead 183–190 °C Very common, slightly pasty range
Lead-free (SAC305: tin-silver-copper) ~217–220 °C Required in commercial products (RoHS). Hotter, duller finish, a little harder to work
Diameter 0.5–1.0 mm 0.6–0.8 mm suits most hobby work

Rosin/flux core solder contains flux inside. ⚠️ Wash your hands after handling leaded solder, and don't eat at the bench.

Flux

Flux cleans oxide off metal surfaces so solder can wet and flow. The core flux often isn't enough for rework, SMD, or old parts. Extra flux (paste, gel, or pen) solves most "solder won't stick" problems.

Other tools

Solder wick (desoldering braid), a desoldering pump ("solder sucker"), flush cutters, tweezers, a PCB holder or helping hands, magnification, a fume extractor or fan, isopropyl alcohol and a brush, and heat-shrink with a heat gun. For SMD work: a hot-air station, solder paste, and possibly a hot plate.


32.5 How to make a good joint (through-hole)

  1. Clean and prepare: fresh pads and component leads (old parts may need extra flux).
  2. Heat the joint, not the solder: touch the iron tip to both the pad and the lead at once.
  3. Feed solder into the joint (not onto the iron) after 1–2 seconds. It should flow around the lead and across the pad.
  4. Remove the solder, then the iron. Total time ~2–4 seconds.
  5. Don't move the part while the solder freezes.
  6. Trim the lead above the joint.

What joints should look like

Good and bad through-hole joints.
Good and bad through-hole joints.
Joint Appearance Cause
Good Shiny (leaded) or satin (lead-free), smooth concave "volcano" shape, wetting both pad and lead —
Cold joint Dull, grainy, lumpy, or balled up Not enough heat, or movement while cooling
Disturbed joint Frosted, cracked appearance Movement during cooling
Insufficient solder Pad not fully covered, lead not surrounded Too little solder
Excess solder A big blob hiding the lead outline Too much solder
Solder bridge Solder connecting adjacent pads Too much solder, poor technique. Remove with wick and flux
Non-wetted pad or lead Solder beads up and won't stick Oxidation, contamination, or too little heat. Add flux
Lifted pad Copper pad torn from the board Too much heat or force
Overheated Burnt flux, discolored board Too hot or too long

32.6 Surface-mount basics


32.7 Desoldering


32.8 Wiring and finishing


32.9 ESD and handling


32.10 Did you know?


32.11 Diagnosing construction faults

Symptom Likely cause Check
Works on the breadboard, not on perfboard Wiring error, solder bridge, cut strips missing on stripboard Continuity check every connection against the schematic
Intermittent Cold joint, cracked joint, loose breadboard contact Wiggle and tap test; reflow suspect joints
Short between adjacent pins Solder bridge, stray strands, flux debris Magnifier; continuity between neighbors
Part hot after assembly Backwards component, bridge, wrong value Orientation; values
Circuit fine, then fails when handled Mechanical stress on joints Strain relief; reflow
Noise or instability Long wires, missing decoupling, breadboard capacitance Shorter wires; decoupling caps
Lifted pad or broken trace Rework damage Repair with a jumper wire

Tip: before powering a newly assembled board, check for a short between the power rail and ground with continuity or resistance. Then power it with a current-limited supply if you have one.

33 — Safety

Most hobby electronics runs at low voltages that can't hurt you. But hazards appear quickly: mains wiring, charged capacitors, lithium batteries, hot irons, solder fumes, lasers. Good habits formed on harmless circuits are what protect you the day you work on one that isn't.


33.1 Electric shock: what actually hurts

Current through the body causes harm, and voltage is what drives that current through your skin's resistance. Dry skin might be 100,000 Ω or more. Wet or broken skin can be under 1,000 Ω.

Approximate effects of 50/60 Hz AC through the body (hand to hand or hand to foot):

Current Effect
~1 mA Barely perceptible tingle
~5 mA Uncomfortable. The GFCI trip threshold in North America
10–20 mA "Can't let go": muscles contract and you may be unable to release the conductor
30 mA The RCD trip threshold in many countries. Breathing may be affected
50–100 mA Ventricular fibrillation possible: the heart stops pumping effectively. Potentially fatal
> 1 A Severe burns, cardiac arrest
Approximate effects of current through the body.
Approximate effects of current through the body.

Hand-to-hand current passes through the chest. Hence the "one hand" rule for work on live high-voltage circuits: keep the other hand away from the circuit (in your pocket or behind your back).

Voltage thresholds


33.2 Working near mains

⚠️ If you're not trained and comfortable, use pre-built, certified modules (enclosed power supplies, relay modules with proper spacing, smart plugs) and keep your own work on the low-voltage side.

If you must:

  1. Unplug it. Don't rely on a switch. Verify dead with a meter or a non-contact tester, and test the tester on a known live circuit first.
  2. Isolate: use an isolation transformer for bench work on mains-powered equipment, and a GFCI/RCD outlet.
  3. Enclose everything: no exposed mains terminals. Use proper strain relief and grommets.
  4. Earth metal enclosures with the ground conductor.
  5. Maintain creepage and clearance (spacing between mains and low-voltage parts: several millimeters minimum).
  6. Fuse the live conductor.
  7. Use appropriately rated wire, connectors, and switches.
  8. Follow local electrical codes. Some work legally requires a licensed electrician.

Hidden dangers in mains equipment


33.3 Capacitors


33.4 Batteries


33.5 Heat and fire


33.6 Chemicals and fumes


33.7 Eyes and lasers


33.8 Mechanical hazards


33.9 Static (protecting the parts)

Static discharge rarely hurts people but easily kills semiconductors (chapter 32). Ground yourself before handling sensitive parts.


33.10 Safe habits

  1. Assume it's live until you've measured it.
  2. Power off before changing wiring.
  3. Use a current-limited bench supply for first power-up.
  4. Check polarity before connecting batteries and supplies.
  5. One hand near live circuits above ~50 V.
  6. Keep the bench dry and tidy. No drinks near live circuits.
  7. Know where the off switch or plug is, and keep it reachable.
  8. Use proper meter ratings (CAT rating) and intact test leads.
  9. Don't work alone on mains or high-energy systems.
  10. If something smells hot, crackles, or smokes: power off first, investigate second.

33.11 Did you know?

34 — Troubleshooting and diagnosis

Every circuit eventually misbehaves. Troubleshooting is a skill: a method for narrowing down where the problem is, then what it is. This chapter collects the approach, the techniques, and quick-reference tables of symptoms and component failure modes.


34.1 The method

  1. Define the symptom precisely. "Doesn't work" isn't a symptom. "The LED lights, but the display stays blank, and it worked yesterday before I added the sensor" is.
  2. Know what "right" looks like. Have the schematic, expected voltages, and expected behavior. Measurements only mean something against expectations.
  3. Check the obvious first: power switched on, battery charged, cable plugged in, fuse intact, correct code uploaded.
  4. Power, then ground, then signals. Most faults are power problems.
  5. Divide and conquer (half-splitting): test at the midpoint of the signal or power path. Good there? The fault is downstream. Bad? Upstream. Repeat.
  6. Change one thing at a time, and re-test after each change.
  7. Substitute known-good parts: a different cable, supply, module, or board. It's the fastest way to separate "this part is bad" from "this setup is wrong."
  8. Think about what changed. New wiring, new code, a move, humidity, a dropped board.
  9. Suspect your tools and references too: meter fuse and battery, probe connections, datasheets for the wrong variant, mislabelled pinouts.
  10. Stop and step back when repeated attempts fail. Re-read the schematic, re-check assumptions, or explain the problem to someone (or write it down). The act of explaining often reveals the gap.
  11. Keep notes: measurements, what you tried, what changed. It prevents going in circles.
Half-splitting a chain of stages.
Half-splitting a chain of stages.

34.2 Techniques

Technique How Finds
Visual inspection Magnifier and bright light: burnt parts, bulging caps, cracked joints, bridges, swapped parts, reversed polarity A large share of faults, before touching a meter
Smell Burnt electronics have a distinctive smell Overheated components
Touch / thermal check Carefully feel for hot parts, or use a thermal camera or IR thermometer Shorts, overloaded parts, failing regulators
Voltage survey Measure every power rail and key node under power Missing supplies, regulator failures, brownouts
Voltage-drop test Voltage across a connection or switch while current flows Bad contacts, corroded connectors, undersized wire
Continuity / resistance Power off: check paths and look for shorts Broken wires, cracked traces, bridges
Current measurement Compare supply current with expected Shorts (too much), dead sections (too little)
Wiggle / tap test Flex cables, tap boards, press on chips while monitoring Intermittent connections
Freeze / heat test Cold spray or a hair dryer on suspect parts Temperature-sensitive faults
Signal tracing Follow a signal through each stage with a scope, logic probe, or audio probe Where a signal disappears
Signal injection Inject a known signal at a stage and check the output Which stage fails
Comparison Compare readings with an identical working unit Differences point at the fault
Simplify Strip the circuit down to minimal parts, then add back one at a time Interactions, conflicts
Current-limited power-up Bench supply with a low current limit Protects a faulty board during diagnosis

34.3 Symptom guide

Nothing works at all

Check Likely finding
Supply voltage at the source Dead supply, flat battery, switch off
Fuse / polyfuse Blown (why? look for a short)
Voltage at the board's power input Broken cable, bad connector, reversed polarity
Regulator input vs output Dead regulator (input present, output missing)
Short between rail and ground (power off) Shorted capacitor, solder bridge, failed chip
Enable/reset pins Held in reset, enable pin low
A quick path for a completely dead circuit.
A quick path for a completely dead circuit.

Works intermittently

Resets, freezes or crashes randomly

  1. Brownout: measure the supply at the chip during the event.
  2. Missing decoupling capacitors.
  3. Noise from motors, relays, or switching supplies coupling in.
  4. Watchdog resets (a code hang).
  5. Memory exhaustion on small microcontrollers.
  6. Overheating.

Something gets hot

Hot part Likely reason
Linear regulator Too big a voltage drop × current. Use a switching regulator
Transistor Not fully on (base/gate drive too low), overloaded
MOSFET Not logic-level, switching too slowly, no heatsink
Resistor Overloaded, or a short downstream
Chip Reversed, output shorted, overvoltage
Capacitor Reversed, over-voltage, high ripple current
Wire / connector Undersized, poor connection
Motor / driver Stalled, overloaded, current set too high

Outputs don't do anything

Inputs misread

Communication failures

See chapter 30's checklist: power, ground, wiring direction, address, baud, pull-ups, logic levels, speed, one device at a time.

Noise, hum, interference


34.4 Component failure modes at a glance

Component Usual failure Symptom Test
Resistor Open, or value drift Dead section, wrong levels Ω (lift a leg)
Potentiometer Worn or dirty track Crackling, jumps Ω while turning
Electrolytic capacitor Dried out (high ESR), bulged, shorted Ripple, hum, resets, won't start Visual, capacitance, ESR
Ceramic capacitor Cracked → short or open Rail shorted, intermittent Continuity, visual
Tantalum capacitor Short (may burn) Rail shorted, burnt part Continuity, visual
Inductor Open winding, saturation No output, overheating Ω
Transformer Open winding, shorted turns No output, hot, hum Ω, isolation
Diode Short or open Blown fuses, no output Diode mode
LED Open Dark Diode mode (faint glow)
BJT C–E short, open Load stuck on or off Diode mode
MOSFET D–S short, gate punctured Load stuck on, gate leakage Diode mode + gate charge test
Voltage regulator Open or shorted No output, or input passed through Voltage in/out
Fuse Open (doing its job) Dead circuit Continuity; find the cause
Relay Contacts burnt or welded, coil open Won't switch, stuck Coil Ω, contact continuity
Switch Dirty or worn contacts Intermittent Continuity, voltage drop
Connector Loose, corroded, pushed-back contact Intermittent Wiggle, voltage drop
Crystal Cracked, not oscillating Chip won't run Scope on the oscillator
IC ESD damage, overvoltage, shorted pin Dead, hot, erratic Power pins, diode test per pin, substitution
Battery Low capacity, high internal resistance Short runtime, sag under load Loaded voltage, capacity test
Motor Worn brushes, open winding, bearings Weak, won't start, noisy Ω while rotating, current draw
Speaker Open coil, rubbing coil Silent, scraping Ω, battery click
Display Backlight failure, cable, contrast Dark, garbled Flashlight test, cable reseat
Sensor Damaged, drift, misconfigured Wrong or stuck readings Known reference, power, bus scan

34.5 Common root causes (the usual suspects)

In rough order of how often they turn out to be the answer:

  1. Power: wrong voltage, not enough current, sagging under load, noisy.
  2. Connections: loose, cold joints, wrong pin, wrong breadboard row, crossed wires.
  3. Ground: missing common ground, broken return, ground loops.
  4. Polarity or orientation: reversed battery, diode, electrolytic, chip, LED.
  5. Configuration: code pin numbers, addresses, baud rates, jumpers, settings.
  6. Logic levels: 3.3 V vs 5 V mismatches.
  7. Missing "small" parts: pull-ups, decoupling caps, flyback diodes, current-limiting resistors, gate pull-downs.
  8. Wrong part or variant: similar-looking modules, look-alike chips, the wrong value.
  9. Heat.
  10. Actually failed components: less common than all of the above, but they happen.

34.6 When to replace vs repair


34.7 Did you know?

Appendix A — Cheat sheet

Core formulas

Quantity Formula
Ohm's law V = I × R · I = V ÷ R · R = V ÷ I
Power P = V × I = I² × R = V² ÷ R
Energy Wh = W × hours · Wh = Ah × V · 1 Wh = 3,600 J
Battery runtime hours ≈ Ah ÷ A ≈ Wh ÷ W (derate 20–30 %)
Series resistance R = R1 + R2 + …
Parallel resistance 1/R = 1/R1 + 1/R2 + … (two: R1R2 ÷ (R1 + R2))
Series capacitance 1/C = 1/C1 + 1/C2 + …
Parallel capacitance C = C1 + C2 + …
Voltage divider V_out = V_in × R2 ÷ (R1 + R2)
LED resistor R = (V_supply − V_f) ÷ I
BJT base resistor R_B = (V_ctrl − 0.7) ÷ (I_load ÷ 10)
RC time constant τ = R × C (63 % at 1τ, ~99 % at 5τ)
RC filter cutoff f = 1 ÷ (2π × R × C)
Capacitor energy E = ½ × C × V²
Capacitive reactance X_C = 1 ÷ (2π × f × C)
Inductive reactance X_L = 2π × f × L
Wire voltage drop V = I × (Ω/m) × length × 2
Linear regulator loss P = (V_in − V_out) × I
Switching converter input current I_in = (V_out × I_out) ÷ (efficiency × V_in)
Temperature rise ΔT = P × θ (°C/W)
AC peak from RMS V_peak = V_RMS × 1.414
Frequency / period f = 1 ÷ T
555 astable f ≈ 1.44 ÷ ((R1 + 2R2) × C)
555 monostable t = 1.1 × R × C
LM317 output V = 1.25 × (1 + R2 ÷ R1)
Non-inverting op-amp gain 1 + Rf ÷ Rg
Inverting op-amp gain −Rf ÷ Rin

Everyday circuits

Five everyday circuits: LED resistor, button pull-up, voltage divider, MOSFET switch, relay with flyback diode.
Five everyday circuits: LED resistor, button pull-up, voltage divider, MOSFET switch, relay with flyback diode.

Pinouts for common parts and connectors are in Appendix D.

Prefixes

G M k — m µ n p
10⁹ 10⁶ 10³ 1 10⁻³ 10⁻⁶ 10⁻⁹ 10⁻¹²

4k7 = 4.7 kΩ · 2R2 = 2.2 Ω · 3V3 = 3.3 V · 100n = 100 nF

Resistor color code

Black Brown Red Orange Yellow Green Blue Violet Grey White Gold Silver
0 1 2 3 4 5 6 7 8 9 ×0.1, ±5 % ×0.01, ±10 %

Tolerance: brown ±1 %, red ±2 %, green ±0.5 %, blue ±0.25 %, violet ±0.1 %. 4-band: digit, digit, multiplier, tolerance. 5-band: digit, digit, digit, multiplier, tolerance.

E12: 10 12 15 18 22 27 33 39 47 56 68 82 E24 adds: 11 13 16 20 24 30 36 43 51 62 75 91

SMD resistor codes

103 = 10 kΩ · 472 = 4.7 kΩ · 4R7 = 4.7 Ω · 1002 = 10 kΩ · R010 = 10 mΩ · 000 = 0 Ω

Capacitor codes (pF)

101 = 100 pF · 102 = 1 nF · 103 = 10 nF · 104 = 100 nF · 105 = 1 µF Tolerance letters: J ±5 %, K ±10 %, M ±20 %, Z +80/−20 % Aluminum electrolytic stripe = negative. Tantalum bar = positive.

LED forward voltages

IR Red Orange/Yellow Yellow-green Green/Blue/White UV
1.2–1.6 V 1.8–2.2 V 2.0–2.2 V 2.0–2.4 V 2.8–3.4 V 3.0–4.0 V

Diode forward drops

Silicon ~0.6–0.7 V · Schottky ~0.2–0.45 V · Germanium ~0.3 V · LED 1.2–3.5 V · BJT B–E ~0.65 V

Wire gauge (copper)

AWG mm² Ω/m ~Amps (short, open air)
10 5.26 0.0033 30
12 3.31 0.0052 20–25
14 2.08 0.0083 15–20
16 1.31 0.013 10–13
18 0.82 0.021 7–10
20 0.52 0.033 5
22 0.33 0.053 3
24 0.20 0.084 2
26 0.13 0.13 1
28 0.08 0.21 0.5–1

Battery voltages (per cell)

Chemistry Nominal Full Empty
Alkaline 1.5 V 1.6 V ~1.0 V
NiMH 1.2 V 1.4 V 1.0 V
Lead-acid 2.0 V 2.1 V (rest) / 2.4 V (charging) ~1.75 V
Li-ion / LiPo 3.6–3.7 V 4.20 V 3.0 V
LiFePO₄ 3.2 V 3.65 V 2.5 V
Lithium coin (CR) 3.0 V 3.2 V ~2.0 V

Logic levels

Family V_IH (min HIGH) V_IL (max LOW)
5 V TTL / HCT / AHCT 2.0 V 0.8 V
5 V CMOS / HC 3.5 V 1.5 V
3.3 V LVCMOS 2.0 V 0.8 V
WS2812 at 5 V ~3.5 V ~1.5 V

3.3 V parts: max input ~3.6 V unless marked 5 V-tolerant.

Typical GPIO current

ATmega328P 20 mA (40 max) · ESP32 ~20 mA (40 max) · RP2040 4–12 mA (50 mA total) · Raspberry Pi ~16 mA (keep the total low)

Common I²C addresses

OLED 0x3C/0x3D · LCD backpack 0x27/0x3F · BME/BMP280 0x76/0x77 · MPU6050 & DS3231 0x68 · ADS1115 0x48–0x4B · BH1750 0x23/0x5C · VL53L0X 0x29 · INA219 0x40+ · PCA9685 0x40 · AT24C32 EEPROM 0x50–0x57

Bus wiring

Bus Connect
UART TX → RX, RX ← TX, GND. Same baud (8N1)
I²C SDA–SDA, SCL–SCL, GND, pull-ups (2.2–10 kΩ)
SPI SCK, MOSI → MOSI, MISO ← MISO, CS per device (active low)
RS-485 / CAN Twisted pair, 120 Ω at each end
1-Wire DQ + 4.7 kΩ pull-up

Mains

North America 120 V 60 Hz (peak ~170 V) · Europe/most of the world 230 V 50 Hz (peak ~325 V) Wire colors: NA hot black/red, neutral white, ground green/bare · IEC live brown, neutral blue, earth green/yellow

Fuse markings

F = fast · T = time-lag (slow-blow) · L = low breaking capacity (glass) · H = high (ceramic)

Hobby servo signal

50 Hz · 1.0 ms = one end · 1.5 ms = center · 2.0 ms = other end (0.5–2.5 ms on many)

Multimeter quick reference

Measure Mode Power Connect
Voltage V⎓ / V~ On Across (parallel)
Current A / mA / µA On In series (break the circuit)
Resistance Ω Off Across the part
Continuity Beeper Off Across
Diode Diode symbol Off Red = anode
Capacitance F Off, discharged Across
Frequency / duty Hz / % On Across the signal

Appendix B — Glossary

AC (alternating current): current that periodically reverses direction, like mains power. See chapter 1.

Active-high / active-low: whether a signal performs its function when HIGH or when LOW. Active-low names carry a bar, /, #, or n (e.g. /RESET, nCS). See chapter 14.

ADC (analog-to-digital converter): turns a voltage into a number. See chapter 29.

Ampere (A): unit of current. One coulomb of charge per second. See chapter 1.

Amp-hour (Ah, mAh): battery charge capacity: current × time. See chapter 19.

Anode / cathode: the positive (anode) and negative (cathode) terminals of a diode or LED. Conventional current flows from anode to cathode. The band marks the cathode. See chapter 13.

AWG (American Wire Gauge): wire size. Smaller numbers are thicker. See chapter 4.

Back-EMF: the voltage a motor generates while spinning, or a coil generates when its current changes. See chapter 22.

Bandgap reference: a circuit inside chips producing a stable ~1.2 V reference. See chapter 28.

Baud rate: symbols (usually bits) per second on a serial link. See chapter 30.

Bias: a steady voltage or current applied to set a device's operating point. See chapter 16.

BJT (bipolar junction transistor): a current-controlled transistor (NPN or PNP). See chapter 16.

BMS (battery management system): monitors and protects a multi-cell battery, often balancing the cells. See chapter 19.

Bootloader: a small program that lets a microcontroller receive new firmware. See chapter 29.

Brownout: a temporary dip in supply voltage that can reset or confuse circuits. See chapter 21.

Buck / boost converter: switching regulators that step voltage down (buck) or up (boost). See chapter 20.

Bulk capacitor: a large capacitor supplying sudden current demands. See chapter 10.

Bus: a shared set of wires connecting multiple devices. See chapter 30.

Capacitance (F): the ability to store charge. Unit: the farad. See chapter 10.

CC/CV: constant-current / constant-voltage charging, used for lithium batteries. See chapter 19.

Clamp diode: a diode that limits a voltage to within the supply rails. Built into most IC pins. See chapter 13.

CMOS: the transistor technology used in most modern logic and microcontrollers. See chapter 27.

Common ground: a shared 0 V reference between connected devices. See chapter 1.

Comparator: a circuit or chip that outputs HIGH or LOW depending on which of two voltages is larger. See chapter 28.

Continuity: an unbroken electrical path. See chapter 3.

Conventional current: current treated as flowing from + to −, the opposite of the actual electron flow. See chapter 1.

Crimp: a mechanical cold-weld joining a wire to a terminal. See chapter 5.

Current (I): the flow rate of electric charge, in amperes. See chapter 1.

Current limiting: restricting current, e.g. with a resistor for an LED, or a supply's current-limit setting. See chapter 14.

DAC (digital-to-analog converter): turns a number into a voltage. See chapter 29.

Darlington: two transistors combined for very high current gain. See chapter 16.

Datasheet: the manufacturer's technical document for a part. See chapter 2.

DC (direct current): current flowing in one direction. See chapter 1.

Debounce: filtering the rapid on/off bouncing of mechanical switch contacts. See chapter 25.

Decoupling capacitor: a small capacitor (usually 100 nF) at an IC's power pins that supplies fast current spikes. See chapter 10.

Derating: operating a part below its maximum ratings for reliability. See chapter 2.

Dielectric: the insulating material between a capacitor's plates. See chapter 10.

Differential signal: a signal carried as the difference between two wires. Rejects noise. See chapter 30.

Diode: a component allowing current in one direction only. See chapter 13.

Duty cycle: the percentage of time a PWM signal is on. See chapter 1.

EMI (electromagnetic interference): unwanted electrical noise radiated or conducted between circuits. See chapter 21.

ESD (electrostatic discharge): a static spark that can damage components. See chapter 32.

ESR (equivalent series resistance): a capacitor's internal resistance. See chapter 10.

Farad (F): unit of capacitance. See chapter 10.

Ferrite bead: a component that blocks high-frequency noise. See chapter 11.

Firmware: the program stored in a microcontroller. See chapter 29.

Flip-flop: a logic circuit storing one bit. See chapter 27.

Floating: an input connected to nothing, reading unpredictably. See chapter 29.

Flux: a chemical that cleans metal surfaces so solder flows. See chapter 32.

Flyback diode: a diode across a coil that absorbs the voltage spike when current is switched off. See chapter 11.

Forward voltage (Vf): the voltage dropped across a conducting diode or LED. See chapter 13.

Frequency (Hz): cycles per second. See chapter 1.

Fuse: a sacrificial component that opens on over-current. See chapter 7.

Gain: the ratio of output to input (e.g. an amplifier's gain, or a transistor's hFE). See chapter 28.

Galvanic isolation: no direct electrical connection between two circuits. See chapter 31.

Gate: the control terminal of a FET. Also a basic logic element (AND, OR…). See chapter 17.

GPIO: general-purpose input/output pin. See chapter 29.

Ground (GND): the reference point defined as 0 V. See chapter 1.

Ground loop: multiple ground paths forming a loop, causing noise or hum. See chapter 21.

H-bridge: four switches that let a motor run in either direction. See chapter 22.

Heatsink: a metal part that dissipates heat from a component. See chapter 17.

hFE / β: a BJT's current gain. See chapter 16.

Hi-Z (high impedance): a disconnected-like output state (three-state logic). See chapter 27.

Hysteresis: different thresholds for switching on and off, preventing chatter. See chapter 28.

I²C: a two-wire addressed bus (SDA, SCL). See chapter 30.

IC (integrated circuit): a complete circuit on a silicon chip. See chapter 27.

Impedance (Z): opposition to AC, combining resistance and reactance. Measured in ohms. See chapter 11.

Inductance (H): the property of storing energy in a magnetic field. Unit: the henry. See chapter 11.

Inrush current: the large surge when a device is first powered. See chapter 7.

Internal resistance: the effective resistance inside a battery or source. See chapter 19.

Isolation: see galvanic isolation. See chapter 31.

Kickback: the voltage spike from an inductor when its current is interrupted. See chapter 11.

LDO (low-dropout regulator): a linear regulator that works with a small input–output difference. See chapter 20.

Level shifter: a circuit translating signals between voltage levels (e.g. 3.3 V ↔ 5 V). See chapter 31.

Linear regulator: a regulator that drops excess voltage as heat. See chapter 20.

Load: whatever a circuit powers or drives. See chapter 1.

Logic-level MOSFET: a MOSFET fully on at logic voltages (≤ 4.5 V or 2.5 V). See chapter 17.

MCU (microcontroller): a single-chip computer with peripherals. See chapter 29.

MOSFET: a voltage-controlled transistor (N- or P-channel). See chapter 17.

Multiplexing: sharing lines or time among several signals or devices. See chapter 24.

NC / NO: normally closed / normally open (switch contacts). NC also means "no connection" in pin tables. See chapter 6.

Noise: unwanted variations in a signal or supply. See chapter 21.

Ohm (Ω): unit of resistance. See chapter 1.

Ohm's law: V = I × R. See chapter 1.

Op-amp: a high-gain differential amplifier IC. See chapter 28.

Open circuit: a break in a path. No current flows. See chapter 1.

Open-drain / open-collector: an output that can only pull LOW. See chapter 27.

Optocoupler: an LED and light sensor in one package, for isolation. See chapter 14.

Oscillator: a circuit producing a repeating signal. See chapter 12.

Parallel: components connected across the same two points. See chapter 1.

PCB: printed circuit board. See chapter 32.

Peripheral: a hardware block inside an MCU (UART, timer, ADC), or a device connected to it. See chapter 29.

Piezoelectric: materials that produce voltage when stressed and flex when voltage is applied. See chapter 12.

Polarity: the orientation of + and − that matters for some parts. See chapter 2.

Potentiometer: a variable resistor with a sliding wiper. See chapter 9.

Power (W): the rate of energy use: V × I. See chapter 1.

Pull-up / pull-down: a resistor holding a line HIGH or LOW by default. See chapter 8.

PWM (pulse-width modulation): fast on/off switching whose duty cycle sets average power. See chapter 1.

Rail: a power supply line (e.g. "the 3.3 V rail"). See chapter 21.

Reactance: opposition to AC by capacitors and inductors. See chapter 11.

Rectifier: converts AC to DC. See chapter 13.

Reference designator: a part label like R1, C3, U2. See chapter 2.

Regulator: holds a steady output voltage. See chapter 20.

Relay: an electrically operated switch. See chapter 6.

Resistance (R): opposition to current, in ohms. See chapter 1.

Resistor: a component with a fixed resistance. See chapter 8.

Ripple: residual AC variation on a DC supply. See chapter 21.

RMS: root mean square, the effective value of an AC waveform. See chapter 1.

Saturation: a transistor fully on. Also, an inductor core unable to store more magnetic energy. See chapter 16.

Schmitt trigger: an input with hysteresis that cleans slow or noisy signals. See chapter 27.

Schottky diode: a low-drop, fast diode. See chapter 13.

Series: components connected end to end in one path. See chapter 1.

Short circuit: an unintended low-resistance path. See chapter 1.

Shunt: a low-value resistor used to measure current. Also, a component connected in parallel. See chapter 26.

Sink / source: an output sinking current (pulling to ground) or sourcing it (supplying from the positive rail). See chapter 29.

SMD / SMT: surface-mount device or technology. See chapter 32.

Snubber: a network (often RC) that suppresses voltage spikes or arcing. See chapter 18.

SPI: a fast clocked bus with chip-select lines. See chapter 30.

SSR (solid-state relay): a relay with no moving parts. See chapter 18.

Strapping pin: a pin read at reset to choose a boot mode. See chapter 29.

Switching regulator: an efficient regulator using high-speed switching and an inductor. See chapter 20.

Thermal runaway: a positive feedback loop of heating that destroys a component or battery. See chapter 19.

Thyristor: a latching semiconductor switch (SCR, TRIAC). See chapter 18.

Tolerance: the allowed deviation from a nominal value. See chapter 8.

Transformer: coupled coils that change AC voltage and provide isolation. See chapter 11.

Transistor: a semiconductor device that switches or amplifies. See chapter 16.

TRIAC: a bidirectional thyristor for AC switching. See chapter 18.

TTL: transistor-transistor logic. Also its logic-level standard (HIGH ≥ 2.0 V). See chapter 27.

TVS diode: a diode designed to absorb voltage surges. See chapter 7.

UART: asynchronous serial interface (TX/RX). See chapter 30.

Voltage (V): electrical potential difference. The "push." See chapter 1.

Voltage divider: two resistors producing a fraction of a voltage. See chapter 8.

Voltage drop: voltage lost across a component or wire as current flows. See chapter 1.

Watt (W): unit of power. See chapter 1.

Wiper: the moving contact of a potentiometer. See chapter 9.

Zener diode: a diode that conducts in reverse at a defined voltage. See chapter 13.

Appendix C — Identifying parts by sight

A part's shape tells you its family. Its markings tell you the exact part. Start with the pictures below to narrow it down, then read the printed code (chapter 2) and confirm with a meter or component tester.


C.1 Through-hole parts

Common through-hole parts with their giveaway features.
Common through-hole parts with their giveaway features.

C.2 Surface-mount parts

Common surface-mount parts, magnified.
Common surface-mount parts, magnified.

Chip sizes

Small rectangular parts (resistors, capacitors, inductors, LEDs) come in standard sizes named by their length and width.

SMD chip sizes to scale.
SMD chip sizes to scale.
Inch code Metric code Body size (mm) Resistor power By hand?
0201 0603 0.6 × 0.3 1/20 W Not realistically
0402 1005 1.0 × 0.5 1/16 W Tweezers, magnification, patience
0603 1608 1.6 × 0.8 1/10 W Takes practice
0805 2012 2.0 × 1.25 1/8 W Comfortable
1206 3216 3.1 × 1.6 1/4 W Easy
1210 3225 3.1 × 2.6 1/2 W Easy
2512 6332 6.35 × 3.1 1 W Easy

Sizes and power ratings are for standard thick-film chip resistors (Yageo RC series). Other makers' sizes are within a tenth of a millimeter or so, and "high-power" versions of the same sizes are rated higher.

⚠️ The two naming systems overlap. An inch "0603" is 1.6 × 0.8 mm, but a metric "0603" is 0.6 × 0.3 mm (the inch 0201). Check which system a listing uses before buying.

Tiny marking codes

Parts in SOT-23 and similar packages are too small for a full part number, so they carry a 2–4 character marking code instead. Codes aren't shared between makers. The same MMBT3904 transistor is marked "1AM" by onsemi and "K1N" by Diodes Inc., and one code can mean different parts from different makers. Search "SMD marking code" plus the code and the package, and treat the answer as a lead to confirm, not a certainty.


C.3 Look-alikes that fool people

These look alike How to tell them apart
Resistor vs axial inductor Inductors are usually fatter and often green or light blue. On a meter, an inductor reads close to 0 Ω; a resistor reads its value (chapter 11)
Signal diode vs Zener (glass, black band) Only the tiny printed number tells: 1N4148 is a signal diode; 1N47xx, BZX55C… and "5V1"-style marks are Zeners. The meter's diode test reads the same for both (chapter 13)
Ceramic capacitor vs MOV vs thermistor vs polyfuse (colored discs) Read the marking. Capacitors: a 3-digit code like 104. MOVs: disc size, D, then a voltage code, like 10D471 (10 mm disc, 470 V). Inrush NTC thermistors: ohms, D, then disc size, like 5D-11 (5 Ω, 11 mm). Polyfuses carry a short maker's code; look it up under the maker's series (Littelfuse RXEF, Bourns MF-R…)
TO-92 transistor vs regulator vs sensor vs reference Identical bodies. The marking decides: 2N3904 (transistor), 78L05 (regulator), DS18B20 or LM35 (temperature sensor), TL431 (reference), 2N7000 (MOSFET). Pinouts differ too (appendix D)
TO-220 MOSFET vs transistor vs regulator vs TRIAC Again, only the marking: IRLZ44N (MOSFET), TIP120 (transistor), 7805 or LM317 (regulator), BT136 (TRIAC)
Crystal vs ceramic resonator Crystals are usually metal cans with 2 leads and a frequency like "16.000". Resonators are colored plastic, often with 3 leads (built-in capacitors) and a shorter frequency mark such as "16.00M" (chapter 12)
Electrolytic vs supercapacitor Same can shape. Supercaps are rated in whole farads (1.0F, 10F) at only a few volts (chapter 10)
Active vs passive buzzer Active buzzers usually have a sealed, flat underside and beep on plain DC. Passive ones often show a green circuit board underneath and only click on DC (chapter 23)
Chip resistor vs chip capacitor Resistors are black on top with a printed code. Capacitors are tan, brown, or grey and almost never marked
Chip capacitor vs chip inductor Often identical. Measure: an inductor reads near 0 Ω; a capacitor reads open
LED vs photodiode vs IR LED IR LEDs are often clear or light blue; photodiodes and IR receivers are often black or dark purple (they filter out visible light). In diode-test mode, many LEDs glow faintly (chapter 14)
Fuse vs fusible resistor A fusible resistor looks like an ordinary resistor (often grey or white) but is shown as a resistor with a fuse symbol on the board. It opens deliberately under overload

C.4 A quick identification routine

  1. Count the leads and look for polarity marks (bands, stripes, flats, notches, +).
  2. Read every marking with a magnifier and good light. Photograph it and zoom in if needed.
  3. Look at the board: the silkscreen reference designator (R, C, D, Q, U, L…) says what kind of part it is (chapter 2).
  4. Search the marking together with the package name.
  5. Confirm with a meter: resistance, diode test, or capacitance (chapter 3). A low-cost component tester identifies most two- and three-lead parts and their pinouts automatically.

Appendix D — Common pinouts

Every pinout on this page was checked against the manufacturer's datasheet listed under D.5. Two cautions still apply:


D.1 TO-92 parts

TO-92 pinouts for common transistors, MOSFETs, regulators and sensors.
TO-92 pinouts for common transistors, MOSFETs, regulators and sensors.

All orders are left to right, with the flat face toward you and the leads pointing down.

Part Left to right What it is Watch out
2N3904 / 2N3906 E B C NPN / PNP small-signal transistors
2N2222 (see note) E B C or C B E NPN transistor onsemi's PN2222A is E B C, but its P2N2222A is C B E. Check which one you have
BC547 / BC557 C B E NPN / PNP (European numbering) Reversed compared with the 2N3904
2SC1815 E C B NPN (Japanese numbering) Base on the end, not in the middle
2N7000 S G D N-channel MOSFET
BS170 D G S N-channel MOSFET Same job as the 2N7000, opposite end pins
78L05 OUT GND IN 5 V, 100 mA regulator Reversed compared with the TO-220 7805
TL431 REF A K Adjustable shunt reference TI numbers these pins 3-2-1 (cathode = pin 1). The physical order is the same
DS18B20 GND DQ VDD 1-Wire temperature sensor
LM35 +VS OUT GND Analog temperature sensor (10 mV/°C)

💡 Go by position, not pin number. The TL431 shows why. Makers don't all number TO-92 pins from the same side, so "pin 1" can be at either end. The left-to-right order above is what matters.


D.2 TO-220 and small SMD packages

TO-220, SOT-23 and SOT-223 pinouts.
TO-220, SOT-23 and SOT-223 pinouts.

TO-220 orders are left to right, with the printed face toward you and the leads pointing down. SOT-23 and SOT-223 are seen from the top: pin 1 is bottom-left.

Part Package Pins Tab / notes
7805 / 7812 TO-220 IN GND OUT Tab = GND
7905 (negative) TO-220 GND IN OUT Tab = IN. Different from the 78xx
LM317 TO-220 ADJ OUT IN Tab = OUT
IRLZ44N, IRF540N, IRLB8721 (N-channel MOSFETs) TO-220 G D S Tab = D
TIP120 / TIP31 / TIP41 TO-220 B C E Tab = C
BT136 TRIAC TO-220 T1 T2 G Tab = T2. (T1/T2 are also called MT1/MT2)
AO3400, 2N7002, BSS138 SOT-23 1 G, 2 S, 3 D
MMBT3904, MMBT2222A SOT-23 1 B, 2 E, 3 C
AMS1117 SOT-223 1 ADJ/GND, 2 OUT, 3 IN Tab = OUT

⚠️ The metal tab is connected to a pin. On every TO-220 part above it's the middle one. Two TO-220 parts sharing one heatsink need an insulating pad and washer unless their tabs are at the same voltage.


D.3 DIP chips

Pinouts of the 555, a dual op-amp, the PC817 optocoupler and the 74HC595.
Pinouts of the 555, a dual op-amp, the PC817 optocoupler and the 74HC595.

All chips are seen from the top, with the notch or dot at pin 1. More pinouts:

Part Pins that matter
TL071 single op-amp 2 = IN−, 3 = IN+, 4 = V−, 6 = OUT, 7 = V+
LM324 quad op-amp 4 = V+, 11 = V− (or GND). Four amplifiers around the edges
74HC00 and most 14-pin 74-series logic 7 = GND, 14 = VCC. Not every 74-series part follows this, so check yours
ULN2803A Darlington array (18-pin DIP) Inputs 1–8, outputs 18–11, 9 = GND, 10 = COMMON (to the load supply, for the built-in flyback diodes). 20-pin surface-mount versions are numbered differently

D.4 Everyday connectors

Connector Pinout
USB-A / USB 2.0 cable 1 VBUS, 2 D−, 3 D+, 4 GND. Wires are usually red, white, green, black in that order, but not always
Qwiic / STEMMA QT (4-pin I²C) Black GND, red 3.3 V, blue SDA, yellow SCL
Grove (4-pin) Pin 1 yellow (SCL, or signal 1), pin 2 white (SDA, or signal 2), pin 3 red VCC, pin 4 black GND
Hobby servo (3-pin) Signal, +V, ground, with power in the middle so a reversed plug doesn't reverse the supply. Wire colors vary by brand
3.5 mm stereo (TRS) Tip = left, ring = right, sleeve = ground
3.5 mm headset (TRRS) Current (CTIA) standard: tip = left, ring 1 = right, ring 2 = ground, sleeve = microphone. The older OMTP standard swaps ground and microphone
Barrel jack Polarity varies; read the symbol printed on the adapter (chapter 5)

On anything without a published standard (addressable LED strips, RGB LEDs, cheap modules), wire colors and lead order vary by maker. Check with a meter's diode or continuity test before connecting power.


D.5 Sources

Each pinout above was checked against these documents:

Parts Source
2N3904, 2N3906, PN2222A, P2N2222A, BC547, BC557, 2N7000, BS170, MC78L05, MC7905, TIP120, TIP31, TIP41, MMBT3904 onsemi datasheets (also used for the TO-92 pin-1 orientation, from onsemi's TO-92 package drawing)
2SC1815 Toshiba datasheet
TL431, LM35, LM7805, LM317, NE555, LM358, LM324, TL071, SN74HC00, SN74HC595 Texas Instruments datasheets
DS18B20 Analog Devices (Maxim) datasheet
IRLZ44N, IRF540N, IRLB8721 Infineon (International Rectifier) datasheets
BT136-600 WeEn Semiconductors datasheet
AO3400A Alpha & Omega Semiconductor datasheet
2N7002, BSS138, MMBT3904, MMBT2222A (SOT-23) Diodes Incorporated datasheets
AMS1117 Advanced Monolithic Systems datasheet
PC817 Sharp datasheet
ULN2803A Toshiba datasheet
Qwiic SparkFun Qwiic documentation
Grove Seeed Studio Grove system documentation
USB, TRS/TRRS, servo Summaries of the USB 2.0 and headset standards, and of servo practice (Wikipedia)
tap or Esc to close