I'm doing a project on Arduino that involves traffic lights. If the crossing button is pressed within a 7 second interval, after waitng for 3 seconds(delay3000), I will call a function. If it's not pressed, the loop will resume as normal. I have tried with a for loop but can't seem to get around it. Help?
This is the base code that I have. How could I use a millis() fucntion in this problem? Or are there any possible solutions to this problem?
//Street1-Estado Inicial
void loop() {
digitalWrite(str1_verd,HIGH);
digitalWrite(str1_ama,LOW);
digitalWrite(str1_verm,LOW);
digitalWrite(str2_verd,LOW);
digitalWrite(str2_ama,LOW);
digitalWrite(str2_verm,HIGH);
digitalWrite(ped1_verd,LOW);
digitalWrite(ped1_verm,HIGH);
digitalWrite(ped2_verd,HIGH);
digitalWrite(ped2_verm,LOW);
//Verifica se o botao foi pressionado dps de 3s -------ISSUE
delay(3000);
int stateButton1=digitalRead(button_street1);
for (int t=7;t>=1;t--){
if(stateButton1 == false){
B_change_1();
}}
delay(1000);
digitalWrite(str1_verd,LOW);
digitalWrite(str2_ama,HIGH);
digitalWrite(str1_ama,HIGH);
delay(5000);
digitalWrite(str1_ama,LOW);
digitalWrite(str2_ama,LOW);
digitalWrite(str2_verm,LOW);
digitalWrite(str1_verm,HIGH);
digitalWrite(ped2_verd,LOW);
digitalWrite(str2_verd,HIGH);
digitalWrite(ped2_verm,HIGH);
digitalWrite(ped1_verm,LOW);
digitalWrite(ped1_verd,HIGH);
//Verifica se o botao foi pressionado dps de 3s --------ISSUE
delay(3000);
for (int t=7;t>=1;t--){
if(button_street2 == true){
B_change_2();
}}
delay(1000);
digitalWrite(str2_verd,LOW);
digitalWrite(str1_ama,HIGH);
digitalWrite(str2_ama,HIGH);
delay(5000);
loop();
}
//Funcao b_change1
void B_change_1(){
digitalWrite(str1_verd,LOW);
digitalWrite(str2_ama,HIGH);
digitalWrite(str1_ama,HIGH);
delay(5000);
digitalWrite(str1_ama,LOW);
digitalWrite(str2_ama,LOW);
digitalWrite(str2_verm,LOW);
digitalWrite(str1_verm,HIGH);
digitalWrite(str2_verd,HIGH);
digitalWrite(ped2_verm,HIGH);
digitalWrite(ped1_verm,LOW);
digitalWrite(ped1_verd,HIGH);
buzzer_alert();
digitalWrite(ped2_verd,LOW);
}
//Funcao bchange2
void B_change_2(){
digitalWrite(str2_verd,LOW);
digitalWrite(str1_ama,HIGH);
digitalWrite(str2_ama,HIGH);
delay(5000);
digitalWrite(str2_ama,LOW);
digitalWrite(str1_ama,LOW);
digitalWrite(str1_verm,LOW);
digitalWrite(str2_verm,HIGH);
digitalWrite(str1_verd,HIGH);
digitalWrite(ped1_verm,HIGH);
digitalWrite(ped2_verm,LOW);
digitalWrite(ped2_verd,HIGH);
}}}
First of all, you are repeatedly checking button press variables that can't change (though this may be intentional?) :
and
You need to update
stateButton1
by reading fromdigitalRead
in the loop, or at least every time you test it.To test if a certain amount of time has passed, you could do something similar to
You can remove the timeout bits if you want to wait indefinitely.