Motors are how embedded systems move things. Today you'll control three types: DC motors, servo motors, and stepper motors.
DC motors draw too much current for GPIO pins directly. The L298N is a dual H-bridge driver — it can drive two motors at up to 2A each. Connect: ENA to PWM pin (speed), IN1/IN2 to digital pins (direction), motor leads to OUT1/OUT2. 12V to VCC, separate 5V or onboard regulator for logic. analogWrite(ENA, 0-255) sets speed. IN1=HIGH,IN2=LOW = forward. IN1=LOW,IN2=HIGH = reverse.
Servo motors have built-in feedback and a control circuit. They use PWM: 50Hz signal, 1–2ms pulse width controls position (0°–180°). The Servo.h library handles this: servo.attach(pin) then servo.write(angle) where angle is 0–180. Servos need their own 5V power supply for anything over small loads — powering from Arduino's 5V pin works for one small servo but will reset the Arduino with multiple servos.
Stepper motors move in discrete steps (typically 200 steps per revolution = 1.8° per step). They're precise without feedback sensors. Controlled with a driver (A4988, DRV8825). Connect STEP and DIR pins to Arduino. digitalWrite(STEP, HIGH); delayMicroseconds(100); digitalWrite(STEP, LOW) = one step. The AccelStepper library provides acceleration curves, which prevent missed steps at high speeds.
// Control servo + DC motor
#include <Servo.h>
// DC Motor (L298N)
const int ENA = 9; // PWM speed
const int IN1 = 7; // direction
const int IN2 = 8;
// Servo
Servo myServo;
const int SERVO_PIN = 6;
void motorForward(int speed) { // speed: 0-255
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
analogWrite(ENA, speed);
}
void motorReverse(int speed) {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
analogWrite(ENA, speed);
}
void motorStop() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
analogWrite(ENA, 0);
}
void setup() {
Serial.begin(9600);
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
myServo.attach(SERVO_PIN);
myServo.write(90); // center position
Serial.println("Motors ready");
}
void loop() {
// Sweep servo 0-180 while running DC motor forward
Serial.println("Forward + servo sweep");
motorForward(180); // ~70% speed
for (int angle = 0; angle <= 180; angle += 5) {
myServo.write(angle);
delay(30);
}
Serial.println("Reverse + servo return");
motorReverse(180);
for (int angle = 180; angle >= 0; angle -= 5) {
myServo.write(angle);
delay(30);
}
motorStop();
delay(1000);
}
Build a robot arm controller with 3 servos: shoulder (base rotation), elbow (up/down), and gripper (open/close). Use 3 potentiometers to control each servo in real time. Add position memory: pressing a button saves the current position. A second button replays all saved positions in sequence — basic robotic arm playback.