DC throttle with momentum on an Arduino Uno
A knob, a direction switch and a brake button drive a DC motor through a TB6612, easing up to speed and down again like a heavy train, and reversing only at a standstill. The whole build, an Arduino Uno and 5 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Intermediate About 25 minutes to build and run. Runs in your browser. Free, and no account needed.
The parts retail for about $36. On Mokxi they're free.
What you'll learn
- PWM as an average voltage
- Driving a DC motor in both directions with an H-bridge
- Momentum: moving toward a target in small steps
- Using the internal pull-up for a switch and a button
- Mapping a knob reading to a speed
- Difficulty: Intermediate
- Time: About 25 minutes
- Board: Arduino Uno R3
- Parts: 9
How it works
A potentiometer on A0 is the throttle. The TB6612 motor driver takes a PWM signal on pin 9 for speed, and two direction pins, 7 and 8. It switches the 12 V supply on and off fast, and the motor feels the average.
The motor does not jump to the speed the knob asks for. Every 20 ms the speed eases up by ACCEL or down by DECEL, like a heavy train. Holding the brake button on pin 3 slows it much harder.
The direction switch on pin 2 only takes effect at a standstill. Flip it at speed and the motor slows to a stop first, then reverses. Knob readings below START_AT count as zero.
Parts list
9 parts, plus the jumper wires. They retail for about $36; on Mokxi they're free.
- 1 × Arduino Uno R3In Starter Kit, Claw Machine Kit, Vending Machine Kit.
- 1 × Full-size breadboard
- 1 × Slide switchIn Logic Lab Kit, Spaceship Panel Kit, 555 Timer Kit.
- 1 × PushbuttonIn Starter Kit, Christmas Lights Kit, Logic Lab Kit.
- 1 × PotentiometerIn Halloween Prop Kit, Starter Projects Kit, MicroPython Pico Kit.
- 1 × Motor driver, TB6612FNG
- 1 × DC motorIn Robot Car Kit.
- 1 × Power, 12 V
- 1 × Power, 5 V
Wiring table
Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.
| Part and pin | Connects to |
|---|---|
| Slide switch pin 3 | Arduino Uno R3 pin GND |
| Pushbutton pin 2a | Arduino Uno R3 pin GND |
| Pushbutton pin 2b | Arduino Uno R3 pin GND |
| Potentiometer pin 1 | Arduino Uno R3 pin GND |
| Motor driver, TB6612FNG pin PWMA | Arduino Uno R3 pin 9 |
| Motor driver, TB6612FNG pin AIN2 | Arduino Uno R3 pin 8 |
| Motor driver, TB6612FNG pin AIN1 | Arduino Uno R3 pin 7 |
| Pushbutton pin 1a | Arduino Uno R3 pin 3 |
| Pushbutton pin 1b | Arduino Uno R3 pin 3 |
| Slide switch pin 2 | Arduino Uno R3 pin 2 |
| Potentiometer pin 3 | Arduino Uno R3 pin 5V |
| Potentiometer pin 2 | Arduino Uno R3 pin A0 |
| Motor driver, TB6612FNG pin STBY | 5 V |
| Motor driver, TB6612FNG pin VCC | 5 V |
| Motor driver, TB6612FNG pin GND1 | Ground |
| Motor driver, TB6612FNG pin VM | 12 V |
| DC motor pin 1 | Motor driver, TB6612FNG pin AO1 |
| DC motor pin 2 | Motor driver, TB6612FNG pin AO2 |
| Motor driver, TB6612FNG pin GND3 | Ground |
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// DC throttle with momentum: a knob, a direction switch, a brake and a TB6612.
//
// A0 the throttle knob (its ends on 5 V and GND)
// pin 2 direction switch (to GND for reverse, internal pull-up)
// pin 3 brake button (to GND, internal pull-up)
// pin 9 PWM into the TB6612's PWMA pins 7 and 8: AIN1 and AIN2
//
// This is how a DC layout runs a train: the speed is the average voltage on the
// rails, and PWM sets that average by switching the full supply on and off.
// What makes it feel like a train is momentum. A heavy train does not jump to
// the speed the knob asks for; it eases up to it at ACCEL per step and slows at
// DECEL, so a quick twist of the knob still gives a gentle start. The brake
// button slows much harder, and the direction switch is only obeyed at a
// standstill: flip it at speed and the train coasts down, stops, then reverses,
// as an engineer would make it.
//
// DCC works differently. The rails carry constant power as a square wave that
// also carries digital packets, and a decoder inside each locomotive does the
// PWM and the momentum itself (its CV3 and CV4 set acceleration and braking).
// Mokxi does not simulate DCC; this sketch is the DC way, and the momentum logic
// is the same idea a decoder runs.
//
// The supply here is 12 V, like most HO and N scale DC power packs. On a real
// layout fit a fuse or a current limit: a derailed wheel across both rails is a
// dead short.
const int KNOB_PIN = A0;
const int REVERSE_PIN = 2;
const int BRAKE_PIN = 3;
const int PWM_PIN = 9;
const int AIN1 = 7;
const int AIN2 = 8;
const int ACCEL = 2; // speed steps gained per 20 ms tick, out of 255
const int DECEL = 3; // lost when the knob is turned down
const int BRAKE = 12; // lost per tick with the brake held
const int START_AT = 30; // below this a typical motor only hums, so treat it as stopped
int speed = 0; // what the motor gets now, 0 to 255
bool reverse = false; // the direction the motor is turning (or will turn)
unsigned long lastTick = 0;
int lastReported = -1;
void drive() {
digitalWrite(AIN1, reverse ? LOW : HIGH);
digitalWrite(AIN2, reverse ? HIGH : LOW);
analogWrite(PWM_PIN, speed);
}
void setup() {
Serial.begin(9600);
pinMode(REVERSE_PIN, INPUT_PULLUP);
pinMode(BRAKE_PIN, INPUT_PULLUP);
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
reverse = digitalRead(REVERSE_PIN) == LOW;
drive();
Serial.println("DC throttle ready: turn the knob");
}
void loop() {
unsigned long now = millis();
if (now - lastTick < 20) return;
lastTick = now;
int asked = map(analogRead(KNOB_PIN), 0, 1023, 0, 255);
if (asked < START_AT) asked = 0;
bool wantReverse = digitalRead(REVERSE_PIN) == LOW;
bool braking = digitalRead(BRAKE_PIN) == LOW;
// A change of direction waits for a standstill: aim for zero until then.
if (wantReverse != reverse) {
if (speed == 0) {
reverse = wantReverse;
Serial.println(reverse ? "reverse" : "forward");
} else {
asked = 0;
}
}
if (braking) asked = 0;
if (speed < asked) speed = min(speed + ACCEL, asked);
else if (speed > asked) speed = max(speed - (braking ? BRAKE : DECEL), asked);
drive();
int percent = speed * 100 / 255;
if (percent / 5 != lastReported / 5 || (speed == 0 && lastReported != 0)) {
lastReported = percent;
Serial.print(reverse ? "reverse " : "forward ");
Serial.print(percent);
Serial.println(braking ? "% braking" : "%");
}
}
Code walkthrough
The key functions of the sketch, and what each one does.
drive sketch.ino
Sets the two direction pins so that one is HIGH and the other LOW, depending on reverse, and writes the current speed to the PWM pin. Swapping which pin is HIGH is what turns the motor the other way.
void drive() {
digitalWrite(AIN1, reverse ? LOW : HIGH);
digitalWrite(AIN2, reverse ? HIGH : LOW);
analogWrite(PWM_PIN, speed);
}loop sketch.ino
Runs once every 20 ms. It reads the knob as the speed asked for, then checks the switch and the brake. A direction change or the brake sets the target to zero. Then the real speed moves one step toward the target, and drive applies it.
void loop() {
unsigned long now = millis();
if (now - lastTick < 20) return;
lastTick = now;
int asked = map(analogRead(KNOB_PIN), 0, 1023, 0, 255);
if (asked < START_AT) asked = 0;
bool wantReverse = digitalRead(REVERSE_PIN) == LOW;
bool braking = digitalRead(BRAKE_PIN) == LOW;
// A change of direction waits for a standstill: aim for zero until then.
if (wantReverse != reverse) {
if (speed == 0) {
reverse = wantReverse;
Serial.println(reverse ? "reverse" : "forward");
} else {
asked = 0;
}
}
if (braking) asked = 0;
if (speed < asked) speed = min(speed + ACCEL, asked);
else if (speed > asked) speed = max(speed - (braking ? BRAKE : DECEL), asked);
drive();
int percent = speed * 100 / 255;
if (percent / 5 != lastReported / 5 || (speed == 0 && lastReported != 0)) {
lastReported = percent;
// ... 5 more lines in the editorTroubleshooting
The usual mistakes with this circuit, and the fix for each.
- The motor hums but does not turn at low knob settings This project
That is whySTART_ATexists. Raise or lower it to match your motor. - The motor does nothing at all This project
The driver's STBY pin must be at 5 V, and the motor supply and grounds must be connected. - The direction switch seems to do nothing This project
It is only obeyed once the motor has stopped. Turn the knob down or press the brake, then wait. - The input reads random values in one position. Slide switch
A switch only connects or disconnects. Add a pull-up or pull-down resistor, or use INPUT_PULLUP, so the pin has a defined level when the switch is open. - The load never turns on when the switch is flipped. Slide switch
Use the center (common) leg and one outer leg. The unused outer leg goes nowhere. Check that the switch is in series with the load. - The input reads random HIGH and LOW when the button is not pressed. Pushbutton
A floating pin picks up noise. Add a 10 k pull-down or pull-up resistor, or use INPUT_PULLUP and wire the button between the pin and GND. Then pressed reads LOW. - The button seems always pressed, or never changes. Pushbutton
A 4-leg tactile switch has legs joined in pairs. Place it across the breadboard center gap so the pairs sit on different rows. Wired along one side, the legs are already connected. - The reading jumps around or only covers part of the range. Potentiometer
Wire the two outer legs to 5 V and ground and the middle leg (the wiper) to an analog pin. Using the wrong two legs gives a dead or partial range.
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.