Don't Burn Your Arduino! The Ultimate Guide to Controlling DC Motors

Don't Burn Your Arduino! The Ultimate Guide to Controlling DC Motors


📑Table of Contents
What You'll Need 9 items
Arduino Uno R3
Buy
DC Motor (6V-9V)
Buy
NPN Transistor (2N2222)
Buy
Diode (1N4007)
Buy
1kΩ Resistor
Buy
9V Battery
Buy
Battery Snap Connector
Buy
Breadboard
Buy
Jumper Wires
Buy

Affiliate links help support this site at no extra cost to you.

Welcome to Day 17. We are entering the Heavyweight Class of Arduino. Until now, we have been playing with “Low Power” devices.

  • LEDs use 20mA.
  • Sensors use 5mA.
  • Piezo buzzers use 10mA.

Today, we want to move physical matter. We want to spin a fan, drive a wheel, or lift a robot arm. We need Torque. We need Power. We need the DC Motor.

But there is a problem. A big, smoking problem. If you plug a motor directly into your Arduino, you will kill your Arduino. Instantly. Ideally with a dramatic “Pop” sound and the smell of burning silicon.

Today, we learn how to tame the beast using the Transistor.

Hero Image: Cinematic Robot Arm / Motor Control

The Physics: Why Arduino can’t drive Motors

To understand the danger, we need to talk about Current (Amps). The Arduino’s processor (ATmega328P) is a brain, not a muscle.

  • Arduino Pin Max Current: 40mA (Absolute Maximum).
  • Small DC Motor (No Load): 100mA.
  • Small DC Motor (Stalled): 1000mA (1 Amp).

Do the math. The motor tries to suck 1000mA through a pin designed for 40mA. It is like trying to suck a watermelon through a straw. The straw bursts. The chip melts. The magic smoke comes out.

Rule #1 of Robotics: NEVER connect a motor directly to an Arduino Pin.

Magic Smoke Error visualization

The Solution: The Electronic Switch (Transistor)

We need a middleman. We need a device that takes a tiny signal from the Arduino (Connect/Disconnect) and uses it to control a massive flow of power from a battery to the motor. This device is the Transistor.

Think of it like a Water Valve.

  • The Pipe: A huge water main (The Battery power).
  • The Handle: A tiny little tap that you can turn easily.
  • The Flow: When you turn the tiny handle, the massive water main opens.

You (the Arduino) only have to touch the handle. You don’t have to hold back the water yourself.

Transistor Analogy: Valve and Pipe

The Hardware: The NPN Transistor (2N2222)

For small motors, we use a BJT (Bipolar Junction Transistor). The most common one is the 2N2222 (or PN2222). It is a small black cylinder with 3 legs.

The Pinout (C-B-E)

If you hold it with the Flat Face facing you, the legs are (from Left to Right):

  1. Collector (C): Connects to the Motor (The Load).
  2. Base (B): Connects to the Arduino (The Handle).
  3. Emitter (E): Connects to Ground (The Exit).

Mnemonic: “Current Flows in C, Out E”.

Transistor Pinout: 2N2222 CBE

The Protection: The Flyback Diode

Motors are nasty. They are Inductive Loads. Inside a motor, there are coils of wire and magnets. When you run electricity through a coil, it creates a magnetic field. When you turning the power OFF, that magnetic field collapses. Physics says this collapsing field must generate electricity. It shoots a massive Voltage Spike (up to 300V!) backwards through the wires. This “Kickback” (or Flyback) can shock your Arduino and reset it, or destroy the transistor.

The Fix: A Flyback Diode (1N4007 or 1N4148). A diode is a one-way valve for electricity. We place it across the motor in Reverse Bias.

  • Normal flow: Diode blocks it (does nothing).
  • Flyback Spike: Diode opens, short-circuiting the spike back into the motor coil. Basically, the motor eats its own kickback.

Flyback Diode Physics: Inductive Spike

The Build: Transistor Motor Driver

Let’s build the standard “Low Side Switch” circuit. Components:

  1. Arduino Uno.
  2. Small DC Motor (Toy motor).
  3. 2N2222 Transistor.
  4. 1N4007 Diode.
  5. 1kΩ Resistor (Current limiter for the Base).
  6. External Power Source (9V Battery). Do not use Arduino’s 5V!

Wiring Instructions:

  1. Motor (+): To Battery Positive (9V).
  2. Motor (-): To Transistor Collector (Middle/Left leg depending on package).
  3. Diode: Across the Motor legs. Stripe side touches Battery (+).
  4. Transistor Emitter: To GND.
  5. Transistor Base: To 1kΩ Resistor.
  6. Resistor other end: To Arduino Pin 9.
  7. IMPORTANT: Connect Battery GND to Arduino GND. (Common Ground).

Schematic: Motor Driver Circuit

The Code Phase 1: Full Speed Ahead

Since the transistor is just a switch, we can use digitalWrite.

const int motorPin = 9;

void setup() {
  pinMode(motorPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println("Motor ON");
  digitalWrite(motorPin, HIGH); // Turn Transistor ON -> Motor Runs
  delay(1000);
  
  Serial.println("Motor OFF");
  digitalWrite(motorPin, LOW); // Turn Transistor OFF -> Motor Stops
  delay(1000);
}

Observation: When Pin 9 goes HIGH, the Transistor Base gets 5V. It opens the floodgates. The 9V from the battery rushes through the motor to Ground. The motor spins.

Breadboard Render: Clean wiring

The Code Phase 2: Speed Control (PWM)

Because we used Pin 9 (a PWM pin), we can control the speed! Just like fading an LED. We are pulsing the motor power. The motor’s inertia smooths out the pulses, so it just spins slower.

void loop() {
  // Accelerate
  for (int speed = 0; speed <= 255; speed++) {
    analogWrite(motorPin, speed);
    delay(10);
  }
  
  // Decelerate
  for (int speed = 255; speed >= 0; speed--) {
    analogWrite(motorPin, speed);
    delay(10);
  }
}

Torque Warning: At very low PWM values (e.g., 20 or 30), the motor might hum but not move. It needs a minimum amount of power to overcome static friction. Usually, motors start spinning around PWM 50-60.

PWM Speed Control Graph: Voltage vs Speed

The Trap: Common Ground

This is the #1 mistake beginners make. You have a 9V battery for the motor. You have a USB cable for the Arduino. You MUST connect the 9V Battery Negative to the Arduino GND. Voltage is relative. If you don’t connect the grounds, the Arduino’s “5V” signal has no reference point for the transistor to understand. Nothing will work. Rule: always tie the grounds together (but NEVER the Positives!).

Deep Dive: MOSFET vs BJT

We used a BJT (2N2222) today. It is cheap and good for small motors (< 600mA). But it runs hot. It wastes power. For bigger motors (Drills, Drones, RC Cars), we use MOSFETs (Metal Oxide Semiconductor Field Effect Transistor). MOSFETs are voltage-controlled (Gate). BJTs are current-controlled (Base). MOSFETs are much more efficient for high power. We will use an IRLZ44N Logic Level MOSFET in future high-power projects. For now, the 2N2222 is your friend.

Deep Dive: The Saturation Region

You might hear engineers talk about “Biasing” a transistor. For motors, we don’t care about linear amplification (like in an audio amplifier). We want the transistor to be fully ON or fully OFF. This “Fully ON” state is called Saturation.

  • Cut-Off Region: Base current is 0. Switch is OFF. Motor has 0V.
  • Active Region: Base current is low. Transistor is “half-open”. It gets extremely hot because it is resisting the flow. Avoid this.
  • Saturation Region: Base current is high enough (>1mA). Transistor is fully open. Vce (Voltage between Collector and Emitter) drops to ~0.2V.

Why does this matter? If you don’t use enough Base Current (e.g. you use a 100kΩ resistor instead of 1kΩ), the transistor won’t fully open. It will act like a bottleneck. Your motor will run slow, and the transistor will burn up. Everything we do today relies on achieving Saturation.

Safety Upgrade: The Optocoupler (4N35)

What if your motor is huge? Like a treadmill motor? What if it generates so much electrical noise that it crashes your Arduino even with a diode? You need Total Isolation. You need an Optocoupler (like the 4N35).

An Optocoupler is a chip with an LED inside and a light-sensitive transistor inside.

  1. Arduino turns on the internal LED.
  2. Light hits the internal transistor.
  3. Transistor opens. There is NO electrical connection between the Arduino and the Motor. It is just light. If the motor explodes and sends 1000V backwards, it burns the Optocoupler, but your Arduino remains untouched. For expensive projects, always use Optocouplers. For expensive projects, always use Optocouplers.

Engineering Spotlight: The Darlington Pair

The 2N2222 has a gain (hFE) of about 100. If you put 1mA into the Base, you get 100mA at the Collector. What if you need 5 Amps? You would need 50mA at the Base, which might kill the Arduino pin. The solution is a Darlington Pair (like the TIP120). It is two transistors inside one package, chained together. Gain 1 * Gain 2 = Total Gain. 100 * 100 = 10,000. You can drive a massive motor with a whisper of current. Note: They have a higher voltage drop (1.4V), so they get hotter than single transistors. Why did we put a resistor between the Arduino and the Transistor Base? Because the Base-Emitter junction inside the transistor looks like a short circuit (technically a diode) to the Arduino. Without the resistor, the Arduino would dump unlimited current into the Base, protecting the Transistor but killing the Arduino pin. The 1kΩ limits current to a safe 5mA.

Challenge: The Automated Fan

You have an LDR (from Day 16). You have a Motor (Fan). Combine them! Build a system that turns the Fan ON when it gets bright (simulating a hot sunny day). Or, if you have a temperature sensor (Thermistor), use that.

int light = analogRead(A0);
if (light > 600) {
  analogWrite(9, 255); // Full blast
} else if (light > 400) {
  analogWrite(9, 128); // Half speed
} else {
  digitalWrite(9, LOW); // Off
}

Final Fan Project Render

Troubleshooting Guide

Troubleshooting Guide: The Diagnostic Checklist

If your motor is dead, don’t panic. Follow this order:

  1. The “Click” Test:

    • Do you hear a faint “whine” or “click” when power is applied?
    • Yes: PWM is too low. Increase softStart minimum.
    • No: Proceed to step 2.
  2. The Common Ground Check:

    • Put your Multimeter logic on Continuity Mode (Beep).
    • Touch one probe to Arduino GND.
    • Touch the other to Battery Negative.
    • No Beep? You found the problem. Tie them together.
  3. The Transistor Orientation:

    • Look at the 2N2222. Is the Flat Side facing you?
    • If you wired it backwards, it might still work poorly but get incredibly hot. Flip it.
  4. The Base Resistor Check:

    • Did you accidently use 10kΩ or 100kΩ instead of 1kΩ?
    • Too much resistance = No Saturation = Weak Motor.
  5. The Diode Direction:

    • If the diode is backwards (Stripe to Negative), you have created a Short Circuit.
    • Your battery will get hot, and the motor will not spin.
  6. The “Magic Smoke” Check:

    • Does the Arduino still run the “Blink” sketch?
    • If not, you might have fried the pin. Try using Pin 10 instead of Pin 9.

The Bill of Materials (BOM)

ComponentQuantityValueNotes
Arduino Uno1AnyThe Brain of the operation.
DC Motor13V-6VSmall Hobby Motor (“130 Size”). Avoid high-power drone motors for this circuit.
Transistor12N2222NPN Bipolar Junction Transistor. Ensure it handles 600mA+.
Diode11N4007Rectifier Diode. Crucial for catching the Flyback spike.
Resistor11kΩBase current limiter (Brown-Black-Red).
Battery19VPower for the Motor. Do not share 5V rail.
Battery Clip19VTo connect to breadboard.
Wires10+M-MBreadboard jumper wires.
Breadboard1Half+Standard prototyping area.

Pro Tip: Noise Suppression (The Ghost in the Machine)

DC Motors are “noisy”. As the brushes spin inside, they spark. This creates Radio Frequency (RF) interference. It can confuse your sensors or reset the Arduino. The Fix: Solder a small 0.1uF Ceramic Capacitor across the motor terminals. It acts like a shock absorber for the electrical noise, shorting the high-frequency sparks before they travel down the wires. If your robot builds are “glitchy”, this is usually the missing piece.

Advanced Theory: Reversing Direction (The H-Bridge)

You might noticed something. Our Transistor circuit allows us to turn the motor ON and OFF. It allows us to control SPEED (PWM). But it does NOT allow us to Reverse Direction. Why? Because the current always flows from Collector to Emitter. One way. To reverse a DC motor, you must swap the Positive and Negative wires.

To do this electronically, we need Four Transistors arranged in an “H” shape. This is called an H-Bridge.

  • Forward: Top-Left and Bottom-Right transistors open.
  • Reverse: Top-Right and Bottom-Left transistors open.
  • Brake: Top-Left and Top-Right open (short circuit).

Building an H-Bridge from scratch is complex (and prone to “Shoot-Through” short circuits). In the future, we will use dedicated H-Bridge Chips like the L293D or L298N. For today, mastered one direction first!

Pro Tip: The Soft-Start Algorithm

When a motor starts from 0 RPM, it is “Stalled” for a split second. It draws maximum current (Inrush Current). This spike can dim your lights or reset your Arduino. To prevent this, never jump from 0 to 255 instantly. Use a “Soft Start” wrapper function:

void softStart(int targetSpeed) {
  for (int i = 0; i <= targetSpeed; i += 5) {
    analogWrite(9, i);
    delay(10); // Ramp up over ~500ms
  }
}

Use this whenever you turn the motor ON. Your power supply will thank you.

Safety Check: Measuring Stall Current

Before you use ANY distinct scavenged motor with a 2N2222, check its Stall Current.

  1. Take your Multimeter.
  2. Set it to 10A Mode (Move the red probe to the 10A socket).
  3. Connect the probes directly to the Battery.
  4. Briefly touch the motor terminals to the probes.
  5. Hold the motor shaft so it cannot spin (Stall).
  6. Read the Amps immediately and let go (do not hold for > 1 second).
  • If < 0.6A: Safe for 2N2222.
  • If > 0.6A: Danger! Do not use 2N2222. Use a MOSFET.

Conclusion

You have successfully broken the 40mA barrier. You are now controlling High Power with Low Power. This is the fundamental concept behind every machine in the world. From the tiny vibrator in your phone to the massive motors in a Tesla Model S to the hydraulics of a Space Shuttle… It is all just small signals controlling big valves.

Tomorrow, on Day 18, we go even bigger. We will control Alternating Current (AC). We will learn about the Relay. We will learn how to turn on a real lightbulb or a coffee machine safely. (Don’t actually plug in current yet, we will stay safe with 12V, but the theory is the same!).

See you on Day 18.

Comments