Basic Turnout And Servo Control

 

The sketch can be used or controlling model railroad turnouts and other animated scenes. The sketch can be
loaded and used on an Arduino Nano.

The basic sketch was created by Gary Granai August 16, 2021 and then modified to eliminate servo wag with
much appreciated code modification help by Jim Weisenbach, Seattle, Washington of the Facebook Group, Arduino For Model Railroaders

The Sketch

The sketch is located at Pastbin where you can review it and download it in ASCII format for immediate and safe loading into your IDE. The link is here.

 

 

 

Wiring diagrams, video and discussion located at Basic Turnout And Servo Control.

Many other arduino projects can be found in the Arduino Projects Chapter

You may use this sketch and modify it as long as these credits remain in place and remain unmodified.
*/

#include <Servo.h>

#define toggle 12 //the servo is controlled by a simple on/off toggle switch or latching push button.

Servo myservo;
int pos;
void setup() {

pinMode(toggle, INPUT_PULLUP); // Pin 12 is used for control. This eliminates the need to add
//a dropping resistor to the switch.
myservo.attach(2); // attach the servo control wire to pin 2
pos = 0; // the starting postion of the servo. Change as you desire.
delay(50); // sets the speed of the servo. Change as you desire.
}

void loop() {

if (digitalRead(toggle) == LOW) {
while (pos < 45) { // the ending position of the servo. Change as you desire.
pos += 1;
myservo.write(pos);
delay(50);
}
}

else {
while (pos > 0) { //note that the while function is used to prevent servo wag.
pos -= 1;
myservo.write(pos);
delay(50);

}
}
}

End Code

Tell others about this information by using one of these services. Thank you for the support.
Scroll to top