SPCoast
Railroading on the Southern Pacific Coast

Arduino Semaphore Example

From SPCoast

Jump to: navigation, search

[edit] Arduino demo sketch showing how to drive a 3-position semaphore

This sketch uses a BareBones Arduino configured with a servo on A1, and 1K pullups on D2 and D3

Compare to Wayne's NE555 based circuit


Prototyped Semaphore driver
Prototyped Semaphore driver

Download the complete sketch as a zip archive

// Model Railroad Servo Driver for Semaphore blades
// by John Plocher
// Application: drive a servo based on yellow or green inputs
 
#include <Servo.h>
 
Servo semaphore;
                                   // With neither D2 or D3 grounded, the semaphore shows Red
#define yellowPin        2        // D2 - use a 1k ohm pullup to 5v, ground this pin to get Yellow
#define greenPin         3        // D3 - use a 1k ohm pullup to 5v, ground this pin to get Green
#define semaphorePin    14        // A1 - pwm output for servo
 
#define REDPOS          20        // Servo positions - Change to match your devices
#define YELLOWPOS       80
#define GREENPOS       110
 
enum States { Red, Yellow, Green };
byte currentstate;
byte newstate;
 
void setup(){
    pinMode(yellowPin,    INPUT);
    pinMode(greenPin,     INPUT);
    pinMode(semaphorePin, OUTPUT);
 
    semaphore.attach(semaphorePin);
    semaphore.write(REDPOS); 
    currentstate = Red;
    newstate     = Red;
}
 
void loop() { 
    // get state of inputs
    if (digitalRead(yellowPin) == 0) {
        newstate = Yellow;
    } else if (digitalRead(greenPin) == 0) {
        newstate = Green;
    } else {
        newstate = Red;
    }
    // Set servo position based on inputs
    if (newstate != currentstate) {
        switch (newstate) {
            case Green:
                semaphore.write(GREENPOS); 
                currentstate = Green;
            break;
           
            case Yellow:
                semaphore.write(YELLOWPOS); 
                currentstate = Yellow;
            break;
           
            default:
            case Red:
                semaphore.write(REDPOS); 
                currentstate = Red;
            break;
        }
    }
}