Hi,
I'm new to Arduino and i'm trying to switch two lamps with couple of relays controlled by a push button.
The idea is when i push the button once, it toggles an LED to HIGH and send signal to the relays to turn on for couple of seconds then turn off the first one and turn the second one for longer time then STOPS till I push the button again.
The problem is when I upload the code, it waits my push, I push it then LED turns on and relays start to work fine according to delays but the problem that they keep looping forever even I pushed the button again to set them LOW again. Seems the looping process is preventing the code to read my second push to turn it off.
here is the code:
const int valveRelay1 = 7;
const int valveRelay2 = 6;
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // the current state of the output pin
int reading;
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(valveRelay1, OUTPUT);
pinMode(valveRelay2, OUTPUT);
Serial.begin(9600);
}
void loop() {
// read the state of the switch into a local variable:
reading = digitalRead(buttonPin);
Serial.println(reading);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
// this is all that's new to the code
// toggles the ledState variable each time the button is pressed
if (buttonState == HIGH) {
ledState = !ledState;
Serial.println(ledState);
}
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
buttonState = reading;
}
digitalWrite(ledPin, ledState);
lastButtonState = reading;
switch (ledState) {
case 1:
digitalWrite(valveRelay1, HIGH);
delay(1000);
digitalWrite(valveRelay1, LOW);
digitalWrite(valveRelay2, HIGH);
delay(3000);
digitalWrite(valveRelay2, LOW);
break;
case 0:
digitalWrite(valveRelay1, LOW);
digitalWrite(valveRelay2, LOW);
break;
}
}