Motor Control Basics
Motors allow your robot to move and interact with the world.
DC Motor with L298N Motor Driver
Never connect motors directly to Arduino! Use a motor driver.
// Motor A connections
const int enA = 9; // PWM pin for speed control
const int in1 = 8;
const int in2 = 7;
void setup() {
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
}
void loop() {
// Move forward at full speed
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
analogWrite(enA, 255); // Speed 0-255
delay(2000);
// Stop
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
delay(1000);
// Move backward at half speed
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
analogWrite(enA, 128); // Half speed
delay(2000);
// Stop
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
delay(1000);
}
Servo Motor Control
Servos are perfect for robotic arms and precise movements.
#include
Servo myServo;
void setup() {
myServo.attach(9); // Servo signal pin
}
void loop() {
myServo.write(0); // Move to 0 degrees
delay(1000);
myServo.write(90); // Move to 90 degrees
delay(1000);
myServo.write(180); // Move to 180 degrees
delay(1000);
}
Motor Driver Wiring (L298N)
- IN1, IN2: Direction control → Arduino pins 7, 8
- ENA: Speed control (PWM) → Arduino pin 9
- OUT1, OUT2: Motor terminals
- 12V: External battery (+)
- GND: Common ground (Arduino + Battery)
Warning: Always connect GND between Arduino and motor driver. Never power motors directly from Arduino!