Guides · 10 min read

Arduino Model Railway Turnout Servo: Slow Motion and PCA9685

Arduino model railway turnout servo: slow-motion points, push buttons and panel, angle table, jitter-free power, EEPROM memory and 16 turnouts on a PCA9685.

An Arduino model railway turnout servo setup is the most practical way to throw the points on your layout with a servo that costs two or three dollars instead of an expensive point motor. The Arduino turns the servo degree by degree, a thin steel wire in the servo horn pushes the turnout's throwbar, and the switch blades move quietly over one or two seconds, just like on the real railway. Instead of the sudden snap of a solenoid point motor you get a smooth, prototypical movement, and you set the end positions yourself.

In this guide you'll see how the servo throws the turnout, an angle table for each scale and how to calibrate the angle from the Serial Monitor. Then we'll build, step by step, the slow-motion code with a push-button control panel and LEDs, a separate power supply that stops servo jitter, EEPROM memory so the turnout remembers its position after a power cut, and 16 turnouts driven by a single PCA9685 board.

SG90 micro servo for a model railway turnout
SG90 micro servo: small, cheap and strong enough for H0 and N scale turnouts.

How does servo turnout control work?

The two moving blades of a turnout are tied to the throwbar under the rails; when the bar slides a few millimetres left or right, the train is guided onto the straight or the diverging route. The servo is screwed under the turnout, usually under the baseboard. A 0.8 mm piano wire sits in a hole of the servo horn, comes up through a small hole in the board and enters the hole in the middle of the throwbar. The servo only turns 15–25 degrees and the wire converts that rotation into blade travel. A small loop bent into the wire (an omega spring) adds some give: even if the servo turns a little too far, it presses the blade against the stock rail gently instead of forcing it. The servo signal is a train of 50 Hz pulses: a 1500 µs pulse means the centre position (90°), and shorter or longer pulses turn the servo one way or the other. The Arduino Servo library maps 0–180 degrees to pulses of 544–2400 µs, so 1 degree is roughly 10 µs.

FeatureSolenoid point motorServo + ArduinoSlow-motion stall motor
MovementSudden, noisy snapSlow and adjustableSlow, fixed speed
Current1–3 A pulse100–250 mA while movingConstant 15–30 mA
Price per turnoutMediumVery low (servo + wire)High
End position adjustmentNone, fixed strokeIn software, per turnoutMechanical
Frog polarityNeeds an extra contactRelay or microswitchBuilt-in contacts on most
Position memoryStays mechanicallyVia EEPROMStays mechanically

Parts list and choosing a servo

  • Arduino Uno or Nano: one turnout needs 2–3 pins, and all digital pins are enough for a 16-button panel.
  • SG90 plastic-gear micro servo: fine for N, TT and H0; for busy turnouts or stiff blades the metal-gear MG90S lasts longer.
  • 0.8 mm piano wire (H0 and TT), 0.5 mm for N; pick a thickness that fits the hole in the servo horn.
  • One push button (or a two-position toggle) per turnout and two LEDs on the control panel (green straight, red diverging) with 220–330 Ω resistors.
  • A separate 5 V supply for the servos: at least 2 A for 1–4 servos, 4–5 A for 16 servos; a 1000 µF capacitor across the supply line.
  • For 16 turnouts a PCA9685 16-channel servo driver, and an optional relay module for frog polarity.

Wiring: one turnout, button, LEDs and relay

PartArduino Uno / NanoNote
Servo signal (orange)D9The Servo library disables analogWrite on D9 and D10
Servo + (red)External 5 VNever from the Arduino 5V pin
Servo − (brown)GNDThe external supply's GND goes here too: common ground
Push buttonD2 and GNDINPUT_PULLUP; reads LOW when pressed
Green LED (straight)D5 → 220 Ω → LED → GNDShows the straight route on the panel
Red LED (diverging)D6 → 220 Ω → LED → GNDShows the diverging route on the panel
Relay module IND7Frog polarity; 5 V relay module
Don't power the servo from the Arduino 5V pin. An SG90 draws up to 250 mA while moving and up to 650 mA when stalled; on a USB-powered board the voltage sags, the Arduino resets or the servo jitters. Use a separate 5 V supply for the servos and always connect its negative terminal to the Arduino GND. Without a common ground the signal loses its reference and the servo moves randomly.

Servo angle settings: how many degrees for a turnout?

You don't swing the servo from 0 to 180 degrees for a turnout; a small angle either side of the 90-degree centre is enough. You can estimate the angle with this formula: if r is the distance from the horn hole to the servo centre, the total travel is s = 2 × r × sin(θ). On an H0 turnout the blades move about 3 mm; with a hole 8 mm out, θ = arcsin(3 ÷ 16) ≈ 11 degrees, so 79 and 101 degrees are a good start. Add 2–4 degrees for the omega spring. The table below gives starting values; you find the exact angle of each turnout by calibration.

ScaleBlade travel (approx.)WireHorn hole rRequired ±θStarting anglesServo
N (1:160)1.5–2 mm0.5 mm6 mm±7–10°82 / 98SG90
TT (1:120)2–2.5 mm0.6–0.8 mm8 mm±8–9°82 / 98SG90
H0 / HO (1:87)3 mm0.8 mm8 mm±11°79 / 101SG90 or MG90S
O (1:45)5 mm1.0 mm10 mm±15°75 / 105MG90S
G / garden (1:22.5)7–8 mm1.2–1.5 mm or a direct rod12 mm±18–20°70 / 110MG996R

Step by step: slow-motion turnout code

  1. Fix the servo under the turnout with double-sided tape or a small bracket, with the horn centred (90°) and square to the throwbar.
  2. Put the top end of the wire into the throwbar hole and the bottom end into the second hole of the servo horn; leave a small omega loop in between.
  3. Wire the button, the two LEDs and the optional relay as in the wiring table; servo plus to the external 5 V, all GNDs together.
  4. Upload the code below, open the Serial Monitor at 9600 baud and press the button to see the turnout move slowly both ways.
  5. If the blade doesn't sit tight against the stock rail, change ANGLE_STRAIGHT and ANGLE_DIVERGE one degree at a time and try again.
  6. Set the speed with STEP_MS: at 25 ms a 20-degree move takes about half a second, at 60 ms it takes 1.2 seconds.
C++ (Arduino IDE)
1// Model tren makası: buton, yavaş servo hareketi, panel LED'leri ve göbek rölesi
2// Model railway turnout: push button, slow servo motion, panel LEDs and frog relay
3#include <Servo.h>
4
5const int SERVO_PIN = 9;     // Servo sinyal kablosu (turuncu) / servo signal wire (orange)
6const int BUTTON_PIN = 2;    // Buton, diğer ucu GND / button, other leg to GND
7const int LED_STRAIGHT = 5;  // Düz yol LED'i (yeşil) / straight route LED (green)
8const int LED_DIVERGE = 6;   // Ayrılan yol LED'i (kırmızı) / diverging route LED (red)
9const int FROG_RELAY = 7;    // Göbek polaritesi rölesi / frog polarity relay
10
11const int ANGLE_STRAIGHT = 80;  // Düz konum açısı (kalibre et) / straight angle (calibrate)
12const int ANGLE_DIVERGE = 100;  // Ayrılan konum açısı (kalibre et) / diverging angle (calibrate)
13const unsigned long STEP_MS = 25;  // Derece başına bekleme, büyükse daha yavaş / delay per degree, larger is slower
14
15Servo turnout;
16int currentAngle = ANGLE_STRAIGHT;  // Şu anki açı / current angle
17int targetAngle = ANGLE_STRAIGHT;   // Hedef açı / target angle
18unsigned long lastStep = 0;
19bool lastButton = HIGH;
20unsigned long lastPress = 0;
21
22void showRoute() {
23  // LED'ler ve röle hedef konumu gösterir / LEDs and relay follow the target position
24  bool diverge = (targetAngle == ANGLE_DIVERGE);
25  digitalWrite(LED_STRAIGHT, diverge ? LOW : HIGH);
26  digitalWrite(LED_DIVERGE, diverge ? HIGH : LOW);
27}
28
29void setup() {
30  pinMode(BUTTON_PIN, INPUT_PULLUP);
31  pinMode(LED_STRAIGHT, OUTPUT);
32  pinMode(LED_DIVERGE, OUTPUT);
33  pinMode(FROG_RELAY, OUTPUT);
34  digitalWrite(FROG_RELAY, LOW);
35
36  turnout.write(currentAngle);   // attach'tan önce yaz: açılışta 90 dereceye sıçramaz / write before attach: no jump to 90 degrees
37  turnout.attach(SERVO_PIN);
38  showRoute();
39  Serial.begin(9600);
40  Serial.println(F("Makas hazir / Turnout ready"));
41}
42
43void loop() {
44  // Buton: basınca yön değiştir (50 ms debounce) / button: toggle on press (50 ms debounce)
45  bool b = digitalRead(BUTTON_PIN);
46  if (b == LOW && lastButton == HIGH && millis() - lastPress > 50) {
47    lastPress = millis();
48    targetAngle = (targetAngle == ANGLE_STRAIGHT) ? ANGLE_DIVERGE : ANGLE_STRAIGHT;
49    if (!turnout.attached()) turnout.attach(SERVO_PIN);
50    showRoute();
51    Serial.println(targetAngle == ANGLE_DIVERGE ? F("Ayrilan / Diverging") : F("Duz / Straight"));
52  }
53  lastButton = b;
54
55  // Yavaş hareket: her STEP_MS'de 1 derece / slow motion: 1 degree every STEP_MS
56  if (currentAngle != targetAngle && millis() - lastStep >= STEP_MS) {
57    lastStep = millis();
58    currentAngle += (targetAngle > currentAngle) ? 1 : -1;
59    turnout.write(currentAngle);
60
61    // Yolun ortasında göbek polaritesini çevir / switch the frog polarity at mid-travel
62    int middle = (ANGLE_STRAIGHT + ANGLE_DIVERGE) / 2;
63    if (currentAngle == middle) digitalWrite(FROG_RELAY, targetAngle == ANGLE_DIVERGE ? HIGH : LOW);
64  }
65
66  // Hedefe varınca 300 ms sonra sinyali kes: vızıltı ve titreme biter
67  // 300 ms after reaching the target, cut the signal: no buzzing or jitter
68  if (turnout.attached() && currentAngle == targetAngle && millis() - lastStep > 300) {
69    turnout.detach();
70  }
71}

The code does not use delay(); every 25 ms it moves the servo one degree and keeps reading the button in between. That way, when you later add more turnouts, signals or level-crossing lights to the same loop, none of them blocks the others. When the move is finished, the servo is released with detach() after 300 ms: with no signal the servo stops buzzing and jittering, and the friction of the plastic gears holds the blade in place. At start-up it matters that write() comes before attach(); otherwise the servo first jumps to 90 degrees. The relay swaps the frog polarity exactly at mid-travel, and the LEDs show the turnout direction on the track diagram of the panel.

Frog polarity is needed on turnouts with a metal (live) frog. Because the frog is one piece of metal, it must carry the polarity of one rail on the straight route and of the other rail on the diverging route; otherwise the locomotive stalls on the frog or you get a short circuit. Connect the relay's common terminal to the frog and its normally closed and normally open terminals to the two stock rails. Turnouts with an insulated plastic frog don't need this part, and the code works even without the relay.

A separate power supply that stops jitter

Servo jitter is the most common complaint among railway modellers, and most of the time it comes from the power supply rather than the software. Every time a servo starts to move, it draws a short current peak; on thin, long wires that current drops the voltage, the signal reference shifts and the servo twitches in place. On a layout, servo leads easily reach 1–2 metres, which makes the problem worse. Noise sources such as the digital (DCC) track supply or solenoid point motors can also couple interference into the servo wires. The table below shows how much current you need to allow; for more fixes see the servo jitter guide.

ConditionSG90MG90SRecommended 5 V supply
Idle (signal present)about 10 mAabout 10 mA-
While moving100–250 mA150–300 mA-
Stalledabout 650 mAabout 700–800 mA-
1–4 servos--5 V 2 A adapter
5–8 servos--5 V 3 A adapter
16 servos (moving together)--5 V 4–5 A adapter or from 12 V with an LM2596
  • Use a separate 5 V supply for the servos and tie its negative to the Arduino GND; never join the positive rails.
  • Place a 470–1000 µF electrolytic capacitor right next to the servo connector; it absorbs the current peak.
  • On runs longer than 1 metre use at least 0.5 mm² wire for power and route the signal wire away from the track feeders.
  • When the move is done, cut the signal with detach() or switch the channel off on the PCA9685; an idle servo then stays silent.
  • Don't skip the omega spring: if the servo presses the blade hard against the rail it stays stalled, heats up and jitters.
  • If you only have one 12 V layout supply, make 5 V with an LM2596 buck converter; don't draw servo power from the Arduino's regulator.

Position memory: start where you left off with EEPROM

When the power goes off, the Arduino forgets its variables. If the code pulls every turnout to straight at the next start, a turnout under a train standing on the diverging route moves and a wagon can derail. The fix is to write the turnout position and your calibrated angles to the EEPROM. The Uno has 1024 bytes of EEPROM and each cell lasts about 100,000 writes. Because EEPROM.put() only writes the bytes that changed, the same cell lasts for years even if you throw a turnout 50 times a day. The code below also lets you set the angles from the Serial Monitor, so you don't have to re-upload the sketch for every turnout.

C++ (Arduino IDE)
1// Makas konum hafızası (EEPROM) ve Seri Monitör'den açı kalibrasyonu
2// Turnout position memory (EEPROM) and angle calibration from the Serial Monitor
3// Komutlar / commands: d80 = düz açı / straight angle, a100 = ayrılan açı / diverging angle,
4//                      t = yön değiştir / toggle, ? = durum / status (her değişiklik kaydedilir / every change is saved)
5#include <Servo.h>
6#include <EEPROM.h>
7
8const int SERVO_PIN = 9;
9const int BUTTON_PIN = 2;
10const unsigned long STEP_MS = 25;
11
12struct TurnoutConfig {
13  byte magic;      // 0x5A ise kayıt geçerli / record is valid when 0x5A
14  byte straight;   // Düz açı / straight angle
15  byte diverge;    // Ayrılan açı / diverging angle
16  byte state;      // 0 = düz / straight, 1 = ayrılan / diverging
17};
18
19TurnoutConfig cfg;
20Servo turnout;
21int currentAngle, targetAngle;
22unsigned long lastStep = 0, lastPress = 0;
23bool lastButton = HIGH;
24
25int angleFor(byte state) { return state ? cfg.diverge : cfg.straight; }
26
27void saveConfig() {
28  EEPROM.put(0, cfg);  // put() yalnız değişen baytı yazar / put() only writes bytes that changed
29}
30
31void moveTo(byte state) {
32  cfg.state = state;
33  targetAngle = angleFor(state);
34  if (!turnout.attached()) turnout.attach(SERVO_PIN);
35  saveConfig();  // Konum her değişimde saklanır / position is stored on every change
36}
37
38void setup() {
39  Serial.begin(9600);
40  pinMode(BUTTON_PIN, INPUT_PULLUP);
41  EEPROM.get(0, cfg);
42  if (cfg.magic != 0x5A || cfg.straight > 180 || cfg.diverge > 180 || cfg.state > 1) {
43    cfg = {0x5A, 80, 100, 0};  // İlk açılış: varsayılan değerler / first boot: default values
44    saveConfig();
45  }
46  currentAngle = targetAngle = angleFor(cfg.state);
47  turnout.write(currentAngle);  // Kayıtlı konumdan başla, sıçrama yok / start from the saved position, no jump
48  turnout.attach(SERVO_PIN);
49  Serial.print(F("Konum / position: "));
50  Serial.println(cfg.state ? F("ayrilan / diverging") : F("duz / straight"));
51}
52
53void handleSerial() {
54  if (!Serial.available()) return;
55  char c = Serial.read();
56  if (c == 'd' || c == 'a') {
57    int v = constrain(Serial.parseInt(), 0, 180);
58    if (c == 'd') cfg.straight = v; else cfg.diverge = v;
59    moveTo(c == 'a' ? 1 : 0);  // Yeni açıyı hemen dene / try the new angle right away
60    Serial.print(c == 'd' ? F("Duz aci / straight = ") : F("Ayrilan aci / diverging = "));
61    Serial.println(v);
62  } else if (c == 't') {
63    moveTo(cfg.state ? 0 : 1);
64  } else if (c == '?') {
65    Serial.print(F("duz/straight=")); Serial.print(cfg.straight);
66    Serial.print(F(" ayrilan/diverging=")); Serial.print(cfg.diverge);
67    Serial.print(F(" konum/state=")); Serial.println(cfg.state);
68  }
69}
70
71void loop() {
72  handleSerial();
73
74  bool b = digitalRead(BUTTON_PIN);
75  if (b == LOW && lastButton == HIGH && millis() - lastPress > 50) {
76    lastPress = millis();
77    moveTo(cfg.state ? 0 : 1);
78  }
79  lastButton = b;
80
81  if (currentAngle != targetAngle && millis() - lastStep >= STEP_MS) {
82    lastStep = millis();
83    currentAngle += (targetAngle > currentAngle) ? 1 : -1;
84    turnout.write(currentAngle);
85  }
86  if (turnout.attached() && currentAngle == targetAngle && millis() - lastStep > 300) {
87    turnout.detach();  // Hareket bitti, sinyali kes / motion done, cut the signal
88  }
89}
Serial commandWhat it doesExample
d + numberSets the straight angle, moves the turnout to straight and savesd78
a + numberSets the diverging angle, moves the turnout to diverging and savesa103
tToggles the turnout (same as the button)t
?Prints the stored angles and position?

The magic byte at the start of the record tells the code whether the EEPROM data belongs to this program. On a new board every EEPROM byte reads 255; if the magic value is not 0x5A, the code writes the default angles (80 and 100). To calibrate, set the Serial Monitor line ending to "Newline", type d80 and send it; change the number one step at a time until the blade rests lightly against the stock rail.

16 turnouts with a PCA9685

The Uno's Servo library supports up to 12 servos, but each servo uses a pin and all pulses are generated in software, so timing gets tight on a busy panel. The PCA9685 board generates 16 servo pulses in its own hardware and connects to the Arduino with just two I2C wires (SDA, SCL). Its default address is 0x40; with the six address jumpers on the board you can give it other addresses between 0x40 and 0x7F and chain boards, so two boards give you 32 turnouts. That leaves the Uno's 16 free pins (D2–D13 and A0–A3) for 16 turnout buttons. The board takes positions in microseconds rather than degrees; 10 µs is roughly 1 degree.

PCA9685 pinArduino Uno / NanoNote
VCC5VLogic supply of the chip only
GNDGNDShared with the external supply's GND
SDAA4I2C data
SCLA5I2C clock
V+ (screw terminal)External 5 V, 4–5 AServo power; 1000 µF capacitor on the terminal
Channels 0–15Servos 0–15Plug in following the PWM / V+ / GND marking on the board
Buttons 0–15D2–D13, A0–A3INPUT_PULLUP, other leg to GND
C++ (Arduino IDE)
1// PCA9685 ile 16 makas: 16 buton, yavaş hareket, EEPROM konum hafızası ve seri panel komutları
2// 16 turnouts with PCA9685: 16 buttons, slow motion, EEPROM position memory and serial panel commands
3// Seri komut / serial command: "5a" = 5. makas ayrılan / turnout 5 diverging, "5d" = düz / straight, "5t" = çevir / toggle
4#include <Wire.h>
5#include <EEPROM.h>
6#include <Adafruit_PWMServoDriver.h>
7
8const byte COUNT = 16;
9// Buton pinleri: D2-D13 ve A0-A3 (A4/A5 I2C için boş kalır)
10// Button pins: D2-D13 and A0-A3 (A4/A5 stay free for I2C)
11const byte BUTTON_PINS[COUNT] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, A0, A1, A2, A3};
12
13// Her makasın darbe genişliği (mikrosaniye), kalibre et
14// Pulse width of each turnout in microseconds, calibrate these
15const int US_STRAIGHT[COUNT] = {1400, 1400, 1400, 1400, 1400, 1400, 1400, 1400,
16                                1400, 1400, 1400, 1400, 1400, 1400, 1400, 1400};
17const int US_DIVERGE[COUNT]  = {1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600,
18                                1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600};
19const int STEP_US = 10;            // Her adımda 10 µs (yaklaşık 1 derece) / 10 µs per step (about 1 degree)
20const unsigned long STEP_MS = 20;  // Adım aralığı / step interval
21const int EE_ADDR = 0;             // 16 makasın konumu 2 baytta (bit maskesi) / 16 positions in 2 bytes (bit mask)
22
23Adafruit_PWMServoDriver pca = Adafruit_PWMServoDriver(0x40);
24uint16_t states = 0;          // Bit 1 = ayrılan / bit 1 = diverging
25int currentUs[COUNT], targetUs[COUNT];
26bool lastBtn[COUNT];
27unsigned long lastPress[COUNT];
28unsigned long lastStep = 0, lastSave = 0;
29bool dirty = false;
30
31void setTurnout(byte n, bool diverge) {
32  if (diverge) states |= (1u << n); else states &= ~(1u << n);
33  targetUs[n] = diverge ? US_DIVERGE[n] : US_STRAIGHT[n];
34  dirty = true;
35  Serial.print(F("Makas / turnout ")); Serial.print(n);
36  Serial.println(diverge ? F(" ayrilan / diverging") : F(" duz / straight"));
37}
38
39void setup() {
40  Serial.begin(9600);
41  EEPROM.get(EE_ADDR, states);
42  if (states == 0xFFFF) states = 0;  // Boş EEPROM: hepsi düz / blank EEPROM: all straight
43
44  pca.begin();
45  pca.setOscillatorFrequency(27000000);
46  pca.setPWMFreq(50);  // Servo için 50 Hz / 50 Hz for servos
47  for (byte n = 0; n < COUNT; n++) {
48    pinMode(BUTTON_PINS[n], INPUT_PULLUP);
49    lastBtn[n] = HIGH;
50    lastPress[n] = 0;
51    bool d = states & (1u << n);
52    currentUs[n] = targetUs[n] = d ? US_DIVERGE[n] : US_STRAIGHT[n];
53    pca.writeMicroseconds(n, currentUs[n]);  // Kayıtlı konumdan başla / start from the saved position
54    delay(50);  // Servolar sırayla uyanır, akım tepesi küçülür / servos wake one by one, smaller current peak
55  }
56  Serial.println(F("16 makas hazir / 16 turnouts ready"));
57}
58
59void handleSerial() {
60  if (!Serial.available()) return;
61  char p = Serial.peek();
62  if (p < '0' || p > '9') { Serial.read(); return; }  // Satır sonu vb. atla / skip line endings etc.
63  int n = Serial.parseInt();
64  char c = Serial.read();
65  if (n < 0 || n >= COUNT) return;
66  if (c == 'a') setTurnout(n, true);
67  else if (c == 'd') setTurnout(n, false);
68  else if (c == 't') setTurnout(n, !(states & (1u << n)));
69}
70
71void loop() {
72  handleSerial();
73
74  // Butonlar / buttons
75  for (byte n = 0; n < COUNT; n++) {
76    bool b = digitalRead(BUTTON_PINS[n]);
77    if (b == LOW && lastBtn[n] == HIGH && millis() - lastPress[n] > 50) {
78      lastPress[n] = millis();
79      setTurnout(n, !(states & (1u << n)));
80    }
81    lastBtn[n] = b;
82  }
83
84  // Tüm makaslar aynı anda yavaşça ilerler / all turnouts move slowly at the same time
85  if (millis() - lastStep >= STEP_MS) {
86    lastStep = millis();
87    for (byte n = 0; n < COUNT; n++) {
88      if (currentUs[n] == targetUs[n]) continue;
89      int diff = targetUs[n] - currentUs[n];
90      currentUs[n] += constrain(diff, -STEP_US, STEP_US);
91      pca.writeMicroseconds(n, currentUs[n]);
92    }
93  }
94
95  // EEPROM'a en fazla 2 saniyede bir yaz / write to EEPROM at most every 2 seconds
96  if (dirty && millis() - lastSave > 2000) {
97    lastSave = millis();
98    EEPROM.put(EE_ADDR, states);
99    dirty = false;
100  }
101}

For this code, install the Adafruit PWM Servo Driver Library from the Library Manager. The program keeps the position of all 16 turnouts in a two-byte bit mask: a bit set to 1 means diverging. At start-up it wakes the servos 50 ms apart at their saved positions, so the 16 servos don't all draw current at once. Every 20 ms the loop moves each servo that hasn't reached its target by 10 µs, so several turnouts thrown together move slowly at the same time. The EEPROM is written at most every two seconds, so pressing buttons in quick succession while setting a route doesn't wear the cells for nothing. A panel program on your computer or the Serial Monitor can send commands like "5a" to set turnout 5 to diverging. For a panel with LEDs, a second PCA9685 (address 0x41) can drive the LEDs.

Project ideas

  • Idea: A route-setting button that throws every turnout of a station throat at once; write the logic as a state machine.
  • Idea: Put a reed switch or a Hall sensor under the track so the turnout throws automatically when the magnet under a locomotive passes.
  • Idea: A small block system that switches the colour light signal beside the turnout from red to green whenever the turnout changes.
  • Idea: Move the code to an ESP32 for phone control; start the web interface from the ESP32 servo web control article.
  • Idea: A safety lock with an infrared sensor that stops the turnout from moving while a locomotive is standing on it.
  • Idea: Drive level-crossing barriers with the same slow servo code, together with flashing LEDs.

Common problems and fixes

SymptomLikely causeFix
All turnouts twitch at power-upwrite() comes after attach(), or the servo supply comes up before the ArduinoCall write() before attach() and start from the EEPROM position
Servo jitters or buzzes in placeWeak supply, no common ground, or the servo presses hard on the bladeSeparate 5 V, shared GND, 1000 µF, omega spring, detach() after the move
Blade doesn't sit against the stock railAngle too small or wire too flexibleAdd 1–2 degrees, use thicker wire
Locomotive stalls on the frogMetal frog not polarisedPolarise the frog with a relay or microswitch
One press fires twiceContact bounceRaise the 50 ms debounce to 80–100 ms
Servo doesn't move on the PCA9685No power on the V+ terminal or wrong addressFeed 5 V to V+, confirm the address (0x40) with an I2C scanner
The D13 button always reads pressedOn older boards the D13 LED pulls the input lowMove that button to another pin or add an external 10 kΩ pull-up
Before screwing the servo permanently under the board, test the turnout on the workbench with a piece of track: calibrate it, read the values with the ? command and write them down. Hunting for angles upside down under the layout is tiring and invites mistakes. When you fit the horn, make sure the servo sits at 90 degrees; shifting the horn by a single spline tooth already makes a difference of about 15 degrees.

Servo turnout control is one of the projects that make a big difference on a model railway for a small budget: start with a single turnout and grow the same code to 16 turnouts with a PCA9685, or 32 with two boards. If you want to see the basics of driving a servo, reading buttons and LED indicators step by step, the BlueGrays app has servo, button and LED projects with circuit diagrams and ready-to-use code.

Frequently asked questions

Which servo is best for model railway turnouts?

For N, TT and H0 scale, a 9-gram SG90 micro servo is enough and is the cheapest option. On busy turnouts or turnouts with stiff blades, the metal-gear MG90S lasts longer. For large turnouts such as G-scale garden railways, choose a stronger servo like the MG996R.

How many degrees should a turnout servo move?

The servo doesn't sweep 0–180 degrees; a small angle either side of 90 degrees is enough. On an H0 turnout with a horn hole 8 mm out, about ±11 degrees (79 and 101 degrees) is a good start. Add 2–4 degrees for the omega spring and calibrate each turnout separately.

Why does my turnout servo jitter?

The most common causes are a weak supply and a missing common ground; if the servo runs from the Arduino 5V pin, the voltage dips as it moves. Give the servos a separate 5 V supply, join the grounds and put a 1000 µF capacitor next to the servo. Cutting the signal with detach() after the move and using an omega spring also stop the jitter.

How many turnouts can an Arduino control?

With the Uno's Servo library you can drive up to 12 servos directly. A PCA9685 board drives 16 servos on its own, and with its address jumpers dozens of boards can share one I2C bus; two boards give you 32 turnouts. The real limit is usually the number of buttons, so large panels use serial commands, a keypad or an I/O expander.

Does a servo turnout forget its position after a power cut?

The variables live in RAM, so the Arduino forgets the position and the code starts from its default. If you write the turnout position to EEPROM, the servo starts where it left off at the next power-up and a turnout under a train doesn't move. Calling write() before attach() also prevents the jump at start-up.

Can servo turnouts be used with DCC?

Yes. An Arduino can read the DCC signal with a simple optocoupler circuit and the NmraDcc library and decode accessory addresses; you then drive the servo with the slow-motion code in this article. That way you throw turnouts from your command station or control software. Getting the button and panel version working first and adding DCC afterwards makes the job easier.

See all projects
Toggle an LED with a Button (On/Off)
AR-10Beginner

Toggle an LED with a Button (On/Off)

Press the button once and the light comes on, press it again and it goes off, just like the light switch in your room.

4.7(105)
183
Using a Servo Motor
AR-35Beginner
Premium

Using a Servo Motor

The arm of a small servo motor turns to three positions in turn: all the way to the start, right to the middle and all the way to the end, waiting two seconds at each stop.

4.7(49)
69
Servo Motor Operation with Potentiometer
AR-36Beginner
Premium

Servo Motor Operation with Potentiometer

As you turn the potentiometer knob, the servo motor's arm turns right along with it: one end of the knob means zero degrees, the other end means half a turn.

4.6(37)
54
Servo Circle Choreography - Animated Patterns with 32 Servos
AR-97Advanced
Premium

Servo Circle Choreography - Animated Patterns with 32 Servos

A visual animation project driven by 32 servo motors arranged in a circle on an Arduino Mega. The servos are managed in a single array, connected to the Mega's pins 22–53, and perform four motion sequences: a chaotic jitter at random angles, a synchronized sweep, a wave travelling around the circle and a compass needle swinging left and right.

4.5(40)
62
Servo Control with Joystick
AR-60Intermediate
Premium

Servo Control with Joystick

Steer two motors with a joystick, just like turning a security camera. Push the stick left or right and the bottom servo motor slowly turns, push it up or down and the top servo tilts up and down…

4.7(42)
58
ESP32 Servo Motor (Potentiometer Control)
ES-16Intermediate
Premium

ESP32 Servo Motor (Potentiometer Control)

In this project, we control an SG90 servo motor using a potentiometer. We adjust the servo angle by mapping the analog value read from the potentiometer to the 0–180-degree range. The ESP32Servo library generates servo signals on suitable output-capable GPIO pins of the ESP32; this project uses GPIO 18. This is a fundamental control method for robotic arms, camera gimbals, and automatic door mechanisms.

4.3(30)
42