Advertisement
kartonman

Servo and turnout control using a switch

Sep 14th, 2021
300
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Servo and turnout control using a switch, button or control signal. This sketch is specially coded to prevent servo wag at the end of its travel. It was created by Gary Granai, steamtraininfo.com with the assistance of Jim Weisenbach, Seattle, Washington. Full documentation can be found at VVVVVVV.
  2. You are free to use this sketch and modify it as long as everything in these credits remains unchanged. */
  3.  
  4. #include <Servo.h>
  5.  
  6. #define toggle 12 //the servo is controlled by a simple on/off toggle switch, latching push button or external control signal.
  7.  
  8. Servo myservo;
  9. int pos;
  10. void setup() {
  11.  
  12. pinMode(toggle, INPUT_PULLUP); // Pin 12 is used for control. This eliminates the need to add
  13. //a dropping resistor to the switch.
  14. myservo.attach(2); // attach the servo control wire to pin 2
  15. pos = 0; // the starting postion of the servo. Change as you desire.
  16. delay(50); // sets the speed of the servo. Change as you desire.
  17. }
  18.  
  19. void loop() {
  20.  
  21. if (digitalRead(toggle) == LOW) {
  22. while (pos < 45) { // the ending position of the servo. Change as you desire.
  23. pos += 1;
  24. myservo.write(pos);
  25. delay(50);
  26. }
  27. }
  28.  
  29. else {
  30. while (pos > 0) { //note that the while function is used to prevent servo wag.
  31. pos -= 1;
  32. myservo.write(pos);
  33. delay(50);
  34.  
  35. }
  36. }
  37. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement