UNIT 01 · LESSON 5 OF 6

Switches, LEDs, and Interface Circuits

Recognising real parts and their symbols, why switch contacts bounce, how to pick an LED resistor from its forward voltage, and how a MOSFET lets a small pin switch a large load safely.

INTERACTIVESeries resistor, forward voltage and LED current
LED with series resistor, and the load line intersecting the LED current–voltage curve5 VR = 330 ΩVR = 3.11 VPR = 29.2 mWVF ≈ 1.89 VI = 9.41 mAONbrightness (relative to 20 mA): 47 %01.32.53.8505101520LED voltage (V)Current (mA)LED curve and the resistor load lineVF = 1.9 VTeal: LED · Orange: resistor load line
LED with series resistor, and the load line intersecting the LED current–voltage curve5 VR = 330 ΩVR = 3.11 VPR = 29.2 mWVF ≈ 1.89 VI = 9.41 mAONbrightness (relative to 20 mA): 47 %01.32.53.8505101520LED voltage (V)Current (mA)LED curve and the resistor load lineVF = 1.9 VTeal: LED · Orange: resistor load line

Try this

Exponential model: the load line meets the LED curve at V ≈ 1.89 V, I ≈ 9.41 mA (simple model would say 9.39 mA). Resistor: VR = 3.11 V, PR = I²R = 29.2 mW. LED: 17.8 mW.

The resistor takes the difference between the supply and the LED’s forward voltage, and that sets the current: I = (Vs − VF) / R. The simple model treats VF as a constant; the exponential model lets the LED’s voltage rise slowly with current, which is why an LED without a resistor is a gamble: a small change in voltage means a huge change in current. Limits shown (30 mA, 1/4 W) are the example LED’s and resistor’s, not general rules.

What you will be able to do
  • Match a physical switch, LED, resistor, capacitor, diode and MOSFET to its schematic symbol and polarity markers.
  • Describe contact bounce and estimate how many false edges a naive edge counter would see.
  • Choose an LED series resistor from the supply, the forward voltage and the target current, and check the resistor’s power.
  • Explain the difference between a constant-VF approximation and a real LED’s exponential curve.
  • Draw a MOSFET low-side driver with gate resistor, gate pull-down, shared ground return and, for an inductive load, a flyback diode.
Before you start
  • Ohm’s law, power and the closed loop (lesson 1).
  • Pull-ups and active-low inputs (lesson 3).
  • The idea of a capacitor slowing a voltage change (lesson 4).
Steps in this lesson
  1. Parts and symbols
  2. Switches bounce
  3. LEDs: polarity, forward voltage and the resistor
  4. Bigger loads: the MOSFET switch
  5. Common misconceptions

The puzzle

You wire an LED straight from a pin to ground and it lights, brightly, for a while. You add a button and your counter goes up by three per press. You want to switch a relay and the pin gets warm. Each of these is the same lesson: the pin is a delicate voltage source, and everything it talks to needs an interface designed around what the part really does.

STEP 1

Parts and symbols

DIAGRAMWhat the part looks like, and how the schematic draws it
Physical sketches of common parts beside their schematic symbolsTactile push buttonPHYSICAL PARTSYMBOLSWLEDPHYSICAL PARTSYMBOL+−anode (+)cathode (−)ResistorPHYSICAL PARTSYMBOLR · no polarityElectrolytic capacitorPHYSICAL PARTSYMBOL−++−polarisedSmall diodePHYSICAL PARTSYMBOLAKbar = cathodeN-channel MOSFETPHYSICAL PARTSYMBOLGDSDSG
Physical sketches of common parts beside their schematic symbolsTactile push buttonPHYSICAL PARTSYMBOLSWLEDPHYSICAL PARTSYMBOL+−anode (+)cathode (−)ResistorPHYSICAL PARTSYMBOLR · no polarityElectrolytic capacitorPHYSICAL PARTSYMBOL−++−polarisedSmall diodePHYSICAL PARTSYMBOLAKbar = cathodeN-channel MOSFETPHYSICAL PARTSYMBOLGDSDSG
Physical marker → symbol: LED long lead = anode; flat rim / short lead = cathode; stripe = electrolytic negative; band = diode cathode.

Left in each cell is a sketch of the physical part; right is its schematic symbol. Polarised parts carry a physical marker: the LED’s longer lead and the flat rim on the cathode side, the electrolytic capacitor’s stripe on the negative lead, the diode’s painted band at the cathode. Pin order on packaged transistors varies between parts, so the datasheet, not the drawing, decides which leg is which.

Schematic symbols are abstractions; the physical part has to be identified and oriented on the bench. The markers that carry polarity information are worth memorising: the LED’s longer lead is the anode (+) and the flat spot on its rim marks the cathode; an electrolytic capacitor has a stripe on the negative lead; a small diode has a painted band at the cathode end. Resistors, ceramic capacitors and switches have no polarity. Transistor packages are the trap: two parts in the same three-leg package can have their pins in different orders, so the pinout diagram in the datasheet is the only reliable guide.

STEP 2

Switches bounce

A switch is two pieces of metal pressed together. When they meet, they strike, spring apart, and strike again, several times, before settling. The input pin sees a burst of edges rather than one.

INTERACTIVEWhat a button really does when you press it
Pull-up button circuit and the bouncing contact voltage during a press or releaseVDD10 kΩopeninputpin05101520253003.3Time (ms)Pin voltage (V)Contact voltage during a pressbounce ≈ 2.6 msEdges: 9 · counted 5 presses
Pull-up button circuit and the bouncing contact voltage during a press or releaseVDD10 kΩopeninputpin05101520253003.3Time (ms)Pin voltage (V)Contact voltage during a pressbounce ≈ 2.6 msEdges: 9 · counted 5 presses
Hold with the pointer, or press and hold Space.
Playback is slowed about 80×: 30 ms of contact behaviour take 2.5 s.
Press: the contact settled after 2.6 ms with 9 edges. Counting edges would register 5 presses for one physical action.

A pull-up holds the input HIGH; pressing the button pulls it LOW. But metal contacts do not close cleanly: they strike, spring apart and strike again for a few hundred microseconds to several milliseconds. A program that counts edges sees several presses. Each press or release here uses a fresh random bounce pattern; durations are chosen to match published measurements, most under 6 ms.

How long does it last? Ganssle’s measurements on 18 different switches are the classic reference. Leaving out two outliers, the average bounce was about 1.6 ms and the longest 6.2 ms; one of the outliers bounced for 157 ms when opening but under 20 µs when closing, and seven of the switches bounced much longer on closing than on opening. Manufacturers give an upper bound where they give anything: Omron specifies 5 ms maximum for its B3F tactile switches. Bounce times below 100 ns were also common, which is faster than most software can see but not faster than a hardware counter.

The practical rule that follows: any edge from a mechanical contact must be treated as the start of a possible event, confirmed only when the level has held steady for longer than the bounce. Doing that well, in hardware with an RC filter and a Schmitt-trigger input or in firmware with a timer, is a topic of its own later in the curriculum. Here the point is to recognise the burst when you see it.

STEP 3

LEDs: polarity, forward voltage and the resistor

An LED is a diode: current flows easily in one direction (anode to cathode) and essentially not at all in the other. In the conducting direction it does not obey Ohm’s law. Its current grows exponentially with voltage, so the voltage across a conducting LED barely moves while the current changes by orders of magnitude. That voltage is the forward voltage VFV_F, and it depends on semiconductor material, current, temperature and device variation: around 1.8–2.2 V for red, 3.0–3.4 V for blue and white. The Kingbright WP7113ID red LED used as the example here lists a typical 1.9 V, maximum 2.3 V, at 10 mA.

Because the LED holds its voltage, something else must set the current. That is the series resistor:

I=Vs−VFRI = \frac{V_s - V_F}{R} PR=I2RP_R = I^2 R

where VsV_s is the supply or pin voltage, VFV_F the LED forward voltage at roughly the current you want, RR the resistor and PRP_R the resistor’s dissipation.

↑ This step uses the figure at the top of the page.

Drive an LED with no resistor and the “resistor” becomes whatever the pin or supply cannot avoid providing: the pin’s own output resistance. The current is then limited by nothing you chose, the LED overheats, and the pin is pushed beyond its rating. Try 33 Ω at 5 V in the figure: nearly 100 mA in the simple model, over three times the example LED’s 30 mA absolute maximum.

The constant-VF approximation and the real curve

Treating VFV_F as a fixed number is a good working model once you know the current is in a sensible range. Switch the figure to the exponential model to see why it is only an approximation: the operating point is where the LED’s curve crosses the resistor’s load line I=(Vs−V)/RI = (V_s - V)/R, and VFV_F slides up and down that curve with current. With a healthy resistor the two models agree within a few hundred microamps. As the resistor shrinks, the load line becomes steep and the true current diverges from the simple estimate. Datasheets give the same picture as a “forward current vs forward voltage” graph, and the maximum-VF column is the reminder that units vary: use maximum forward voltage to check minimum current, and minimum forward voltage with maximum supply voltage and minimum resistance to check maximum current. A typical value alone cannot guarantee either bound.

Worked example

A 3.3 V pin should light a red LED at about 4 mA. With VF=1.9V_F = 1.9 V:

R=3.3−1.90.004=350 Ω→330 Ω (standard value)R = \frac{3.3 - 1.9}{0.004} = 350\ \Omega \rightarrow 330\ \Omega \text{ (standard value)}
I=3.3−1.9330=4.2 mAI = \frac{3.3 - 1.9}{330} = 4.2\ \text{mA} PR=0.00422×330=5.9 mWP_R = 0.0042^2 \times 330 = 5.9\ \text{mW}

If this particular LED is at its 2.3 V maximum, the current drops to 3.0 mA; still lit, slightly dimmer. Either way the resistor barely warms.

Can the pin drive it directly?

Only within limits the datasheet states, and they differ enormously between parts. The RP2040 lets you select a nominal 2, 4, 8 or 12 mA drive strength and guarantees VOH≥2.62V_{OH} \ge 2.62 V at that current; the settings are described as “not hard limits”, but the total sourced by all pads together must stay under 50 mA, and above the setting the guaranteed high voltage is void. The ATmega328P can sink or source 20 mA per pin at 5 V (with VOLV_{OL} rising to 0.9 V and VOHV_{OH} falling to 4.2 V at that current), lists 40 mA per pin as an absolute maximum, and caps the sum over groups of pins at 100–150 mA. So: 4 mA from a single pin is comfortable on both; 20 mA is a characterised test current for the ATmega328P at the stated conditions, but exceeds the RP2040’s highest 12 mA drive-strength test point; selecting 12 mA does not establish a guarantee at 20 mA. Three 20 mA LEDs exceed the RP2040 total budget and need the ATmega328P group and supply-current limits checked. Note also that the pin’s VOHV_{OH} at load current, not the supply voltage, is the VsV_s in the resistor formula.

STEP 4

Bigger loads: the MOSFET switch

A relay coil at 50 mA, a motor, a string of LEDs at 100 mA: none of these belongs on a pin. The answer is a transistor used as a switch, and the simplest reliable form is an N-channel MOSFET on the low side of the load.

INTERACTIVESwitching a bigger load with a MOSFET
Microcontroller pin driving a MOSFET low-side switch with a load, gate resistor, gate pull-down and shared groundMOSFET CHANNELOFF · not conductingMCUGPIO0 VGNDRG 100 Ω100 kΩgatepull-down+12 Vcoil240 Ωflybackdiodeshared ground: the return path
Microcontroller pin driving a MOSFET low-side switch with a load, gate resistor, gate pull-down and shared groundMOSFET CHANNELOFF · not conductingMCUGPIO0 VGNDRG 100 Ω100 kΩgatepull-down+12 Vcoil240 Ωflybackdiodeshared ground: the return path
Automatic cycle: OFF → ON → flyback (coil only) → OFF. Timing is slowed for teaching, not a device switching-time simulation.
Pin LOW: the gate sits at 0 V, the MOSFET is off, no load current. The pull-down also holds it off before the firmware has configured the pin.

The pin drives only the MOSFET gate through RG, so the load current never passes through the microcontroller. The 100 kΩ pull-down keeps the gate at 0 V while the pin is still floating at reset. Every current has a return path: the load current returns to the 12 V supply through the shared ground, which is why the two grounds are wired together. With a coil, the flyback diode gives the collapsing current a loop to circulate in; without it the drain voltage would spike far above the supply.

Read the circuit from the pin outward:

  • The gate is a capacitor. The MOSFET starts to conduct near its threshold VGS(th)V_{GS(th)}, but low-resistance switching requires a higher gate voltage supported by the RDS(on)R_{DS(on)} specification. Ideal gate current falls to zero after charging, although the external pull-down still draws a small steady current. The small gate resistor limits the pulse of current that charges the gate capacitance so the pin is not shorted for a few nanoseconds on every edge.
  • The gate pull-down (100 kΩ) holds the gate at 0 V while the pin is undriven, which is the case from power-up until firmware configures it. Without it the gate floats (lesson 3), and a floating gate can half-turn-on the MOSFET, which then heats.
  • Drain to the load, source to ground. The load sits between its supply, 12 V here, and the drain. When the gate is high, the channel connects drain to source and current flows +12 V → load → drain → source → ground.
  • The return path. That current returns to the 12 V supply through the ground net. The microcontroller’s ground and the load supply’s ground must be the same net, or the gate voltage is measured against nothing and the loop is open.

Which MOSFET

The gate is driven from 3.3 V, so the part must be fully on at 3.3 V. Datasheets tell you by listing RDS(on)R_{DS(on)} at specific gate voltages, and this is where “logic level” in a title is not enough. The Nexperia 2N7002 has VGS(th)V_{GS(th)} up to 2.5 V and its lowest characterised RDS(on)R_{DS(on)} row is at VGSV_{GS} = 4.5 V (5.3 Ω max); at 3.3 V a worst-case unit is barely above threshold, and nothing is promised. The BSS138AKA specifies VGS(th)≤1.5V_{GS(th)} \le 1.5 V and gives an RDS(on)R_{DS(on)} row at 2.5 V (13 Ω max at 10 mA), but that 10 mA condition does not establish a 50 mA guarantee at 3.3 V. Choose a part whose on-resistance is specified at a gate voltage no higher than your guaranteed drive and at an appropriate load current; check temperature, dissipation, and the load’s minimum operating voltage. The diagram uses a generic illustrative 5 Ω switch, not a guaranteed model of either named part.

Inductive loads and the flyback diode

A relay coil or motor is an inductor, and an inductor’s current cannot stop instantly: v=L di/dtv = L\,di/dt says that forcing a fast change produces a large voltage. When the MOSFET turns off, the coil tries to keep its current flowing and drives the drain voltage upward, tens or hundreds of volts if nothing stops it, enough to break the MOSFET.

The flyback diode across the coil, cathode to the supply, anode to the drain, is reverse-biased in normal operation and does nothing. At turn-off it gives the coil current a loop: coil → diode → coil, circulating until the coil’s own resistance dissipates the stored energy. In the idealized circuit the drain is clamped near one diode drop above the supply; wiring inductance and diode dynamics can add overshoot. Select the figure’s “just switched off” state to see that loop. A 1N4148 is one possible example for a small load, not a universal relay-diode recommendation. Check reverse voltage, initial coil current, pulse duration, repetition rate, thermal limits, and the coil’s stored energy for the selected diode.

MYTHS AND FACTS

Common misconceptions

An LED needs a certain voltage

It needs a certain current; the voltage follows from the LED. Without deliberate current limiting, current depends strongly on the source impedance and LED characteristics and can exceed ratings.

The resistor value is critical

Within a wide range the LED is simply a little brighter or dimmer; what is critical is that there is one, and that it is not so small the current exceeds the LED or pin rating.

A pin rated at 12 mA can drive 12 mA forever with no side effects

It can, at a reduced guaranteed high voltage, and only if the summed current over all pins stays within budget.

Any ‘logic level’ MOSFET works at 3.3 V

Look for an RDS(on)R_{DS(on)} row at or below your gate voltage. A threshold spec alone says only when the part starts to conduct.

Bounce is a firmware bug

It is physics; firmware or a filter handles it, but it is always there.

A flyback diode is optional if the relay is small

The spike depends on how fast the current is interrupted, not only on the coil size. A MOSFET switches fast.

Check yourself

Answer in your head, then open the card.

A 5 V supply, a white LED with VF ≈ 3.1 V, and a target of 10 mA. What resistor, and how much power does it dissipate?

R=(5−3.1)/0.010=190 ΩR = (5 - 3.1) / 0.010 = 190\ \Omega; use 180 or 200 Ω. At 200 Ω: I=9.5I = 9.5 mA, PR=0.00952×200=18P_R = 0.0095^2 \times 200 = 18 mW.

The same LED is wired to a 3.3 V pin through the same 200 Ω. What happens?

3.3−3.1=0.23.3 - 3.1 = 0.2 V across 200 Ω gives 1 mA in the simple model: barely lit. With VF at a maximum of 3.4 V it does not light at all. A white LED needs more headroom than a 3.3 V rail comfortably gives.

A button press produces 7 edges in 2 ms. What does a program that increments on every falling edge count?

Four presses (the falling edges among the seven transitions, for a press that starts high and ends low). Only a debounce, in hardware or software, turns the burst into one event.

A 12 V relay coil draws 50 mA. Why not drive it from a pin that is rated to source 12 mA?

The coil needs four times the pin’s rated current and a 12 V supply the pin cannot provide. A MOSFET switches the coil’s own supply while the pin only charges the gate. And because the coil is inductive, the MOSFET needs a flyback diode across the coil.

What does the 100 kΩ gate pull-down do, given that the pin drives the gate anyway?

Between power-up and the moment firmware configures the pin, the pin floats. The pull-down holds the gate at 0 V so the MOSFET stays off instead of drifting into partial conduction.

Sources (8)
  1. Jack Ganssle, “A Guide to Debouncing”, Part 1 (August 2004, rev. 2 April 2007) — measurements on 18 switches: excluding two outliers the average bounce was 1557 µs with a maximum of 6200 µs; one switch bounced 157 ms on opening; seven switches bounced much longer when closed than when opened
  2. Omron, Tactile Switch B3F datasheet (Cat. No. A070-E1-08), Ratings/Characteristics — bounce time 5 ms max; rating 1–50 mA at 3–24 V DC; minimum applicable load 10 µA at 1 V DC
  3. Kingbright, WP7113ID 5 mm High Efficiency Red LED datasheet (Spec No. DSAF0012, Rev. V.14A, 01/08/2026) — VF typ 1.9 V, max 2.3 V at IF = 10 mA; absolute maximum DC forward current 30 mA; peak 160 mA at 1/10 duty, 0.1 ms; reverse voltage 5 V; luminous intensity typ 50 mcd at 10 mA; forward-current derating curve on p. 3
  4. Raspberry Pi Ltd, RP2040 Datasheet (build 2025-02-20), Table 625 and §5.5.3.5 “Interpreting GPIO output voltage specifications”, pp. 616–617 — drive-strength settings of 2, 4, 8 or 12 mA that are “not hard limits”; VOH ≥ 2.62 V and VOL ≤ 0.5 V at the selected current; total sourced and total sunk pad current each ≤ 50 mA
  5. Microchip, ATmega328P Data Sheet DS40002061B (Rev. B, 08/2020), §29.1 Absolute Maximum Ratings p. 308 and Table 30-1 pp. 322–323 — DC current per I/O pin 40 mA (absolute maximum); VOL ≤ 0.9 V at IOL = 20 mA and VOH ≥ 4.2 V at IOH = −20 mA, VCC = 5 V, 85 °C; notes 3 and 4 cap the summed port currents at 100–150 mA
  6. Nexperia, 2N7002 “60 V, 300 mA N-channel Trench MOSFET” datasheet, Rev. 7 (8 September 2011), Tables 5 and 7 — VGS(th) 1–2.5 V; RDS(on) ≤ 5.3 Ω at VGS = 4.5 V, ID = 75 mA (lowest characterised gate voltage); ID 300 mA; VDS 60 V
  7. Nexperia, BSS138AKA “60 V, single N-channel Trench MOSFET” datasheet (2 February 2024), Table 7 — VGS(th) 0.8–1.5 V; RDS(on) ≤ 13 Ω at VGS = 2.5 V, ID = 10 mA and ≤ 5.2 Ω at VGS = 4.5 V, ID = 100 mA; ID 200 mA
  8. NXP (now Nexperia), 1N4148; 1N4448 High-speed diodes datasheet (2004 Aug 10) — VRRM 100 V; IF 200 mA continuous; IFRM 450 mA; VF ≤ 1 V at 10 mA; t_rr ≤ 4 ns