The following code should, when a button is pressed, execute the commands once. If the user holds the button pressed, the code must also be executed only once, as if it were just a pulse on the button. When you release the button, the system should be ready to repeat the routine.
I tested using the Serial Monitor, and the code meets my need, but when connecting the Arduino to the electrical / electronic system, it presents inaccurate behavior, sometimes obeying the routine, sometimes looping after the first button.
Would anyone have any tips to help me? I am already trying to solve this problem for a few days, I have already re-programmed it in several ways, but I always encounter this same problem.
int x=0;
int ledVermelho = 8, ledVerde = 9, sensor = 12, aspersor = 7, cooler = 5;
void setup() {
pinMode(ledVermelho, OUTPUT); // seta o pino 9 como saÃda
pinMode(ledVerde, OUTPUT); // seta o pino 10 como saÃda
pinMode(aspersor, OUTPUT); // seta o pino 11 como saÃda
pinMode(cooler, OUTPUT); // seta o pino 12 como saida
pinMode(sensor, INPUT); // seta o pino 13 como entrada
digitalWrite(aspersor, LOW); // desliga o aspersor
digitalWrite(cooler, LOW); // desliga o cooler
digitalWrite(ledVermelho, LOW); // desliga o led vermelho
digitalWrite(ledVerde, HIGH); // liga o led verde
Serial.begin(9600);
Serial.println("aguardando ");
}
void loop() {
if(digitalRead(sensor)){
if(x==0){
digitalWrite(aspersor, HIGH);
digitalWrite(ledVerde, LOW);
digitalWrite(ledVermelho, HIGH);
Serial.println("aspersor ativado");
delay(1000);
digitalWrite(aspersor, LOW);
digitalWrite(cooler, HIGH);
Serial.println("cooler ativado");
delay(3000);
digitalWrite(ledVermelho, LOW);
digitalWrite(cooler, LOW);
digitalWrite(ledVerde, HIGH);
Serial.println("processo concluido");
}
x=1;
}
else{
Serial.println("sensor desativado");
x=0;
}
}