Knob-controlled motor (L293D)
One knob sets a DC motor's speed and direction through an L293D: turn left to reverse, right to go forward, the middle to stop.
Motors · Beginner
In a real product: Toy car (Consumer electronics): One control sets the motor's speed and direction.
An L293D is the classic motor driver chip: four half bridges in a 16-pin package, enough to run a DC motor both ways (two half bridges make an H-bridge). A potentiometer centred is stop; turned either way it runs the motor that way, faster the further you turn.
What you'll learn
- Making an H-bridge from two half bridges: 1A and 2A choose the direction, the enable pin the speed
- A dead band around the knob's centre, so the motor really stops
- Mapping 0–1023 onto −255…255
How it works
analogRead(A0) gives 0–1023; the sketch subtracts 512 and scales it to −255…255. Within 40 of the middle it is zero. The sign picks the direction (1A HIGH and 2A LOW one way, the reverse the other), and the size goes to analogWrite() on 1,2EN, which switches both half bridges on and off together: PWM speed control.
Try this
- Turn the knob from one end to the other: the motor slows, stops in the middle and turns the other way.
- Widen the dead band and feel how much of the knob does nothing.
- Use outputs 3 and 4 (3,4EN, 3A, 4A) for a second motor.
sketch.ino
// A DC motor on an L293D (outputs 1Y and 2Y): the knob on A0 sets speed and direction, with a dead band in the middle.
// 1,2EN on pin 9 (PWM), 1A on 7, 2A on 8.
const int EN = 9, IN1 = 7, IN2 = 8, DEAD_BAND = 40;
void setup() {
Serial.begin(9600);
pinMode(EN, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
}
void loop() {
int knob = analogRead(A0) - 512;
int speed = abs(knob) < DEAD_BAND ? 0 : constrain(knob / 2, -255, 255);
digitalWrite(IN1, speed > 0);
digitalWrite(IN2, speed < 0);
analogWrite(EN, abs(speed));
static int shown = 1000;
if (abs(speed - shown) > 8) {
shown = speed;
Serial.print("speed ");
Serial.println(speed);
}
}