Hello!
I am trying to get traffic lights to work on my lego city build. I've written a code with millis instead of delays so I can use a button that gives a fast green light to a bus lane. But my code gets stuck on 2 green lights and 2 red lights constantly...
this here is my code:
int Red1_pin = 12;
int Yellow1_pin = 11;
int Green1_pin = 10;
int Red2_pin = 9;
int Yellow2_pin = 8;
int Green2_pin = 7;
int Bus_pin = 6;
unsigned long starttime;
unsigned long currenttime;
int state = 1;
void setup()
{
pinMode(Red1_pin, OUTPUT);
pinMode(Yellow1_pin, OUTPUT);
pinMode(Green1_pin, OUTPUT);
pinMode(Red2_pin, OUTPUT);
pinMode(Yellow2_pin, OUTPUT);
pinMode(Green2_pin, OUTPUT);
pinMode(Bus_pin, INPUT);
starttime = millis();
}
void loop()
{
if (state == 1) {
digitalWrite(Yellow1_pin, LOW);
digitalWrite(Red1_pin, HIGH);
digitalWrite(Red2_pin, HIGH);
currenttime = millis();
if(currenttime - starttime >= 2000) {
state = 2;
starttime = millis();
}
}
if(state == 2) {
digitalWrite(Green1_pin, HIGH);
digitalWrite(Red1_pin, LOW);
currenttime = millis();
if(currenttime - starttime >= 8000) {
state = 3;
starttime = millis();
}
}
if (state == 3) {
digitalWrite(Yellow1_pin , HIGH);
digitalWrite(Green1_pin , LOW);
if(digitalRead(Bus_pin) == HIGH) {
state = 4;
starttime = millis();
}
currenttime = millis();
if(currenttime - starttime >=2000) {
state = 4;
starttime = millis();
}
}
if (state == 4){
digitalWrite(Red1_pin, HIGH);
digitalWrite(Yellow2_pin, LOW);
if(digitalRead(Bus_pin) == HIGH) {
state = 5;
starttime = millis();
}
currenttime = millis();
if(currenttime - starttime >=2000) {
state = 5;
starttime = millis();
}
}
if(state == 5){
digitalWrite(Green2_pin, HIGH);
digitalWrite(Red1_pin, LOW);
currenttime = millis();
if(currenttime - starttime >=10000) {
state = 6;
starttime = millis();
}
}
if (state == 6){
digitalWrite(Red1_pin, HIGH);
digitalWrite(Red2_pin, HIGH);
if(digitalRead(Bus_pin) == HIGH) {
state = 1;
starttime = millis();
}
currenttime = millis();
if(currenttime - starttime >=2000) {
state = 1;
starttime = millis();
}
}
}
I have no clue what causes the problem there for my question to you guys, can you help me?
sorry for english, not my motherlanguage