0
The following code must, when pressing a button, execute the commands once. If the user holds the button pressed, the code should 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, however when connecting the Arduino to the electrical/electronic system, the same presents inaccurate behavior, sometimes obeying the routine, sometimes looping after the first push of the button.
Would anyone have any tips to help me? I’ve been trying to solve this problem for a few days, I’ve already re-scheduled several ways, but I always find 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;
}
}
I believe it is a problem with the mechanical noise of the button. Search about deboucing that will probably solve your problem.
– Woss
The problem is debouncing as Anderson indicated. It can either solve with debouncing hardware or debouncing software. Start by reading what the Arduino documentation already has in this sense here and here
– Isac
Thanks Anderson and Isac. The problem was the same noise. I solved it with the deboucing software of the Isac link. I’m new to the forum, I don’t know how to flag as an answered question or something like.
– Paulo Sérgio