DC Motor Speed Control (Transistor + Arduino)
Drive a DC motor from one pin through a transistor and vary its speed with PWM. Learn transistor switching and flyback protection.
Beginner25 min
What you need
- · 1kΩ resistor
- · 1N4001 diode
- · External 5V supply
- · jumper wires
Wiring
Hover a pin or a wire to trace the connection.
Code
dc_motor.ino
// Ramp a DC motor's speed up and down with PWM through a transistor.
const int motorPin = 9; // PWM -> transistor base (through a resistor)
void setup() {
pinMode(motorPin, OUTPUT);
}
void loop() {
for (int s = 0; s <= 255; s += 5) { analogWrite(motorPin, s); delay(50); } // speed up
delay(1000);
for (int s = 255; s >= 0; s -= 5) { analogWrite(motorPin, s); delay(50); } // slow down
delay(1000);
}
Steps
- Transistor: base to D9 through a 1kΩ resistor, emitter to GND, collector to one motor terminal.
- Motor's other terminal to +5V (use an external supply; share ground with the Arduino).
- Add a 1N4001 flyback diode across the motor (band/stripe toward +5V).
- Upload — the motor ramps up and down. Never wire a motor straight to a pin.