Prezados,
boa tarde.
Estou desenvolvendo um simulador de presença com o Arduino UNO, que acende e apaga a luz de um determinado relé em tempos randômicos.
Essa rotina para acender e apagar já está pronta conforme abaixo (linha 51-65).
O que pretendo agora é que, ao iniciar o Arduino, a rotina esteja desligada e ao apertar um pushbuttom que está na porta 3, a rotina inicie. Caso o mesmo pushbuttom seja apertado mais uma vez, a rotina deverá parar.
Com o código abaixo, eu consigo iniciar a rotina ao apertar o botão. Mas se eu apertar novamente o pushbuttom, a rotina não é interrompida.
const int btn1 = 4;
const int LedPinON = 3;
const int LedPinOFF = 2;
const int Rele1 = 13; // LED connected to digital pin 13
long randOn = 0; // Initialize a variable for the ON time
long randOff = 0; // Initialize a variable for the OFF time
// Variables will change:
int Ativo = 0; // 0 = Desligado, 1 = Ligado
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
int reading = 0;
long time = 0; // the last time the output pin was toggled
long lastDebounceTime =0;
long debounceDelay = 1000; // the debounce time, increase if the output flickers
void setup(){ // run once, when the sketch starts
Serial.begin(9600);
randomSeed (analogRead (0)); // randomize
pinMode(Rele1, OUTPUT); // sets the digital pin as output
pinMode(btn1, INPUT);
pinMode(LedPinON, OUTPUT);
pinMode(LedPinOFF, OUTPUT);
digitalWrite(LedPinOFF, HIGH);
}
void loop(){ // run over and over again
if (digitalRead(btn1) == HIGH && millis() - lastDebounceTime > debounceDelay) { //Se botão for pressionado e tiver 1seg após último pressionamento do botão (debounce)
if (Ativo == 0){ //Se o sistema estiver Desligado (0)
Ativo = 1;
}
else{
Ativo = 0;
digitalWrite(LedPinOFF, HIGH); //Desligar LED Vermelho
digitalWrite(LedPinON, LOW); //Ligar LED Verde
Serial.println("Sistema Desligado");
}
}
do {
if (Ativo == 1){
digitalWrite(LedPinOFF, LOW); //Desligar LED Vermelho
digitalWrite(LedPinON, HIGH); //Ligar LED Verde
Ativo = 1; //Mudar variável para
lastDebounceTime = millis();
Serial.println("Sistema Ligado");
randOn = random (1000, 10000); // generate ON time between 1seg e 10seg
randOff = random (1000, 10000); // generate OFF time between 1seg e 10seg
Serial.print("Tempo ligado ");
Serial.print(randOn/1000);
Serial.println(" SEG");
Serial.print("Tempo desligado ");
Serial.print(randOff/1000);
Serial.println(" SEG");
Serial.println(" ");
digitalWrite(Rele1, HIGH); // sets the LED on
delay(randOn); // waits for a random time while ON
digitalWrite(Rele1, LOW); // sets the LED off
delay(randOff); // waits for a random time while OFF
}
} while (btn1==LOW);
time = millis();
}