DC Motor Control
Flip the switch to start and stop a DC motor.
- Beginner
- Motors
- 3 parts
Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.
How it works
A switch connects 5 volts to pin 2, so pin 2 reads high when the switch is closed and low when it is open. Pin 5 is wired to the motor’s positive terminal and the motor’s other terminal goes to ground, so setting pin 5 high applies 5 volts to the motor and it spins. A real motor needs more current than an Arduino pin can supply, so a real build puts a transistor or motor driver between the pin and the motor, with a diode across the motor to absorb voltage spikes. This circuit connects it directly to keep the idea clear.
loop() reads the switch five times a second. If it is closed the sketch sets pin 5 high and prints “Motor ON”; if it is open it sets pin 5 low and prints “Motor OFF”. Click the switch in the editor to toggle it and watch the motor start and stop.
Parts
- Arduino Uno
- Switch
- DC Motor
Wiring
- Arduino Uno 5V → Switch A
- Switch B → Arduino Uno D2
- Arduino Uno D5 → DC Motor +
- Arduino Uno GND → DC Motor -
Arduino code
// DC Motor Control
void setup() {
pinMode(2, INPUT);
pinMode(5, OUTPUT);
Serial.begin(9600);
}
void loop() {
int on = digitalRead(2);
if (on == HIGH) {
digitalWrite(5, HIGH);
Serial.println("Motor ON");
} else {
digitalWrite(5, LOW);
Serial.println("Motor OFF");
}
delay(200);
}
Try changing it
- Flip the logic so the motor runs while the switch is open: change on == HIGH to on == LOW.
- Make it respond faster by changing delay(200) to delay(20).