Built-in project · Arduino Uno R3

Servo turnouts with a panel on an Arduino Uno

Two servo turnouts that glide across one degree at a time, a panel button and a pair of route lamps for each, and positions kept in EEPROM so nothing jumps at power-up. The whole build, an Arduino Uno and 12 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 40 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $38. On Mokxi they're free.

Servo turnouts with a panel · Arduino Uno R3live0.000 s 0.00x
Press Run, then press a panel button and watch the servo glide
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

What you'll learn

  • Slow, smooth servo motion
  • Setting an angle for each end of travel
  • Saving a value in EEPROM so it survives power off
  • Debouncing a button with a 50 ms lockout
  • Controlling things from the Serial Monitor
  • Difficulty: Intermediate
  • Time: About 40 minutes
  • Board: Arduino Uno R3
  • Parts: 15

How it works

Each model railway turnout is moved by a hobby servo: one on pin 9 and one on pin 10. Press a panel button, on pin 5 or pin 2, and that turnout flips between closed (through) and thrown (diverging).

The servo does not snap. It moves one degree every 30 ms, so the points glide across like the real thing. Each turnout has two lamps. Green means closed, yellow means thrown.

The lamp for the new route blinks while the points travel and goes steady on arrival. The last position of each turnout is saved, so after a restart the servos start where they were.

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 pinConnects to
Hobby servo (1) pin GNDArduino Uno R3 pin GND
Hobby servo (2) pin GNDArduino Uno R3 pin GND
Resistor, 220 Ω (1) pin 2Arduino Uno R3 pin GND
Resistor, 220 Ω (2) pin 2Arduino Uno R3 pin GND
Pushbutton (1) pin 2aArduino Uno R3 pin GND
Pushbutton (1) pin 2bArduino Uno R3 pin GND
Resistor, 220 Ω (3) pin 2Arduino Uno R3 pin GND
Resistor, 220 Ω (4) pin 2Arduino Uno R3 pin GND
Pushbutton (2) pin 2aArduino Uno R3 pin GND
Pushbutton (2) pin 2bArduino Uno R3 pin GND
Hobby servo (2) pin PWMArduino Uno R3 pin 10
Hobby servo (1) pin PWMArduino Uno R3 pin 9
LED, green (1) pin AArduino Uno R3 pin 7
LED, yellow (1) pin AArduino Uno R3 pin 6
Pushbutton (1) pin 1aArduino Uno R3 pin 5
Pushbutton (1) pin 1bArduino Uno R3 pin 5
LED, green (2) pin AArduino Uno R3 pin 4
LED, yellow (2) pin AArduino Uno R3 pin 3
Pushbutton (2) pin 1aArduino Uno R3 pin 2
Pushbutton (2) pin 1bArduino Uno R3 pin 2
Hobby servo (1) pin VCC5 V
Hobby servo (2) pin VCC5 V
Resistor, 220 Ω (1) pin 1LED, green (1) pin C
Resistor, 220 Ω (2) pin 1LED, yellow (1) pin C
Resistor, 220 Ω (3) pin 1LED, green (2) pin C
Resistor, 220 Ω (4) pin 1LED, yellow (2) pin C

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · Arduino Uno R3
// Servo turnouts with a control panel: two turnouts, two buttons, four lamps.
//
//   pin 5, pin 2     panel buttons for turnouts 1 and 2 (to GND, internal pull-ups)
//   pin 9, pin 10    the two turnout servos
//   pins 7 and 6     turnout 1's lamps: green for through (closed), yellow for diverging (thrown)
//   pins 4 and 3     turnout 2's lamps, the same way round
//
// A hobby servo under the layout, with a stiff wire up through the throwbar,
// is the cheapest slow-motion turnout motor there is. Three things make it look
// and last like a real one:
//
//   1. Slow motion. The horn moves one degree every 30 ms instead of snapping,
//      so the points glide across, the way the prototype's do.
//   2. A throw set per turnout. CLOSED_ANGLE and THROWN_ANGLE are where the
//      points just touch each stock rail. Past that the servo pushes against
//      the rail forever, hums and gets hot, so set them on the layout.
//   3. Memory. The last position of each turnout is kept in EEPROM, so at power
//      up the servo is sent where it already is and does not jump.
//
// The panel lamp for the new route blinks while the points travel and goes
// steady when they arrive. Type "1" or "2" in the Serial Monitor to throw from
// the keyboard, the way a computer panel such as JMRI might send a command.
//
// On a DCC layout the same sketch would take its commands from accessory
// decoder packets instead of buttons; the servo side does not change.

#include <EEPROM.h>
#include <Servo.h>

const int TURNOUTS = 2;
const int BUTTON_PIN[TURNOUTS] = {5, 2};
const int SERVO_PIN[TURNOUTS] = {9, 10};
const int CLOSED_LAMP[TURNOUTS] = {7, 4};
const int THROWN_LAMP[TURNOUTS] = {6, 3};
const int CLOSED_ANGLE[TURNOUTS] = {75, 80};
const int THROWN_ANGLE[TURNOUTS] = {105, 100};
const unsigned long STEP_MS = 30;  // one degree per step: slower is more realistic
const unsigned long BLINK_MS = 250;

Servo servo[TURNOUTS];
bool thrown[TURNOUTS];   // where each turnout is going (or is)
int angle[TURNOUTS];     // where its servo is now
bool buttonWas[TURNOUTS];
unsigned long buttonAt[TURNOUTS];
unsigned long lastStep = 0;

int targetOf(int t) { return thrown[t] ? THROWN_ANGLE[t] : CLOSED_ANGLE[t]; }

void showLamps(int t, bool blinkOn) {
  bool moving = angle[t] != targetOf(t);
  bool lit = !moving || blinkOn;
  digitalWrite(CLOSED_LAMP[t], (!thrown[t] && lit) ? HIGH : LOW);
  digitalWrite(THROWN_LAMP[t], (thrown[t] && lit) ? HIGH : LOW);
}

void flip(int t) {
  thrown[t] = !thrown[t];
  EEPROM.update(t, thrown[t] ? 1 : 0);
  Serial.print("turnout ");
  Serial.print(t + 1);
  Serial.println(thrown[t] ? " throwing" : " closing");
}

void setup() {
  Serial.begin(9600);
  for (int t = 0; t < TURNOUTS; t++) {
    pinMode(BUTTON_PIN[t], INPUT_PULLUP);
    pinMode(CLOSED_LAMP[t], OUTPUT);
    pinMode(THROWN_LAMP[t], OUTPUT);
    thrown[t] = EEPROM.read(t) == 1;  // a blank EEPROM reads 255: closed
    angle[t] = targetOf(t);
    servo[t].attach(SERVO_PIN[t]);
    servo[t].write(angle[t]);
    showLamps(t, true);
  }
  Serial.println("Turnout panel ready: press a button, or type 1 or 2");
}

void loop() {
  unsigned long now = millis();

  // Buttons: act on the press, then ignore the pin for 50 ms of contact bounce.
  for (int t = 0; t < TURNOUTS; t++) {
    bool down = digitalRead(BUTTON_PIN[t]) == LOW;
    if (down != buttonWas[t] && now - buttonAt[t] >= 50) {
      buttonWas[t] = down;
      buttonAt[t] = now;
      if (down) flip(t);
    }
  }
  while (Serial.available() > 0) {
    char c = Serial.read();
    if (c == '1' || c == '2') flip(c - '1');
  }

  // Slow motion: every STEP_MS, each moving servo takes one degree toward its target.
  if (now - lastStep >= STEP_MS) {
    lastStep = now;
    bool blinkOn = (now / BLINK_MS) % 2 == 0;
    for (int t = 0; t < TURNOUTS; t++) {
      int target = targetOf(t);
      if (angle[t] != target) {
        angle[t] += angle[t] < target ? 1 : -1;
        servo[t].write(angle[t]);
        if (angle[t] == target) {
          Serial.print("turnout ");
          Serial.print(t + 1);
          Serial.println(thrown[t] ? " thrown" : " closed");
        }
      }
      showLamps(t, blinkOn);
    }
  }
}

Code walkthrough

The key functions of the sketch, and what each one does.

targetOf sketch.ino

Returns the angle a turnout is heading for. It picks THROWN_ANGLE if the turnout is thrown, and CLOSED_ANGLE if not. Each turnout has its own pair, so you can tune them separately.

int targetOf(int t) { return thrown[t] ? THROWN_ANGLE[t] : CLOSED_ANGLE[t]; }

showLamps sketch.ino

Sets the two lamps for one turnout. The lamp for the current route is lit. While the servo is still moving, that lamp only lights on the blink phase, so it flashes until the points arrive.

void showLamps(int t, bool blinkOn) {
  bool moving = angle[t] != targetOf(t);
  bool lit = !moving || blinkOn;
  digitalWrite(CLOSED_LAMP[t], (!thrown[t] && lit) ? HIGH : LOW);
  digitalWrite(THROWN_LAMP[t], (thrown[t] && lit) ? HIGH : LOW);
}

flip sketch.ino

Toggles which way a turnout wants to go, then saves the choice with EEPROM.update. It also prints a message. It does not move the servo: the loop does that, one degree at a time.

void flip(int t) {
  thrown[t] = !thrown[t];
  EEPROM.update(t, thrown[t] ? 1 : 0);
  Serial.print("turnout ");
  Serial.print(t + 1);
  Serial.println(thrown[t] ? " throwing" : " closing");
}

loop sketch.ino

Reads both buttons and the Serial Monitor, where typing 1 or 2 flips a turnout. Every STEP_MS it moves each servo one degree toward its target and refreshes the lamps.

void loop() {
  unsigned long now = millis();

  // Buttons: act on the press, then ignore the pin for 50 ms of contact bounce.
  for (int t = 0; t < TURNOUTS; t++) {
    bool down = digitalRead(BUTTON_PIN[t]) == LOW;
    if (down != buttonWas[t] && now - buttonAt[t] >= 50) {
      buttonWas[t] = down;
      buttonAt[t] = now;
      if (down) flip(t);
    }
  }
  while (Serial.available() > 0) {
    char c = Serial.read();
    if (c == '1' || c == '2') flip(c - '1');
  }

  // Slow motion: every STEP_MS, each moving servo takes one degree toward its target.
  if (now - lastStep >= STEP_MS) {
    lastStep = now;
    bool blinkOn = (now / BLINK_MS) % 2 == 0;
    for (int t = 0; t < TURNOUTS; t++) {
      int target = targetOf(t);
      if (angle[t] != target) {
        angle[t] += angle[t] < target ? 1 : -1;
        servo[t].write(angle[t]);
        if (angle[t] == target) {
          Serial.print("turnout ");
  // ... 8 more lines in the editor

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • A servo hums and gets warm at the end of travel. This project
    It is pushing against the rail. Lower THROWN_ANGLE or raise CLOSED_ANGLE until the points just touch.
  • A button does nothing. This project
    Wire it between its pin and GND. The sketch uses the internal pull-up, and a press reads LOW.
  • Turnouts start in the wrong position. This project
    The position comes from EEPROM. A blank EEPROM means closed, so flip the turnout once and it will be remembered.
  • The servo jitters, twitches or resets the board when it moves. Hobby servo
    Power it from its own 5 V supply, not the Arduino 5 V pin, and join the grounds. A hobby servo can pull several hundred milliamps. Add a 100 uF to 470 uF capacitor across its supply.
  • The servo hums at the end of its travel or will not reach full angle. Hobby servo
    Stay inside the pulse range, about 1000 to 2000 us for most hobby servos. Pushing past the end stop makes it strain. Calibrate the min and max pulse for your servo.
  • The LED does not light, or it lights once and then dies. LED
    LEDs have polarity. The longer leg (anode) goes toward the positive side. Always add a series resistor, about 220 ohms to 1 k ohm on a 5 V pin.
  • A blue or white LED stays dark on 3.3 V. LED
    Blue and white LEDs drop about 3 V, so 3.3 V leaves almost nothing for the resistor. Use a 5 V supply, or a smaller resistor and a red or green LED.
  • The LED is dim, burns out, or the pin reads wrong because the resistor value is off. Resistor
    Read the color bands again. A 220 ohm to 330 ohm resistor suits a typical LED on 5 V. 10k is a common pull-up or pull-down value. Check with a multimeter if unsure.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.