Français

Lessons · Lesson C2 · Components · 45 min

Transistors, MOSFETs and diodes

Let a tiny signal from your board switch a bigger current: an NPN transistor, a logic-level MOSFET, and the diode that protects them from a motor. About 45 minutes.

A tiny finger on a big floodgate

A pin of your board can light an LED, but a motor, a long LED strip or a relay coil asks for much more current than a pin is built to give. Wire a small motor straight to a pin and there is a good chance of damaging the board [1].

The fix is a switch that another signal can press. A small hand on a lever opens a huge sluice gate: little effort in, big flow out. That is what a transistor does [3]. Your pin presses the lever, and a separate battery pack pushes the real current.

In this lesson you will:

  1. switch a load with an NPN transistor,
  2. do the same with a logic-level MOSFET,
  3. add the diode that keeps a motor from hurting them.

Keep everything small and safe: a small DC motor and a battery pack of 6 V at most. Never use wall power here.

A tiny finger on a big floodgate A canal drawn in section, flat. On the left, a deep basin of water; in the middle, a heavy sluice gate in its frame, lifted a little; water rushes under it to the right. A long lever on a pivot holds the gate: a tiny finger presses the far end of the lever down, and the gate end goes up. Label on the lever: pin, small signal. Label on the water: battery pack, big current. Below: little effort in, big flow out; that is what a transistor does. FIG. 1 — SMALL SIGNAL, BIG CURRENTpin: small signalbattery pack: big currentpushes the waterbig flow outheavy gateLittle effort in, big flow out: that is what a transistor does.The pin presses the lever. A separate battery pack pushes the real current.Small and safe: a small DC motor and 6 V at most. Never wall power.
Tap the diagram to open it full screen.

The NPN transistor

A transistor has three legs: collector (C), base (B) and emitter (E) [3]. The big current flows from collector to emitter, but only while a small current flows into the base [1][3]. In a switch circuit, the transistor is either off (no base current) or fully on, called saturation, where it acts like a closed switch [3].

A common part is the PN2222. Adafruit lists it as an NPN that can switch up to 40 V at peak currents of 1 A, “not continuously”, with a gain of about 100 [2]. Keep your load well under that. Its legs follow the E-B-C order on Adafruit’s part [2], but pin order can differ between makers, so check the drawing in your own datasheet before you wire.

The base resistor. Without a resistor the base would take too much current, so a resistor limits it, just like for an LED [1]. When the transistor is on, its base sits about 0.6 V above the emitter [3]. With a 3.3 V pin and 330 Ω, Ohm’s law (I = V ÷ R) gives I ≈ (3.3 − 0.6) ÷ 330 ≈ 8 mA. SparkFun says 1 to 10 mA is usually enough for the base, to be checked on the datasheet [3]. When fully on, the drop across the transistor is small, often about 0.05 to 0.2 V [3]. To be fully on, though, the base needs enough current: with a gain of 100, 1 mA into the base can give 100 mA at the collector [3], and to be safe you count on much less. So keep the NPN for small loads (about 100 mA). For a toy motor, the MOSFET below is the better choice.

Wiring the NPN (low side, the load sits between the plus of the pack and the collector):

From To
GPIO 26 330 Ω resistor, then the base
emitter GND of the board and minus of the pack
collector one wire of a small load under 100 mA (a buzzer, for example), not the motor
other wire of the load plus of the pack
An NPN transistor switches a small buzzer Schematic, left to right. GPIO 26 of the ESP32 goes through a 330 ohm resistor to the base of an NPN transistor, a PN2222. The emitter goes down to a bold ground rail, labelled common ground, that joins the ESP32's GND and the pack's minus. The collector goes up to a small buzzer, a load under 100 mA, and the buzzer's other lead goes to the plus of the battery pack, 3 AA cells, 4.5 V, 6 V at most. No motor on this version. Base current: about (3.3 minus 0.6) divided by 330, about 8 mA. Leg order: E, B, C on Adafruit's PN2222; check your own datasheet. FIG. 2 — NPN SWITCH, LOW SIDEESP32DevKitC26GND+3 × AA4.5 V6 V maxcommon groundpack +330 ΩI ≈ (3.3 − 0.6) ÷ 330≈ 8 mA into the baseBCEsmall buzzerunder 100 mAPN2222NPNNo motor here: the NPN is for small loads (about 100 mA).Leg order: E-B-C on Adafruit's PN2222. Check your own datasheet.
Tap the diagram to open it full screen.

The logic-level MOSFET

A MOSFET is the other common electronic switch. It has a gate (the control), a drain and a source. For an N-channel one, the load goes on the drain and the source goes to ground. It is a good fit for motors: N-channel power MOSFETs are made to switch a lot of power [4], and the gate is driven by a voltage.

The trap: “fully on”. A MOSFET starts to conduct at its threshold voltage, but it is only fully open at a higher gate voltage. Its on-resistance, written Rds(on), depends on the gate voltage [4]. So you need a logic-level MOSFET, sold as working from 3.3 V signals. In its datasheet, the on-resistance should be listed at a low gate voltage (4.5 V or less, the lower the better), not only at 10 V. A part made for much higher gate voltages can stay far from fully on at 3.3 V and heat up. Do not trust the threshold alone.

An example: Adafruit describes the IRLB8721 as an N-channel power MOSFET (30 V) with a threshold under 2.5 V that can be driven from 3.3 V logic, and an on-resistance as low as 8.7 mΩ, depending on the gate voltage [4]. That lowest figure is for a gate voltage well above 3.3 V. At 3.3 V the resistance is higher, but for a small motor like ours the part stays cool. Any logic-level N-MOSFET with similar numbers does the job. At the time of writing that page said “out of stock”, so check availability and read the datasheet of the part you buy.

The gate pull-down. A pin that nothing drives is floating: it can pick up any value [6]. A pull-down resistor to ground makes sure it reads low [6]. While the board starts, GPIO 26 is neither an output nor pulled up or down [7]. So we add a 10 kΩ resistor from gate to GND. The MOSFET stays off while the board starts, is reset or is being programmed, instead of letting the motor jump on by itself.

Wiring the MOSFET (low side):

From To
GPIO 26 gate
gate 10 kΩ resistor to GND (pull-down)
source GND of the board and minus of the pack
drain one wire of the motor
other wire of the motor plus of the pack
across the two motor wires 1N4001 diode, stripe on the wire to the plus of the pack (see screen 4)

Read the pin order (gate, drain, source) on the datasheet of your own part: it is not the same for every package.

A logic-level MOSFET switches the motor Schematic, same layout as the NPN one. GPIO 26 goes straight to the gate of a logic-level N-channel MOSFET. A 10 kilohm resistor goes from the gate to the ground rail: the pull-down that keeps the MOSFET off while the board starts. The source goes to the bold ground rail, the common ground of the ESP32 and the pack's minus. The drain goes to the motor, and the motor's other wire to the plus of the pack, 3 AA, 4.5 V. A flyback diode, a 1N4001, sits across the motor, its bar, the stripe, on the plus side. A note box: datasheet, Rds(on) at the gate voltage you use. FIG. 3 — MOSFET SWITCH, LOW SIDEESP32DevKitC26GND+3 × AA4.5 V6 V maxcommon groundpack +10 kΩpull-downGDSM1N4001bar (stripe) to +motorlogic-levelN-MOSFETdatasheet: Rds(on) at thegate voltage you usePin order (G, D, S) depends on the part:read your own datasheet.
Tap the diagram to open it full screen.
The gate opens the valve (interactive)
The gate opens the valve (interactive) Interactive simulation with illustrative numbers. Left, the motor current drawn as water in a pipe: from the pack's plus, through the motor, through a valve, the MOSFET, to ground. The gate voltage slider, from 0 to 3.3 V, lifts the valve and the flow grows. Right, a graph of motor current against gate voltage for two example parts: a logic-level MOSFET, fully open well before 3.3 V, and a part made for higher gate voltages, still only half open at 3.3 V. A marker shows the current setting. simulation, illustrative numberspack + 4.5 VMMOSFET= valve03.3 Vgatecurrentlogic-levelnot logic-level

Simulation with illustrative numbers, not a measurement.

gate 0.0 V · valve 0 % open · motor current about 0 mA

Closed: below the threshold, no current flows.

Read Rds(on) in the datasheet at the gate voltage you use, not only at 10 V.

This is the starting state: the controls need JavaScript.


The flyback diode

A motor is a coil of wire. A coil does not like its current to stop suddenly: when you switch it off, it produces a spike of voltage, possibly a large negative one [5]. That spike can damage your transistor or your board [1].

A diode lets current go in one direction only, from its anode to its cathode [5]. In the symbol, the triangle points the way the current can go and the bar is the cathode, the end with a stripe on the real part [5]. A flyback diode is placed across the coil and gives the spike a safe path to die out [5]. In other words, it shorts out the reverse current from the motor [1].

Which way round? While the motor runs normally, the diode must do nothing, so it must block. Put the stripe (cathode) on the plus wire of the pack and the other end on the wire that goes to the transistor or the drain. If you swap it, the diode makes a short circuit across the pack as soon as the transistor switches on: the motor stays still and the diode, the transistor and the cells can get hot. Always check that the stripe goes to the plus side before you switch on.

Which part? A 1N4001 is rated for 1 A and 50 V [5]. The smaller 1N4148 is meant for signals up to about 200 mA [5]. For a small motor, take the 1N4001.

The flyback diode gives the spike a safe path Two panels, the moment the transistor switches off, drawn as an open switch under the motor. a, with the diode: a diode across the motor's two wires, its bar towards the plus of the pack. A red dashed arrow loops down through the motor and up through the diode: the spike dies out in that loop. Tick: safe. b, no diode: the same circuit without any diode. A spike mark at the open switch: the voltage jumps and hits the transistor. Cross. Bottom, the symbol and the real part side by side: the triangle points the way current can go; the bar is the cathode, the end with the stripe on the real 1N4001; the stripe goes to the plus wire. FIG. 4 — WHEN THE MOTOR SWITCHES OFFaWith the diodepack +pack −+Mtransistor:just offmotorbar to +safe: the spike dies out in the loopbNo diodepack +pack −+Mtransistor:just offmotorspike!hits the transistorrisky: nothing catches the spikecSymbol and real partanodecathodestripeTriangle: the way current can go.Bar = cathode = stripe.Stripe to the pack's + wire.
Tap the diagram to open it full screen.

Build it: a motor on a pin

Gather: a small DC motor, a battery holder with a switch (3 AA cells, 4.5 V; 6 V at most in all), a 1N4001 diode, and the logic-level MOSFET with its 10 kΩ pull-down. The PN2222 with its 330 Ω resistor works only for a tiny load under about 100 mA, such as an LED strip segment or a buzzer, not for the motor. Build one version at a time.

Rules for this circuit.

  • The board stays on its USB cable. The motor has its own pack. Only the grounds are joined. Voltages are measured between two points, and the transistor or MOSFET needs both to share the same reference, called a common ground. Never connect the pack’s plus to any pin of the board.
  • Keep the pack at 6 V or less and the load small. Keep the shaft free: do not hold or block it.
  • Switch the pack off while you wire. Check the diode’s stripe before you switch on.

Upload this sketch and open the Serial Monitor at 115200 baud:

// Tinker Mission, lesson C2: switch a small motor with a GPIO pin (logic-level N-MOSFET or NPN transistor)
// Board: ESP32 DevKitC, "esp32 by Espressif" 3.3.x.
// The motor has its OWN battery pack (6 V maximum). The board only sends a tiny control signal.
//
// MOSFET wiring (low side):
//   GPIO 26 -> gate                       10 kOhm resistor from gate to GND (keeps it OFF while the board resets)
//   source -> GND of the board AND minus of the battery pack (common ground)
//   drain -> one wire of the motor        other wire of the motor -> plus of the battery pack
//   1N4001 diode across the motor: stripe (cathode) to the plus wire, other end (anode) to the drain wire
// NPN (PN2222) variant, only for a small load under 100 mA, not the motor: GPIO 26 -> 330 ohm -> base; emitter -> GND; collector -> load.
// Open the Serial Monitor at 115200 baud.

const int MOTOR_PIN = 26;

void setup() {
  Serial.begin(115200);
  pinMode(MOTOR_PIN, OUTPUT);
  digitalWrite(MOTOR_PIN, LOW);   // start OFF
}

// In loop(), only analogWrite drives the pin: once analogWrite has used a pin, digitalWrite is ignored on it.
void loop() {
  Serial.println("Full speed");
  analogWrite(MOTOR_PIN, 255);    // 255 = always on
  delay(2000);

  Serial.println("Off");
  analogWrite(MOTOR_PIN, 0);      // 0 = always off
  delay(1500);

  Serial.println("About half speed (fast on-off switching)");
  analogWrite(MOTOR_PIN, 128);    // 0 = always off, 255 = always on
  delay(2000);

  Serial.println("Off");
  analogWrite(MOTOR_PIN, 0);
  delay(1500);
}

Download the sketch folder (.zip)

The motor should run, stop, run slower, and stop, over and over. analogWrite(pin, 128) switches the output on and off very fast, so the motor sees about half the power. The same sketch works with the NPN version, for a load under about 100 mA.

C2 build: MOSFET, pull-down, diode, motor on its own pack Breadboard view, top. The DevKitC sits off the breadboard, USB on the left, powered by its USB cable; female jumpers go on its pins. The breadboard's top rails carry the motor supply: a holder of 3 AA cells, 4.5 V, with a switch, off while you wire. 1 red, pack plus to the top plus rail; 2 black, pack minus to the top minus rail. 3 black, a thick wire labelled common GND, from the top minus rail round the left of the breadboard to a GND pin on the bottom row of the DevKitC. A logic-level MOSFET stands in rows 5, 6 and 7: gate, drain, source, as on many TO-220 parts; check your own. 4 yellow, GPIO 26 to the gate row, 5. A 10 kilohm resistor from row 2 to row 5, and 5 black, row 2 to the minus rail: the gate pull-down. 6 black, the source row, 7, to the minus rail. The motor's two wires go to row 6, the drain, and row 11. 7 red, the plus rail to row 11. A 1N4001 diode lies from row 6 to row 11, its stripe on row 11, the plus side. The plus rail feeds only the motor and the diode, never a pin of the board. FIG. 5 — BREADBOARD BUILD, MOTOR ON ITS OWN PACKENBOOT5VCLKCMDD0D3D1D215132GND0124141627172652518331932GND352134RXVNTXVP22EN233V3GND+−−+jihgfedcba15101518bottom rails: not usedGDSMOSFET10 kΩMmotor3 × AA, 4.5 V+++ONOFFcommon GNDGND26GNDGNDUSB cable:powers theboard1234567MOSFET: rows 5 (G), 6 (D), 7 (S). 10 kΩ: rows 2 to 5.1N4001: rows 6 to 11, stripe on 11.Motor wires: rows 6 and 11.1red: pack + → top + rail2black: pack − → top − rail3black: − rail → GND pin (bottom row): common GND4yellow: GPIO 26 → gate (row 5)5black: pull-down (row 2) → − rail6black: source (row 7) → − rail7red: + rail → row 11 (motor, diode stripe)The + rail feeds only the motor and the diode, never a pin of the board. Pack off while you wire; check the stripe.G, D, S as on many TO-220 MOSFETs: read the pin order in the datasheet of your own part.
Tap the diagram to open it full screen.

Try your own changes

Change one thing, then observe.

  1. Slower and faster. Change 128 to 60, then to 200. How does the motor respond?
  2. The pull-down. With the board unplugged and the pack off, look at the circuit: where does the pull-down go? What would the gate be connected to without it?
  3. Find the stripe. Pack off, look at your diode: which wire of the motor does the stripe face? Trace the path the spike takes through the motor and the diode when the motor switches off.
  4. Other loads. Replace the motor with a small buzzer or an LED strip made for your pack’s voltage. Is a diode still useful?

When it does not work

  • The motor does not move. Check the pack is on and fresh. Check that the board’s GND and the pack’s minus are joined. Check the order of the three legs of your part in its datasheet.
  • The motor is always on. On a MOSFET, check that drain and source are not swapped (its built-in diode then lets current through all the time), and that the gate goes to GPIO 26. A part that overheated can also stay stuck on: replace it.
  • The motor turns slowly, and the part gets warm. With a MOSFET, it may not be fully on at 3.3 V: switch to a logic-level part [4]. With an NPN, the load is too big for it: use the MOSFET for a motor. On an NPN, also check that collector and emitter are not swapped.
  • The board resets when the motor starts. Keep the motor on its own pack, not the board’s supply. A diode in the wrong direction shorts the pack: switch the pack off at once and turn the diode round. Always check the stripe goes to the plus side.
  • The part gets hot. Switch the pack off. The load is probably too big for the part [2][4].
  • Nothing in the Serial Monitor. Set it to 115200 baud.

Check yourself

Three short questions. Nothing is saved, take your time.

  1. Why do you put a diode across a motor that a transistor switches?

    • To make the motor turn faster
    • To let the battery pack charge up
    • When the motor is switched off it makes a voltage spike, and the diode gives that spike a safe path
    Show the answer

    When the motor is switched off it makes a voltage spike, and the diode gives that spike a safe path. Switching off a motor gives a spike of voltage that can damage the transistor or the board, and the diode shorts out that reverse current [1]. A diode across an inductive load gives the spike a safe path to die out [5].

  2. You want to switch a load with a MOSFET driven by a 3.3 V pin. What do you look for?

    • Any MOSFET, the bigger the better
    • A logic-level MOSFET, sold as working from 3.3 V logic, with its on-resistance listed at a low gate voltage
    • A MOSFET with a blue case
    Show the answer

    A logic-level MOSFET, sold as working from 3.3 V logic, with its on-resistance listed at a low gate voltage. A MOSFET's resistance depends on its gate voltage, so a part made to be driven from 3.3 V logic matters [4]. The lower the gate voltage at which the datasheet lists it, the better for a 3.3 V pin.

  3. What does the resistor between the GPIO pin and the transistor's base do?

    • It limits the small current flowing into the base
    • It makes the motor run backwards
    • It stores energy for the motor
    Show the answer

    It limits the small current flowing into the base. Just as with an LED, the resistor limits the current going into the base [1]. SparkFun says about 1 to 10 mA is usually enough for the base, to be confirmed on the datasheet [3].


In short

  • A pin gives a small signal. A transistor or MOSFET lets that signal switch a bigger current from a separate supply [1][3].
  • NPN: a base resistor limits the base current (about 1 to 10 mA) [1][3]. The PN2222 is meant for modest loads [2].
  • MOSFET: choose a logic-level part and check its on-resistance at your gate voltage [4]. Add a 10 kΩ pull-down from gate to GND [6].
  • A flyback diode goes across a motor or coil, with its stripe on the plus side, to absorb the voltage spike [1][5].
  • Join the grounds, keep the pack at 6 V or less, and never connect the pack’s plus to the board.

Next steps: motors in both directions with a driver (A3), and smoothing the supply with a capacitor (C1).


Sources

Show the 7 sources
  1. Adafruit, “Arduino Lesson 13. DC Motors”, page “Transistors” (a small DC motor may use more current than an Arduino pin can handle and could damage it; a small transistor such as the PN2222 acts as a switch; collector-emitter current flows only when a small current flows into the base; the resistor limits the base current as for an LED; a diode across the motor shorts out the negative voltage spike when it is turned off) — https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/transistors
  2. Adafruit, “NPN Bipolar Transistors (PN2222) - 10 pack”, product 756 (standard EBC pinout for that part; up to 40 V at peak currents of 1 A, “not continuously”; DC gain about 100; datasheet linked) — https://www.adafruit.com/product/756
  3. SparkFun, “Transistors” (collector, base and emitter pins; a small base current controls a larger flow; saturation is the on mode and acts like a short circuit; base-emitter drop about 0.6 V; collector-emitter saturation voltage about 0.05 to 0.2 V; 1 mA to 10 mA is usually enough for the base, check the datasheet) — https://learn.sparkfun.com/tutorials/transistors
  4. Adafruit, “N-channel power MOSFET [30V / 60A]”, product 355 (IRLB8721: TO-220; threshold voltage below 2.5 V so it can be controlled from 3.3 V logic; on-resistance as low as 8.7 milliohm depending on the gate voltage, check the datasheet; the page showed “out of stock” when read) — https://www.adafruit.com/product/355
  5. SparkFun, “Diodes” (current flows from anode to cathode; the symbol is a triangle against a line; a flyback diode across an inductive load such as a motor gives a voltage spike a safe path; 1N4001 rated 1 A and 50 V; 1N4148 for signals up to about 200 mA) — https://learn.sparkfun.com/tutorials/diodes
  6. SparkFun, “Pull-up Resistors” (an input pin that is connected to nothing floats and its state is unknown; a pull-up or pull-down resistor ensures a high or low state; the pull-down resistor goes to ground) — https://learn.sparkfun.com/tutorials/pull-up-resistors
  7. Espressif, “ESP32 Series Datasheet” v5.3, table “IO MUX” (column “At Reset”: GPIO 26 has output and input disabled, no pull-up or pull-down) — https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf

Pinch or double-tap to zoom, swipe to change diagram.Scroll with Ctrl or double-click to zoom. Arrow keys change diagram.