Model Scenery Tutorials

Comprenshive Tips. Hints And Techniques For Budget Minded Diorama Maker, Model Train Enthusiast And Wargammer

Crossing Gate Servo

 

 

Code

#define SWITCH_PIN    2
#define SERVO_PIN     3
#define GATE_SPEED   50 // [ms] lower number is higher speed
#define GATE_OPEN    45 // angle
#define GATE_CLOSED 135 // angle
#define POTM_PIN     A0

#include 
Servo gate_servo; // creates a Servo with the name 'gate_servo'

byte angle    = GATE_OPEN;
byte setpoint = GATE_OPEN;
unsigned long time_for_servo;

void setup() {
  pinMode(SWITCH_PIN,INPUT_PULLUP);
  gate_servo.attach(SERVO_PIN);
  Serial.begin(9600);
}

void loop() {

  if(digitalRead(SWITCH_PIN) == LOW)
    setpoint = map(analogRead(POTM_PIN), 0, 1024, 2 , 179);
// alternative: setpoint = GATE_CLOSED; 
  else
    setpoint = GATE_OPEN;

  if (millis() > time_for_servo) {
    time_for_servo = millis() + GATE_SPEED;
    if (angle < setpoint) angle++;     if (angle > setpoint) angle--;
    gate_servo.write(angle);
    Serial.print(setpoint);
    Serial.print("  ");
    Serial.println(angle);
  }
}
Scroll to top