Hi Guys,
I have been racking my brain trying to get this sketch to work properly but still not 100%.
The servos are being used to open boom gates for my model railway crossing. When the train triggers the first mini reed switch the lights flash and the boom gate comes down and stays down until the second mini reed switch is triggered and the boom gate comes up and the lights stop flashing. I think i may have the servo parts wrong.
Can anyone see what I may have done wrong?
#include <Servo.h>
Servo myservo;
const int A = 8; // Amber LED
const int R1 = 9; // 1st Red LED
const int R2 = 10; // 2nd Red LED
const int G = 11; // Green Active LED
const int R = 12; // Red inactive LED
const int BL = 13; // Building Lights
const int BL2 = 14; // Building Lights2
const int buttonPin = 2; // pushbutton pin
const int S1Lights = 3; // BL Switch
const int S2Lights = 4; // BL2 Switch
int buttonState = 0; // variable for reading the pushbutton status
int running = 0;
int long interval = 400;
long previousMillis = 0;
int R1State = HIGH;
int pos = 0;
void setup() {
pinMode(R1, OUTPUT);
pinMode(R2, OUTPUT);
pinMode(G, OUTPUT);
pinMode(R, OUTPUT);
pinMode(A, OUTPUT);
pinMode(BL, OUTPUT);
pinMode(BL2, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode(S1Lights, INPUT);
pinMode(S2Lights, INPUT);
myservo.attach(7);
digitalWrite(buttonPin, HIGH);
}
// the loop routine runs and stops after last command
void loop() {
if (digitalRead(S1Lights) == HIGH) {
Lights(); // calls Lights Function
}
if (digitalRead(S2Lights) == HIGH) {
Lights2(); // calls Lights2 Function
}
int buttonState = digitalRead(buttonPin);
// the switch has been activated and the program can run
if (buttonState == HIGH && running == 0) {
int running = 1;
digitalWrite(A, HIGH);
delay(1000);
digitalWrite(A, LOW);
tone(6, 550, 1000); // play SOUND
digitalWrite(G, HIGH); // turn on GREEN LED
myservo.write(90);
delay(1000);
digitalWrite(G, LOW); // turn off GREEN LED
delay(250);
buttonState = digitalRead(buttonPin);
while(buttonState == LOW && running == 1) {
// Timer used instead of delay to allow input to be read at the same time
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
if (R1State == HIGH){ // Switches lights over
digitalWrite(R1, LOW);
digitalWrite(R2, HIGH);
R1State = LOW;
}
else {
digitalWrite(R1, HIGH); // Switches lights over
digitalWrite(R2, LOW);
R1State = HIGH;
}
}
else {
// Terminates program and switches off lights if the trigger input is detected
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH){
digitalWrite(R1, LOW); // turn the LED off
digitalWrite(R2, LOW); // turn the LED off
tone(6, 450, 1000); // play SOUND
digitalWrite(R, HIGH); // turn on RED LED
myservo.write(0);
delay(2500);
digitalWrite(R, LOW); // turn off RED LEDD
int R1State = LOW;
delay(5000);
int running = 0;
break;
}
}
}
}
}