Mastering Arduino Part 14: PWM and Switching Real Loads

Mastering Arduino Part 14 cover: PWM and Switching Real Loads, with an Arduino board, a transistor switch, a DC motor with a diode, and a separate power supply

Mastering Arduino Part 14: PWM and Switching Real Loads

Picture a wall switch that somebody can flip several hundred times a second. The lamp it controls never receives a half voltage: at any instant the switch is closed or open. If the switch spends most of each cycle closed, the lamp looks bright, and if it spends most of each cycle open, the lamp looks dim. An Arduino pin driven by analogWrite() is that switch, with one serious restriction. The switch built into the pin is far too small to carry a motor, so this part adds a second, larger switch for the pin to operate.

The technique is called pulse-width modulation (PWM): a digital output switches on and off at a steady rate, and the share of each cycle spent on is changed to control how much a load receives [1]. A load is whatever consumes the power at the far end of the wire, such as an LED, a lamp, a relay coil, or a motor. Switching a load means using one small electrical signal to connect and disconnect a larger current that comes from somewhere else.

Part 13 moved data between chips, where every signal carried information and almost no power. A motor or a relay asks for current that an Uno pin is not rated to deliver, and its coil pushes back with a voltage spike each time the current is cut off. Wiring such a part straight to a pin can damage the microcontroller. The circuit that prevents this needs only a transistor, one or two resistors, and a diode, and each of them has a specific job.

Part 3 introduced analogWrite(), and Part 4 used it to build a knob-controlled LED on D9. We start from that LED and then go further: the duty-cycle arithmetic, the six PWM pins and their two frequencies, the current limits of a pin, a transistor switch, a logic-level MOSFET switch, the flyback diode, and the shared ground between two power supplies. The practical project is a motor speed control with a knob. Everything runs on an Uno R3 and a 5V supply. Mains voltage is outside this series. Reversing a motor is the subject of Part 16, and hobby servos are covered in Part 17.

Bill of Materials

Component Description Buy on Amazon Buy on Temu Buy on SparkFun Buy on Seeed Studio Datasheet
Arduino Uno R3 The controller board. Any Uno R3 or compatible board works. Amazon Link Not yet available SparkFun Link Seeed Link N/A
IRLZ44N logic-level MOSFET N-channel, TO-220 package. The motor switch in the project. Not yet available Not yet available Not yet available Not yet available IRLZ44N datasheet
2N2222 NPN transistor The relay coil driver. The Amazon item is an assortment that includes the 2N2222. Check the pin order of the part you receive. Amazon Link Temu Link Not yet available N/A P2N2222A datasheet
1N4001 diodes (×2) Flyback diodes, one for the motor and one for the relay coil. Amazon Link Temu Link SparkFun Link N/A 1N4001 datasheet
5V SPDT relay Bare relay with a 5V coil, used in Exercise 4. The linked SparkFun relay has a 56Ω coil. Not yet available N/A SparkFun Link N/A JZC-11F relay datasheet
3–6V brushed DC motor A small two-wire hobby motor whose listing states its stall current. Not yet available Not yet available Not yet available Not yet available N/A
5V DC power supply, 2A or more The separate load supply. The linked Amazon supply is rated 5A and includes a screw terminal. The Seeed supply is rated 4A. Amazon Link Temu Link Not yet available Seeed Link N/A
DC barrel jack to screw terminal adapter Needed if your supply ends in a barrel plug with no screw terminal. Match the plug size. Not yet available Not yet available Not yet available Not yet available N/A
10kΩ potentiometer The speed knob. Amazon Link Temu Link SparkFun Link N/A N/A
Resistor kit 220Ω for the LEDs, 330Ω for the gate and base, 10kΩ for the gate pull-down. Amazon Link Temu Link SparkFun Link Seeed Link N/A
5mm LEDs One for the dimming exercises, one for the relay contact. Amazon Link Temu Link SparkFun Link Not yet available N/A
Breadboard & jumper wires For all of the builds. Amazon Link Temu Link SparkFun Link Seeed Link N/A

The products linked above may contain affiliate links. The Makers Workbench earns from qualifying purchases when these links are used.

Buy the MOSFET by its full part number. Parts with similar names, including the IRF520 found on many ready-made driver modules, behave differently when an Arduino pin drives them, and a later section shows why. Transistors sold as "2222" also come with different pin orders, so find the datasheet for the exact marking before wiring one.

How PWM Works

Duty Cycle and Average Voltage

A PWM signal repeats. One full repetition, an on-time followed by an off-time, is the period, written T. The frequency, f, is the number of periods in one second, measured in hertz (Hz), so T is 1 divided by f. The duty cycle, D, is the fraction of the period for which the signal is on:

D = ton / T

Here ton is the on-time within one period. A signal that is on for 0.5 milliseconds (ms) out of every 2ms has a duty cycle of 0.25, or 25%. analogWrite() takes the duty cycle as a whole number from 0 to 255, where 0 is always off and 255 is always on [1], so the duty cycle you command is close to the value divided by 255.

If the signal swings between 0V and a high voltage Vhigh, its average over a full period is:

Vavg = D × Vhigh

For analogWrite(9, 64) on a 5V board, D is 64 / 255, or about 0.251, and the average is 0.251 × 5V, about 1.25V. As a second check, 25% of a 2.04ms period is about 0.51ms at 5V and 1.53ms at 0V, which also averages to 1.25V.

Three square waves at 25, 50, and 75 percent duty cycle, each with a dashed line at its average voltage

The average is a calculation about the waveform. The pin itself is still at one of two levels at every instant, and a multimeter that shows 1.25V on a PWM pin is reporting that average. An LED flashes at full current during each on-time and your eye blends the flashes, which is why the Part 4 LED appears to dim. A resistive load such as a small heater responds to the average power. A motor smooths the pulses with its own inductance and spinning mass, but its speed also depends on its load, so 50% duty does not promise half speed. Producing a steady in-between voltage requires either a digital-to-analog converter (DAC), which the Uno R3 does not have, or a filter, which is the subject of Part 33.

analogWrite() on the Uno

analogWrite() works on six pins of the Uno R3: 3, 5, 6, 9, 10, and 11, each marked with a tilde (~) on the board [2]. The function sets the pin as an output on its own, and it has no connection to the analog input pins or to analogRead() [1]. The wave it starts continues without further code until the next analogWrite(), digitalWrite(), or digitalRead() call on the same pin [1].

Behind the function is a timer, a counter inside the ATmega328P that runs at a fixed rate and flips a pin when its count passes the value you supplied. Because the timer does the work, loop() is free to read a knob or print to Serial while the pulses continue. The hand-made alternative, digitalWrite() HIGH, wait, digitalWrite() LOW, wait, ties the processor to the waveform, and any other work stretches the timing.

The Arduino core, which is the code behind every built-in function, treats the two ends of the range specially. A value of 0 is written to the pin as a plain LOW and a value of 255 as a plain HIGH [3]. On a pin with no PWM timer, any value below 128 becomes LOW and any value from 128 up becomes HIGH, with no error message [3]. That second rule explains a motor that stays off for the lower half of a knob's travel and runs at one speed for the upper half.

Timers and Frequencies

The Uno has three timers, and each one serves two of the six PWM pins [3]. The Arduino reference states 490Hz for the PWM pins, except pins 5 and 6, which run at 980Hz [2].

Pins Timer Stated frequency Also used by
5, 6 Timer 0 980Hz millis() and delay()
9, 10 Timer 1 490Hz The Servo library
3, 11 Timer 2 490Hz tone()

The six Uno PWM pins grouped by timer, with each group's frequency and the feature that shares the timer

Both figures come from the 16MHz system clock. The core divides that clock by 64 for all three timers [3]. Timer 0 counts from 0 up to 255 and starts again, a mode called fast PWM, so one period takes 256 counts:

f = 16,000,000 / (64 × 256) = 976.6Hz

Timers 1 and 2 count up to 255 and then back down, a mode called phase-correct PWM, so one period takes 510 counts [3] [4]:

f = 16,000,000 / (64 × 510) = 490.2Hz

The reference rounds these to 980Hz and 490Hz. Part 3 described the rate loosely as somewhere around 500 to 1,000 times a second, and these are the two exact settings inside that range. Both rates are also within the range of human hearing, so a motor driven this way may produce a whine. Changing the frequency means writing to timer registers, which Part 46 covers.

Sharing a timer has consequences. The Arduino documentation says pins 5 and 6 can produce a higher duty cycle than requested, mostly at low values around 0 to 10, because Timer 0 also keeps time for millis() and delay() [1]. The mechanism is the fast PWM mode the core selects for that timer. The output stays on for one count more than the stored value, so a value of 64 is on for 65 of the 256 counts, and a stored 0 would still leave a narrow spike in each period [4]. The current core avoids the spike by writing a plain LOW for a value of 0 [3], although the documentation still warns that 0 may not fully turn those two pins off [1]. The Servo library disables analogWrite() on pins 9 and 10 on boards other than the Mega, whether or not a servo is on those pins [5]. The tone() function uses Timer 2 on the Uno [3], so it interferes with PWM on pins 3 and 11. This part uses pin 9, which is free as long as the sketch does not include the Servo library.

PWM on Other Boards

The pin list and frequency change with the board, so check them before moving a sketch [2].

Board PWM pins Stated frequency
Uno R3, classic Nano 3, 5, 6, 9, 10, 11 490Hz (pins 5 and 6: 980Hz)
Uno R4 Minima and WiFi 3, 5, 6, 9, 10, 11 490Hz
Mega 2–13, 44–46 490Hz (pins 4 and 13: 980Hz)
Nano Every, Uno WiFi Rev2 3, 5, 6, 9, 10 976Hz
MKR boards 0–8, 10, A3, A4 732Hz

The wiring and current figures in the rest of this part are for the 5V Uno R3. A 3.3V board drives a transistor with less voltage, so its switching parts have to be chosen again.

What a Pin Can Supply

PWM controls timing, and it does nothing to increase the current a pin can deliver. The ATmega328P datasheet lists an absolute maximum of 40mA per input/output pin, and 200mA through the chip's VCC and GND pins [4]. An absolute maximum is a damage threshold: stress beyond it may permanently harm the chip, and the rating is not a promise of normal operation up to that point [4].

The figure to design with is lower. The datasheet guarantees the output voltage of a pin at a test current of 20mA with a 5V supply. At that current a HIGH pin is at least 4.2V up to 85°C, so it is already below a full 5V [4]. Groups of pins also share limits. The total current sourced by each of two pin groups should not exceed 150mA, and the total sunk by each of three groups should not exceed 100mA [4]. Sourcing is current flowing out of a HIGH pin, and sinking is current flowing into a LOW pin.

Limit Value Meaning
Output test condition per pin 20mA Voltage levels are guaranteed here
Absolute maximum per pin 40mA Damage threshold
Sourced total per pin group 150mA Applies to each of two groups
Sunk total per pin group 100mA Applies to each of three groups
Absolute maximum through VCC and GND pins 200mA Whole-chip supply path

Compare those numbers with real loads. The 5V relay used in this part has a 56Ω coil and draws 90mA [6], more than twice the 40mA damage threshold. Other 5V relays differ, so read the coil figures for yours. A DC motor draws its largest current when it is powered and not turning, which includes the instant it starts. A turning motor generates its own opposing voltage, called back emf, that reduces the current, and at a standstill there is none [7]. The current in that condition is the stall current. If the motor listing gives it, use that figure. If it does not, measure the resistance between the motor terminals with the power disconnected and apply Ohm's law as an estimate. A winding of 10Ω, a value chosen here for clean arithmetic, would draw 5V / 10Ω = 0.5A, which is 12.5 times the pin's absolute maximum.

The Uno's 5V pin is not the answer for a motor either. It shares its source with the microcontroller, and a motor that pulls the voltage down as it starts can reset the board. We give the load its own supply and let the pin do nothing more than control a switch.

Switching a Load on the Low Side

The Low-Side Switch

A transistor is a three-terminal semiconductor part in which a small signal on one terminal controls the current between the other two. In a low-side switch, the transistor sits between the load and ground. The load's other terminal connects straight to the positive side of its supply. When the transistor conducts, the path is complete and current flows from the supply, through the load, through the transistor, to ground. When the transistor is off, the path is broken.

The low side suits an Arduino because the control signal is measured from the ground the transistor connects to. A 5V pin can therefore switch the transistor no matter what voltage feeds the load, within the transistor's ratings. Switching on the positive side, called a high-side switch, needs a different transistor and a more involved drive circuit, so this part stays on the low side.

Two Supplies and One Ground

The circuit now has two power sources. The Uno runs from USB, and the load runs from its own 5V supply. Their positive terminals stay separate. Their negative terminals must be joined, creating a common ground.

A voltage is always a difference between two points. When the pin goes HIGH, it is about 5V above the Uno's ground. The transistor responds to the voltage between its control terminal and its own ground-side terminal, which belongs to the load circuit. Without a wire between the two grounds, the pin's signal has no defined voltage at the transistor and no path back, and the load switches erratically or not at all.

A common ground wire joining the Uno and the load supply, beside the same circuit with the wire missing

The NPN Transistor Switch

An NPN bipolar junction transistor has terminals called the base, collector, and emitter. For a low-side switch, the emitter goes to ground, the collector goes to the load, and a small current into the base allows a larger current to flow from collector to emitter. The base needs a resistor, because the base-to-emitter path behaves like a diode and would otherwise draw far too much from the pin.

A switch should be fully on, which for this transistor is called saturation: the voltage left between collector and emitter is small. The P2N2222A datasheet specifies that voltage as 0.3V at most with 150mA of collector current and 15mA of base current [8]. Both of its saturation tests supply a base current of one tenth of the collector current [8], and we copy that test condition when choosing the resistor. The relay coil draws 90mA [6], so the base current target is:

IB = IC / 10 = 90mA / 10 = 9.0mA

IC is the collector current, and IB is the base current. The resistor RB receives whatever voltage is left after the base-emitter junction takes its share, VBE:

RB = (VOH − VBE) / IB

VOH is the voltage of a HIGH pin. For a cautious result we use its 4.2V minimum [4] and the largest saturation VBE on the sheet, 1.2V [8]: (4.2V − 1.2V) / 9.0mA is about 333Ω. A resistor at or below that value meets the target, so we use 330Ω, which gives about 9.1mA in that worst case. A relay that draws more than 90mA needs this calculation repeated. In the other extreme, a full 5V pin and a 0.6V junction [8] give (5V − 0.6V) / 330Ω = 13.3mA, still inside the 20mA test condition.

The transistor itself stays cool. Its dissipation is at most 0.3V × 90mA, about 27mW (milliwatts), against a 625mW rating in free air [8]. Its collector current rating is 600mA [8], but the air rating limits it well before that figure if the saturation voltage rises, so the motor goes to a different part.

An NPN low-side switch driving a relay coil from a separate supply, with a 330Ω base resistor and a flyback diode

The Logic-Level MOSFET

A MOSFET (metal-oxide-semiconductor field-effect transistor) has a gate, a drain, and a source. In an N-channel low-side switch, the source goes to ground, the drain goes to the load, and the voltage between gate and source controls the path from drain to source. The gate is insulated and acts like a small capacitor, so it draws current while its voltage is changing and almost none while it holds steady.

Two voltage figures on a MOSFET datasheet are easy to confuse. The gate threshold voltage, VGS(th), is the gate voltage at which the part barely begins to conduct, measured at a tiny current such as 250µA (microamps, millionths of an amp) [9]. The on-resistance, RDS(on), is the resistance between drain and source when the part is properly on, and it is guaranteed only at the gate voltages the datasheet lists. A logic-level MOSFET is one with a guaranteed on-resistance at a gate voltage that a logic pin can supply. Here are three parts a beginner is likely to meet.

Part Gate threshold On-resistance guaranteed at Continuous drain current rating
IRLZ44N [9] 1.0V to 2.0V at 250µA 0.035Ω at 4V, 0.025Ω at 5V, 0.022Ω at 10V 47A at 25°C case, 10V gate
IRF520N [10] 2.0V to 4.0V at 250µA 0.20Ω at 10V only 9.7A at 25°C case, 10V gate
2N7000 [11] 0.8V to 3.0V at 1mA 5.3Ω at 4.5V and 75mA, 5Ω at 10V and 500mA 200mA

Gate threshold and the gate voltages at which on-resistance is guaranteed for the IRLZ44N, IRF520N, and 2N7000

The IRF520N shows why the threshold is the wrong number to shop by. A sample at the top of its range conducts only 250µA with 4V on the gate, and the datasheet promises nothing about its on-resistance below 10V [10]. It may switch a light load from a 5V pin, but nobody can calculate from the sheet how hot it will get. The 2N7000 does have a low-voltage figure, for a small current only, which suits an LED and rules out a motor [11]. The IRLZ44N has guaranteed values at 4V and 5V [9], so it is our motor switch.

When the MOSFET is fully on, it loses power as heat according to its current, ID, and its on-resistance:

P = ID2 × RDS(on)

At 1A, the ceiling for this build, using the 4V figure of 0.035Ω because a HIGH pin can sit near 4.2V under load, P = 1A × 1A × 0.035Ω = 0.035W. The same sheet gives 62°C per watt from the junction to the surrounding air [9], which makes the rise about 2°C, so no heatsink is needed at this current. Treat the result as optimistic: the on-resistance was measured at 25°C with very short pulses [9], it rises as the part warms, and switching adds a further loss that this equation leaves out. The 47A headline rating assumes a case held at 25°C and a 10V gate [9], and it says nothing about what a breadboard can carry. Breadboard contacts and thin jumper wires are the weak point, so keep this build to motors with a stall current under 1A.

Question NPN transistor Logic-level MOSFET
Controlled by Base current Gate voltage
Pin current while on Steady, set by the base resistor Almost none
Part here P2N2222A IRLZ44N
Load here 90mA relay coil Motor, under 1A

Gate Resistor and Pull-Down

The MOSFET circuit uses two resistors. A gate resistor of 330Ω sits between pin 9 and the gate. At the moment the pin changes level, the empty gate capacitance looks like a short circuit, and the resistor limits the current to about 5V / 330Ω = 15mA, inside the 20mA test condition. The cost is a short delay. The IRLZ44N needs at most 48nC (nanocoulombs, a measure of electric charge) to bring its gate to 5V under the datasheet's test conditions [9]. Treating the gate as a capacitor of 48nC / 5V, about 9.6nF (nanofarads), charged through 330Ω gives a time constant of about 3µs (microseconds), so charging takes roughly 10µs. That is under 1% of the 2,040µs period at 490Hz. This is an estimate, and it is why a much larger gate resistor would be a poor choice.

A pull-down resistor of 10kΩ connects the gate to the source. While the board is in reset, the ATmega328P leaves its port pins tri-stated, meaning disconnected [4], and they remain inputs until the sketch says otherwise. A floating gate can hold stray charge and turn the motor partly on. The pull-down drains that charge. It also forms a divider with the gate resistor, so check that it does not steal the drive voltage: with a 5V pin the gate receives 5V × 10,000 / 10,330, about 4.84V, and the resistor takes only 0.5mA.

A logic-level MOSFET low-side motor switch with a gate resistor, a pull-down, a flyback diode, and two supplies sharing ground

At this point the pin has a job it can do: it supplies a few milliamps to a base or charges a gate, while a transistor carries the load current from a separate supply that shares the Uno's ground. The part sizes follow from datasheet figures. The relay and the motor still have one property that a resistor or an LED does not, and it can destroy the transistor the first time it switches off.

Inductive Loads and the Flyback Diode

A relay coil, a solenoid, and a motor winding are all coils of wire, and a coil has inductance: it stores energy in a magnetic field and resists any sudden change in its current. When a transistor switches the current off, the field collapses and the coil generates whatever voltage it takes to keep current moving. TE Connectivity, a relay maker, states that this can reach hundreds or even thousands of volts, added to the supply voltage, across the switch [12]. The IRLZ44N's drain-to-source breakdown rating is 55V [9] and the P2N2222A's collector-to-emitter rating is 40V [8].

A diode conducts current in one direction, from its anode to its cathode, which is the end marked with a band. A flyback diode is placed directly across the coil with its band toward the positive supply. In normal operation it is reverse biased, meaning the supply pushes against it, and it does nothing. At switch-off the coil reverses its own voltage, the diode conducts, and the current circulates through the coil and diode until it dies away, with the voltage held to about the diode's forward drop [12].

Current paths through a coil and its flyback diode while the switch is on and just after it opens

A diode fitted backward is a short circuit across the supply whenever the transistor is on, so check the band before applying power. Mount it close to the load, so the circulating current takes a short loop.

The 1N4001 is rated for 50V in reverse and 1A of average forward current, with a forward voltage of 1V at 1A [13]. Those figures cover the relay and a motor within the limit used here. A motor that draws more needs a diode with a higher current rating. The manufacturer's current sheet marks the family as not recommended for new designs and gives no reverse-recovery time, which is how long a diode takes to stop conducting when the voltage reverses [13]. That time matters more when a motor is switched hundreds of times per second than when a relay switches once in a while. For a motor that will run for long periods, I would pick a Schottky diode, a faster type, with a suitable current and voltage rating.

The protection has a cost for relays. Because the current decays slowly through a plain diode, the contacts open more slowly, and TE warns that this can shorten contact life by weakening the relay's ability to break contacts that have stuck together [12]. TE's compromise is a Zener diode in series with the ordinary diode, which lets the voltage rise to a higher, controlled level and ends the current sooner [12]. For the light, occasional switching in this lesson, the plain diode is appropriate. Leave neither coil unprotected.

Some relay modules sold on small circuit boards already contain a transistor and a diode. Their input pin can connect straight to the Arduino, within the module's documented input current. Some of them turn the relay on when the input is LOW, so check the module's documentation before assuming which level is on. The bare relay in this lesson contains neither, which is why we build both.

Planning the First Build

Build in stages, and test each one before adding the next. Disconnect both supplies whenever you move a wire.

Item Pin or connection Voltage Resistor
LED (Exercise 1) D9 5V from the pin 220Ω in series
Frequency jumper (Exercise 3) D9 to D7 5V logic None
Relay driver (Exercise 4) D8 to transistor base 5V load supply 330Ω base
Motor switch (project) D9 to MOSFET gate 5V load supply 330Ω gate, 10kΩ pull-down
Knob (Exercise 1 and project) A0 5V from the Uno None
  1. Wire the knob and LED, and run Exercise 1 on USB power alone.
  2. Remove the LED and run Exercises 2 and 3.
  3. Build the relay driver with the load supply unplugged. Check the transistor pin order, the diode band, and the common ground, then apply power.
  4. Replace the relay circuit with the motor switch. Test it with the motor disconnected first, using an LED and 220Ω resistor in the motor's place, then fit the motor and its diode.

Keep the load supply at 5V. A supply rated for several amps can push all of that current into a short circuit and overheat a jumper wire, so check the screw terminal polarity and make sure no bare strands bridge the two terminals.

Exercises

Exercise 1: Report the Duty Cycle

The goal is to connect the number in analogWrite() to a duty cycle and an average voltage, using the Part 4 LED. Wire the potentiometer's outer legs to 5V and GND and its center leg to A0. Wire D9 through a 220Ω resistor to the LED's long leg (anode), and the short leg to GND.

const uint8_t POT_PIN = A0;               // potentiometer wiper
const uint8_t LED_PIN = 9;                // LED on D9, a PWM pin (marked ~)
const unsigned long REPORT_MS = 500;      // time between Serial reports, in milliseconds

unsigned long lastReport = 0;             // millis() value at the previous report

void setup() {
  pinMode(LED_PIN, OUTPUT);               // the LED pin drives out
  Serial.begin(9600);                     // open the Serial Monitor link at 9600 baud
}

void loop() {
  int raw = analogRead(POT_PIN);          // knob position, 0 to 1023
  int duty = map(raw, 0, 1023, 0, 255);   // rescale to the analogWrite() range
  duty = constrain(duty, 0, 255);         // keep the value inside 0 to 255
  analogWrite(LED_PIN, duty);             // set the share of each cycle that is HIGH

  if (millis() - lastReport >= REPORT_MS) {     // has half a second passed?
    lastReport = millis();                      // remember when this report went out
    float fraction = duty / 255.0;              // duty cycle as a number from 0.0 to 1.0
    Serial.print(F("value="));                  // F() keeps the label text out of SRAM
    Serial.print(duty);                         // the number given to analogWrite()
    Serial.print(F("  duty="));
    Serial.print(fraction * 100.0, 1);          // duty cycle in percent, one decimal place
    Serial.print(F("%  average="));
    Serial.print(fraction * 5.0, 2);            // calculated average for a 5V high level
    Serial.println(F("V"));
  }
}

Open the Serial Monitor at 9600 baud. With the knob fully one way you should see value=0 duty=0.0% average=0.00V, and fully the other way value=255 duty=100.0% average=5.00V. Near the middle the value is about 127, the duty about 49.8%, and the average about 2.49V. The voltage is calculated by the sketch from an assumed 5V high level, and nothing in this circuit measures it. If the LED only snaps between off and on, it is wired to a pin without a ~.

Exercise 2: Ask a Plain Pin for PWM

This exercise shows what happens on a pin with no timer. Nothing needs to be connected to D7, because the sketch reads the pin's own level back with digitalRead().

const uint8_t PLAIN_PIN = 7;              // D7 has no ~ mark, so it has no PWM hardware
const int VALUES[] = {0, 64, 127, 128, 200, 255};   // commands to try, on both sides of 128
const int VALUE_COUNT = 6;                // number of entries in VALUES

void setup() {
  Serial.begin(9600);                     // open the Serial Monitor link
}

void loop() {
  for (int i = 0; i < VALUE_COUNT; i++) {        // step through the commands one by one
    analogWrite(PLAIN_PIN, VALUES[i]);           // ask for PWM on a pin that has none
    delay(10);                                   // let the pin settle before reading it back
    int level = digitalRead(PLAIN_PIN);          // read the real level of the pin
    Serial.print(F("analogWrite(7, "));
    Serial.print(VALUES[i]);
    Serial.print(F(") leaves the pin "));
    if (level == HIGH) {                         // report which level we found
      Serial.println(F("HIGH"));
    } else {
      Serial.println(F("LOW"));
    }
    delay(1000);                                 // one second per step, long enough to watch
  }
  Serial.println();                              // blank line between passes
}

The Serial Monitor should report LOW for 0, 64, and 127, and HIGH for 128, 200, and 255, matching the threshold in the core [3]. If you change PLAIN_PIN to a PWM pin, the results no longer match that pattern, because digitalRead() switches PWM off on a PWM pin before it reads the level [3].

Exercise 3: Measure the PWM Frequency

The Uno can time its own pulses. Connect a jumper from D9 to D7. pulseIn() waits for a pulse of the chosen level on a pin and returns its length in microseconds, or 0 if none arrives before its time limit.

const uint8_t PWM_PIN = 9;                // PWM output under test; change to 5 for a second run
const uint8_t SENSE_PIN = 7;              // jumper this pin to PWM_PIN

void setup() {
  pinMode(SENSE_PIN, INPUT);              // the sense pin only listens
  analogWrite(PWM_PIN, 128);              // start a wave that is HIGH about half the time
  Serial.begin(9600);                     // open the Serial Monitor link
}

void loop() {
  unsigned long highUs = pulseIn(SENSE_PIN, HIGH);   // length of one HIGH pulse, in microseconds
  unsigned long lowUs = pulseIn(SENSE_PIN, LOW);     // length of one LOW pulse, in microseconds

  if (highUs == 0 || lowUs == 0) {                   // pulseIn() returns 0 when no pulse arrives
    Serial.println(F("No pulses. Check the jumper."));
  } else {
    unsigned long periodUs = highUs + lowUs;         // one full cycle
    Serial.print(F("high="));
    Serial.print(highUs);
    Serial.print(F("us  low="));
    Serial.print(lowUs);
    Serial.print(F("us  frequency="));
    Serial.print(1000000.0 / periodUs, 0);           // one million microseconds over the period
    Serial.print(F("Hz  duty="));
    Serial.print(100.0 * highUs / periodUs, 1);      // HIGH share of the period, in percent
    Serial.println(F("%"));
  }
  delay(1000);                                       // one reading per second
}

From the timer arithmetic, expect a period near 2,040µs on D9, which is about 490Hz, with a duty near 50%. Change PWM_PIN to 5, move the jumper to D5, and upload again: the period should be near 1,024µs, about 976Hz. In the Electronics Lab simulator, these two runs reported about 493Hz on D9 and 980Hz on D5. A real board and its clock will differ slightly, and pulseIn() timing has limited accuracy. If you see the no-pulses message, the jumper is on the wrong pin.

Exercise 4: Switch a Relay Through a Transistor

The goal is to switch a 90mA coil with a pin that supplies about a tenth of that. A relay is a switch operated by an electromagnet: current in the coil moves a contact called COM (common) away from the NC (normally closed) contact to the NO (normally open) contact. The coil and the contacts are electrically separate. PWM plays no role here, because a relay's moving contact is meant to be either on or off.

From To
D8 330Ω resistor, then transistor base
Transistor emitter Common ground
Transistor collector One coil terminal
Other coil terminal Load supply +5V
1N4001 anode (no band) Collector side of the coil
1N4001 cathode (band) +5V side of the coil
Load supply negative Uno GND
Uno 5V Relay COM
Relay NO 220Ω resistor, then LED anode
LED cathode GND

On a P2N2222A in the TO-92 package, pin 1 is the collector, pin 2 the base, and pin 3 the emitter [8]. Parts sold as 2N2222 or PN2222 can use a different order, including the reverse one, so check the datasheet for the exact marking. Find the coil terminals from your relay's diagram, or look for the pair that reads your relay's coil resistance on a meter, about 56Ω for the relay described here.

const uint8_t RELAY_PIN = 8;              // goes to the transistor base through 330Ω
const unsigned long HOLD_MS = 2000;       // time the relay stays in each state, in milliseconds

unsigned long lastChange = 0;             // millis() value at the last switch
bool relayOn = false;                     // the state we have commanded

void setup() {
  pinMode(RELAY_PIN, OUTPUT);             // the pin supplies the small base current
  digitalWrite(RELAY_PIN, LOW);           // start with the coil off
  Serial.begin(9600);                     // open the Serial Monitor link
}

void loop() {
  if (millis() - lastChange >= HOLD_MS) {       // time for the next switch?
    lastChange = millis();                      // remember when it happened
    relayOn = !relayOn;                         // flip the commanded state

    if (relayOn) {                              // turn the coil on or off to match
      digitalWrite(RELAY_PIN, HIGH);            // base current flows, the transistor conducts
      Serial.println(F("Relay ON"));
    } else {
      digitalWrite(RELAY_PIN, LOW);             // base current stops, the transistor opens
      Serial.println(F("Relay OFF"));
    }
  }
}

Every two seconds the relay should click, the Serial Monitor should print Relay ON or Relay OFF, and the LED should follow. A click with no LED points to the contact wiring. No click with a correct Serial message points to the coil circuit: check the supply, the common ground, and the transistor's pin order, in that sequence.

Try the Switches in the Electronics Lab

The Electronics Lab can run the relay driver and the project's switching circuit with no hardware. In both Labs, the part drawn as a signal generator is set to a steady 5V and stands in for the separate load supply, with its GND lead joined to the Uno's ground.

Try the Relay Driver in the Lab

This Lab runs the Exercise 4 sketch with a 330Ω base resistor, an NPN transistor, a relay with a 56Ω coil, a flyback diode across the coil, and an LED on the relay contacts.

Lab part Connection
Base resistor, 330Ω D8 to transistor B
Transistor E Uno GND
Relay coil Load supply +5V and transistor C
Diode (1N4007 in the Lab) Anode at transistor C, cathode at +5V
Relay COM and NO Uno 5V, then 220Ω resistor and LED
  1. Press Run and wait for the sketch to compile.
  2. Open Serial. Relay ON and Relay OFF alternate every two seconds.
  3. Watch the LED follow the messages.

The Lab shows the control logic: a pin drives a base resistor, the transistor completes the coil circuit, and the contacts switch a separate LED circuit. It does not show a voltage spike or what the diode does about it, so do not remove the diode from a real build on the strength of a simulation. The Lab uses a 1N4007, a higher-voltage member of the same diode family [13].

Try the Motor Switch in the Lab

This Lab runs the exact project sketch. The Lab has no IRLZ44N or DC motor, so a 2N7000 MOSFET stands in as the switch, and a yellow LED with a 220Ω resistor stands in for the motor. The LED draws a current well within the 2N7000's rating [11]. No flyback diode appears, because the stand-in load has no coil.

Lab part Connection
Potentiometer VCC to 5V, SIG to A0, GND to GND
Gate resistor, 330Ω D9 to MOSFET G
Pull-down, 10kΩ MOSFET G to GND
Load resistor and LED Load supply +5V, 220Ω, LED, MOSFET D
MOSFET S and load supply GND Uno GND
  1. Press Run and open Serial.
  2. With the knob at its low end, the report reads knob=0 value=0 state=off.
  3. Turn the knob up. The state changes to run after the short start pulse, and the value climbs to 255.

When we ran this Lab, a knob reading of 700 printed value=197 state=run with the LED lit. The LED stayed dark through the lower part of the knob's travel and reached full brightness before the top, even though the printed value rose smoothly. The simulated brightness therefore does not track duty cycle the way a real LED does, and a real motor will respond differently again. Use the Lab to check wiring and program logic. If you are reading without running it, the lesson is that one pin value controls a transistor that switches a load on a separate supply.

Practical Project: Knob-Controlled Motor

What you will build

A knob sets the speed of a small DC motor in one direction. Turned all the way down, the motor is off. Turned up from off, the sketch gives the motor a brief full-power start pulse, then holds the speed the knob requests, never lower than a floor that keeps the shaft turning. A status line reports the knob, the PWM value, and the state.

A motor that is standing still needs more drive to begin turning than to keep turning, which is the reason for the start pulse. Without it, low knob settings can leave the motor stalled and humming while it draws its highest current.

Components needed

An Uno R3, an IRLZ44N, one 1N4001, a 3–6V DC motor with a stall current under 1A at 5V, the 5V load supply with a screw terminal, a 10kΩ potentiometer, a 330Ω resistor, a 10kΩ resistor, a breadboard, and jumper wires.

Wiring

The IRLZ44N's three legs, read from the front with the printing facing you and the legs down, are gate, drain, and source [9]. The metal tab on a TO-220 MOSFET is normally connected to the drain, so keep it from touching other wires.

From To
Potentiometer outer leg Uno 5V
Potentiometer center leg A0
Potentiometer other outer leg Uno GND
D9 330Ω resistor, then MOSFET gate
MOSFET gate 10kΩ resistor to MOSFET source
MOSFET source Common ground
MOSFET drain Motor terminal A
Motor terminal B Load supply +5V
1N4001 anode (no band) Motor terminal A
1N4001 cathode (band) Motor terminal B
Load supply negative Uno GND

Run the motor current from the MOSFET source straight back to the load supply's negative terminal, and connect the Uno's ground to that point. This keeps the heavy current off the thin ground wire that serves the Uno.

The sketch

const uint8_t POT_PIN = A0;                   // speed knob wiper
const uint8_t GATE_PIN = 9;                   // goes to the MOSFET gate through 330Ω
const int KNOB_OFF_BELOW = 40;                // raw knob readings under this mean "off"
const int MIN_RUN_DUTY = 80;                  // lowest running value; tune it for your motor
const unsigned long KICK_MS = 200;            // length of the full-power start pulse
const unsigned long REPORT_MS = 500;          // time between Serial reports

bool running = false;                         // true while the motor is being driven
unsigned long kickStart = 0;                  // millis() value when the last start began
unsigned long lastReport = 0;                 // millis() value at the previous report

void setup() {
  pinMode(GATE_PIN, OUTPUT);                  // the pin now drives the gate
  digitalWrite(GATE_PIN, LOW);                // motor off
  Serial.begin(9600);                         // open the Serial Monitor link
}

void loop() {
  int raw = analogRead(POT_PIN);              // knob position, 0 to 1023
  int duty = 0;                               // value to send this pass; 0 means off
  bool starting = false;                      // true during the start pulse

  if (raw < KNOB_OFF_BELOW) {                 // knob is in the off zone
    running = false;                          // the next turn-up counts as a new start
  } else {
    if (!running) {                           // the motor was stopped until now
      running = true;                         // it is being driven from here on
      kickStart = millis();                   // begin timing the start pulse
    }
    starting = (millis() - kickStart < KICK_MS);   // still inside the start pulse?
    if (starting) {
      duty = 255;                             // full power to get the shaft moving
    } else {
      duty = map(raw, KNOB_OFF_BELOW, 1023, MIN_RUN_DUTY, 255);   // knob sets the speed
      duty = constrain(duty, MIN_RUN_DUTY, 255);                  // never below the floor
    }
  }
  analogWrite(GATE_PIN, duty);                // the MOSFET switches the motor at this value

  if (millis() - lastReport >= REPORT_MS) {   // time for a status line?
    lastReport = millis();                    // remember when this report went out
    Serial.print(F("knob="));
    Serial.print(raw);
    Serial.print(F("  value="));
    Serial.print(duty);
    Serial.print(F("  state="));
    if (!running) {                           // name the state in words
      Serial.println(F("off"));
    } else if (starting) {
      Serial.println(F("start"));
    } else {
      Serial.println(F("run"));
    }
  }
}

What is happening

Each pass reads the knob. Below a reading of 40, the sketch marks the motor stopped and writes 0. When the reading rises above that zone and the motor was stopped, kickStart records the time. For the next 200ms the sketch writes 255, which the core turns into a steady HIGH [3]. After that, map() converts the rest of the knob's travel into values from 80 to 255, and constrain() enforces the floor. The timing uses the millis() subtraction from Part 4, so the knob stays responsive during the start pulse and no delay() is needed.

The two constants at the top belong to your motor. If it stalls at the low end, raise MIN_RUN_DUTY in steps of 10. If it starts reliably with a shorter pulse, reduce KICK_MS.

The done test

Action Expected result
Power up with the knob at zero Motor still, value=0 state=off
Hold the Uno's reset button Motor stays still
Turn the knob up slowly Motor starts firmly and keeps turning
Turn the knob to maximum value=255, highest speed
Return the knob to zero Motor stops, state=off

Build and test sequence

Wire the circuit with both supplies off. Upload the sketch over USB with the load supply still unplugged, and confirm the Serial reports follow the knob. Unplug USB, check the diode band and the common ground, then connect USB and finally the load supply. Touch nothing metal on the circuit while it runs. If the MOSFET, diode, or motor becomes hot, remove the load supply first and look for the cause.

Reading the output critically

The report shows what the sketch commanded, and the Uno has no sensor that reports whether the shaft is turning. A line reading value=120 state=run is consistent with a spinning motor, a stalled motor, and a disconnected one. The start state lasts 200ms and reports print every 500ms, so some starts produce no start line. Part 20 adds a Hall effect sensor, which is one way to measure rotation.

Troubleshooting

Symptom Likely cause First check
Load only off or fully on Pin has no PWM, or the Servo library or tone() holds the timer Use D9 and remove the conflicting library call
Nothing switches Missing common ground or load supply Wire from load negative to Uno GND
Motor runs whenever powered MOSFET legs in the wrong order or shorted MOSFET Gate, drain, source order
Motor twitches during upload or reset No gate pull-down 10kΩ from gate to source
Uno resets when the motor starts Motor powered from the Uno, or ground current path shared poorly Separate supply, short ground return
Transistor or MOSFET gets hot Not fully on, wrong part, or load too large Part number and load current
Supply shuts off as soon as the switch turns on Flyback diode backward Band toward +5V
Motor hums but does not turn Duty too low to start Raise MIN_RUN_DUTY

The motor starts, stops, and restarts near the low end

A knob resting at the edge of the off zone can read 39 on one pass and 40 on the next, because analog readings jitter as Part 10 showed. Each crossing counts as a new start and fires another pulse. Turn the knob clear of the edge, or add a second, higher threshold for starting so that the stop point and start point differ.

The motor whines

The whine at low and middle settings comes from switching inside the audible range. It does not by itself mean the circuit is faulty. A different PWM frequency is a timer-register change, covered in Part 46.

The transistor switches but the relay does not pull in

Measure the load supply at the coil. The relay datasheet gives a pull-in voltage of up to 75% of nominal, which is 3.75V for a 5V coil [6]. A weak supply, a long thin lead, or a transistor that is not saturated can leave less than that. Confirm the 330Ω resistor value and the pin order.

Measuring a PWM Circuit

A multimeter on DC volts averages a PWM signal, so a reading at D9 against GND should sit near the duty cycle multiplied by the pin's HIGH voltage. The same meter across a switched motor shows an average that includes the motor's own generated voltage, so it will not follow that simple product. To see pulses, edges, and any spike, use an oscilloscope with its ground clip on the common ground. A scope ground clip is joined to earth on many bench instruments, so never clip it to the drain or collector. Measure current by placing the meter in series with the load supply's positive lead, with power off while you connect it and the leads in the meter's correct current jack and range.

Design Limits

This circuit drives one load in one direction from a 5V supply, with less than 1A of load current on a breadboard. Do not use it for mains voltage, even though the relay's contacts carry a printed mains rating: a breadboard and an open relay offer no safe isolation or enclosure. Larger motors need wiring, a diode, and possibly a heatsink sized for their current. Switching two sides of a motor to reverse it requires an H-bridge, covered in Part 16. Hobby servos accept a control pulse with its own timing, which Part 17 covers, and their power is a separate question from this switch.

Where This Fits in the Series

Mastering Arduino Part 13: SPI: A Different Bus moved bytes between chips over a clocked bus. This part turns a pin's signal into control over loads that the pin cannot power. Part 15, Comparison Logic and Tolerance: The RGB Color-Match Game, puts PWM to work on RGB LED channels and compares the results in code.

References

  1. Arduino, “analogWrite(),” Arduino Language Reference, revised May 9, 2025, docs.arduino.cc. https://docs.arduino.cc/language-reference/en/functions/analog-io/analogWrite/ Accessed November 30, 2026.
  2. Arduino, “analogWrite(),” reference-en source file with the board pin and frequency table, GitHub. https://github.com/arduino/reference-en/blob/master/Language/Functions/Analog%20IO/analogWrite.adoc Accessed November 30, 2026.
  3. Arduino, “ArduinoCore-avr” source: wiring.c, wiring_analog.c, wiring_digital.c, Tone.cpp, and pins_arduino.h, GitHub. https://github.com/arduino/ArduinoCore-avr/tree/master/cores/arduino Accessed November 30, 2026.
  4. Microchip Technology, “ATmega48A/PA/88A/PA/168A/PA/328/P Data Sheet,” document DS40002061B, 2020, I/O ports and electrical characteristics chapters, microchip.com. https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf Accessed November 30, 2026.
  5. Arduino, “Servo,” library documentation, version 1.3.0, docs.arduino.cc. https://docs.arduino.cc/libraries/servo/ Accessed November 30, 2026.
  6. Zhejiang Dongya Electronic Co., Ltd., “JZC-11F Miniature Relay,” approval datasheet for JZC-11F-05VDC-1Z, dated December 20, 2010, hosted at cdn.sparkfun.com. https://cdn.sparkfun.com/assets/f/4/7/b/0/DS-00100-Relay_SPDT_Sealed.pdf Accessed November 30, 2026.
  7. OpenStax, University Physics Volume 2, section 13.6, “Electric Generators and Back Emf,” openstax.org. https://openstax.org/books/university-physics-volume-2/pages/13-6-electric-generators-and-back-emf Accessed November 30, 2026.
  8. onsemi, “P2N2222A Amplifier Transistors, NPN Silicon,” publication P2N2222A/D, Rev. 7, January 2013, onsemi.com. https://www.onsemi.com/pdf/datasheet/p2n2222a-d.pdf Accessed November 30, 2026.
  9. Infineon Technologies, “IRLZ44NPbF,” datasheet Rev. 2.1, August 12, 2026, infineon.com. https://www.infineon.com/assets/row/public/documents/24/49/infineon-irlz44npbf-datasheet-en.pdf Accessed November 30, 2026.
  10. Infineon Technologies, “IRF520NPbF,” datasheet Rev. 2.1, July 24, 2026, infineon.com. https://www.infineon.com/assets/row/public/documents/24/49/infineon-irf520npbf-datasheet-en.pdf Accessed November 30, 2026.
  11. onsemi, “2N7000, 2N7002, NDS7002A N-Channel Enhancement Mode Field Effect Transistor,” publication NDS7002A/D, Rev. 11, March 2025, onsemi.com. https://www.onsemi.com/pdf/datasheet/nds7002a-d.pdf Accessed November 30, 2026.
  12. TE Connectivity, “Coil Suppression Can Reduce Relay Life,” September 2020, te.com. https://www.te.com/en/products/relays-and-contactors/electromechanical-relays/intersection/coil-suppression-relay-life.html Accessed November 30, 2026.
  13. Diodes Incorporated, “1N4001 - 1N4007 1.0A Rectifier,” document DS28002 Rev. 11-3, July 2024, diodes.com. https://www.diodes.com/assets/Datasheets/ds28002.pdf Accessed November 30, 2026.

Wrap-Up and What's Next

analogWrite() produces a pulse train whose duty cycle you set, at 490Hz or 980Hz on the Uno, and the pin that produces it is limited to a few tens of milliamps. A transistor or logic-level MOSFET carries the load current from a separate supply, a common ground lets the pin's signal reach it, and a flyback diode gives a coil's current somewhere to go at switch-off. The project combines these in a motor speed control.

Part 15 uses PWM to mix colors in an RGB color-match game, so it comes next.

Hack The World and Make Awesome.

Add new comment

Restricted HTML

  • You can align images (data-align="center"), but also videos, blockquotes, and so on.
  • You can caption images (data-caption="Text"), but also videos, blockquotes, and so on.