Hello everyone,
I'm a bit confused about the boolean statements I have in my code. I am controlling a relay and an LED.
Basically when a button is pressed the relay is engaged, and at the same time I want the led to turn on.
This is working, but the following two statements are confusing me.
boolean relayOff = true; // The present state of the relay (on/off)
boolean ledOff = false; // The present state of the LED (on/off)
If relayOff = true, to me it means the relay is off, so why in the case of the ledOff = false the led of actually off. Shouldn't it be true like the relay is?
I've tried various combinations, but I just can't see it.
Hope someone can help and explain the problem.
Thanks,
Robert
/*
* Modified by Robert Budnikas
*
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-relay
*/
const int BUTTON_PIN = 2; // Arduino pin connected to button's pin
const int RELAY_PIN = 3; // Arduino pin connected to relay's pin
const int LED_PIN = 9; // The LED is connected to pin 9
boolean lastButton = LOW; // Variable containing the previous button state
boolean currentButton = LOW; // Variable containing the current button state
boolean relayOff = true; // The present state of the relay (on/off)
boolean ledOff = false; // The present state of the LED (on/off)
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
pinMode(RELAY_PIN, OUTPUT); // set arduino pin to output mode
pinMode(LED_PIN, OUTPUT); // Set the LED pin as an output
}
boolean debounce(boolean last)
{
boolean current = digitalRead(BUTTON_PIN); // Read the button state
if (last != current) // If it's different…
{
current = digitalRead(BUTTON_PIN); // Read it again
}
return current; // Return the current value
}
void loop()
{
currentButton = debounce(lastButton); // Read debounced state
if (lastButton == LOW && currentButton == HIGH) // If it was pressed…
{
relayOff = !relayOff; // Toggle the RELAY value
ledOff = !ledOff; // Toggle the LED value
}
lastButton = currentButton; // Reset button value
digitalWrite(RELAY_PIN, relayOff); // Change the RELAY state
digitalWrite(LED_PIN, ledOff); // Change the LED state
int buttonState = digitalRead(BUTTON_PIN); // read new state
if (buttonState == LOW) {
Serial.println("Power off");
digitalWrite(RELAY_PIN, HIGH); // turn on
digitalWrite(LED_PIN, HIGH); // turn on
}
else
if (buttonState == HIGH) {
Serial.println("Power on");
digitalWrite(RELAY_PIN, LOW); // turn off
digitalWrite(LED_PIN, LOW); // turn off
}
}