Servos are fantastic for precise, twitchy movements, but what if you want to build a wheeled robot or a motorized fan that spins continuously? You need a standard DC Motor.
Hereās the catch: DC motors are power-hungry monsters. Connect one directly to your Arduino, and you will instantly fry your microcontroller into an expensive paperweight. To safely tame this beast, we use a Motor Driver. The L298N is big, clunky, and perfectly suited for the job.
The L298N driver acts as a heavy-duty switch, taking small control signals from the Arduino and delivering high power to the motors.
The L298N uses a circuit called an āH-Bridgeā to control both the speed and direction of up to two DC motors.
It has three main types of connections:
Letās wire up a single motor (Motor A).
OUT1 and OUT2.12V terminal on the L298N.GND terminal.GND terminal on the L298N.ENA pin (if present).ENA to Arduino Pin 9 (for speed control via PWM).IN1 to Arduino Pin 8 (direction control 1).IN2 to Arduino Pin 7 (direction control 2).To control direction, we set IN1 and IN2 to opposite states (one HIGH, one LOW). Reversing those states reverses the motor. To control speed, we use analogWrite() on the ENA pin, sending a value between 0 (stopped) and 255 (full speed).
// Define the L298N control pins
const int enA = 9;
const int in1 = 8;
const int in2 = 7;
void setup() {
// Set all the motor control pins to outputs
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
// Start with the motor turned off
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
analogWrite(enA, 0);
}
void loop() {
// 1. Spin forward at full speed
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
analogWrite(enA, 255); // Full speed
delay(2000); // Wait for 2 seconds
// 2. Stop
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
analogWrite(enA, 0);
delay(1000);
// 3. Spin backward at half speed
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
analogWrite(enA, 128); // Half speed
delay(2000);
// 4. Stop again
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
analogWrite(enA, 0);
delay(1000);
}
Upload the code and watch your motor come to life! In future lessons, we can connect a second motor and pair it with an ultrasonic sensor to build an autonomous robot car.