Hello all.
I am trying to activate a relay module after pushing a button.
After uploading code when I push the button nothing happens.
When I serial print "If ((digitalRead(pushButton) == LOW) && (relayBState == HIGH)) and push button, serial monitor shows " Button is Pushed" msg 5-6 times with each press.
When I change digitalRead(pushButton) ==HIGH) and run the code, it works as expected, only it just toggles relay LOW to HIGH continuously.
I just want to turn relay 'ON' only when button is pushed and turn itself 'OFF' after 'const unsigned long offTime' is over. Please advise. Could not understand why it doesn't work when I push the button.
My code:
[
const byte relayB = 7; // output pin no for relayB
const byte pushButton = 9; // input pin for pushbutton
const byte led = 13; // outputpin for LED
byte relayBState; // to store state of relayB
unsigned long currentMillis;
unsigned long previousMillis = 0;
unsigned long debounceOnTime = 200; // debounce time for push button
const unsigned long offTime = 10000; // time to stop relay after button is pushed
void setup()
{
pinMode (relayB,OUTPUT);
pinMode (pushButton, INPUT_PULLUP);
pinMode (led, OUTPUT);
digitalWrite (relayB, HIGH);
digitalWrite (led, LOW);
Serial.begin(9600);
}
void loop()
{
currentMillis = millis();
relayBState = digitalRead(relayB);
if ((digitalRead(pushButton) == LOW) && (relayBState == HIGH))
{
//Serial.println ("BUTTON is PUSHED");
if ((relayBState == HIGH) && (currentMillis - previousMillis == debounceOnTime))
{
digitalWrite(led, HIGH);
digitalWrite(relayB, LOW);
previousMillis = currentMillis;
Serial.println("LED IS ON NOW");
Serial.println ("RELAY IS TURNED ON");
Serial.println("motor is running.....");
}
}
else if ((relayBState == LOW) && (currentMillis - previousMillis == offTime))
{
digitalWrite(led, LOW) ;
digitalWrite(relayB, HIGH);
previousMillis = currentMillis;
Serial.println("LED isOff now!");
Serial.println ("RELAY is turned OFF!");
Serial.println("motor is NOT RUNNINGG.");
}
}
]