Hi Guys, Fairly new to the world of Arduino and I am trying to create a program that flashes some LED's in a level crossing sequence until they receive the same input that was the trigger. I have written a code using bits I have learnt but it doesn't work between the while loop and the termination sequence for some reason I can't understand. One red is supposed to come on for 500 milliseconds then switch over to the other for 500 milliseconds and this carries on until the sequence is terminated. Could you please troubleshoot it for me and explain the problem. Thanks Owen
const int R1 = 12; // 1st Red light
const int A = 11; // Amber Light
const int R2 = 10; // 2nd Red light
const int trigger = 4; // Trigger
int triggerState = 0;
int running = 0;
int long interval = 500;
long previousMillis = 0;
int R1State = HIGH;
void setup() {
pinMode(R1, OUTPUT);
pinMode(A, OUTPUT);
pinMode(R2, OUTPUT);
pinMode(trigger, INPUT);
}
void loop() {
triggerState = digitalRead(trigger);
if(triggerState == HIGH && running == 0){
int running = 1; //To prevent the While loop from triggering early
digitalWrite(A, HIGH); //Gives a constant Amber
delay(5000);
digitalWrite(A, LOW);
digitalWrite(R1, HIGH);
digitalWrite(R2, HIGH); //Both Red lights come on
delay(500);
digitalWrite(R1, LOW); // One switches off
delay(500);
triggerState = digitalRead(trigger);
while(triggerState == LOW && running == 1) {
digitalWrite(R1, HIGH);
digitalWrite(R2, LOW);
unsigned long currentMillis = millis(); // Timer used instead of delay to allow input to be read at the same time
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
if (R1State == HIGH){ // Switches lights over
digitalWrite(R1, LOW);
digitalWrite(R2, HIGH);
int R1State = LOW;
}
else {
digitalWrite(R1, HIGH); // Switches lights over
digitalWrite(R2, LOW);
int R1State = HIGH;
}
}
else {
triggerState = digitalRead(trigger); // Terminates program and switches off lights if the trigger input is detected
if (triggerState == HIGH){
digitalWrite (R1, LOW);
digitalWrite (R2, LOW);
int R1State = LOW;
delay(5000);
int running = 0;
break;
}
}
}
}
}