This update covers power outages and what happens next. This code retains the last state of the relay and uses that as the initial value instead of the switch position. If you would rather have the light come on in the state of the switch on reset use the code in my other post.
#include <EEPROM.h>
boolean FanStart = false;
boolean LightStart = false;
int LightRelay = 7; // pin the light relay is connected to
int FanRelay = 6; // pin the fan relay is connected to
int FanSwitch = 3; // pin the fan switch is connected to
int LightSwitch =2; // pin the light is connected to
int relayValLight = 0; // sets the lights initially to off
int relayValFan = 0; // sets the fan initially to off
char ser; // Serial character received
int reading; // the current reading from the input pin
int previous = HIGH; // the previous reading from the input pin
int reading1; // the current reading from the input pin
int previous1 = HIGH; // the previous reading from the input pin
void setup(void){
Serial.begin(115200);
pinMode(FanSwitch,INPUT_PULLUP);
pinMode(LightSwitch, INPUT_PULLUP);
pinMode(LightRelay, OUTPUT);
pinMode(FanRelay, OUTPUT);
digitalWrite(FanRelay,LOW);
digitalWrite(LightRelay,LOW);
}
void loop(void){
if (Serial.available()) {
ser = Serial.read();
if (ser == '1')
AllOff();
else if(ser == '2')
toggleFan();
else if(ser == '3')
toggleLight();
else if(ser == '4')
Serial.println(digitalRead(LightRelay));
else if(ser == '5')
Serial.println(digitalRead(FanRelay));
}
reading = digitalRead(FanSwitch);
if (reading == HIGH && previous == LOW || reading == LOW && previous == HIGH){
toggleFan();
previous = reading;
}
reading1 = digitalRead(LightSwitch);
if (reading1 == HIGH && previous1 == LOW || reading1 == LOW && previous1 == HIGH){
toggleLight();
previous1 = reading1;
}
}
void toggleFan() //Function for fan
{
if (FanStart == true)
{
relayValFan ^= 1; // xor current value with 1 (causes value to toggle)
digitalWrite(FanRelay, relayValFan);
EEPROM.write(0,relayValFan);
// Serial.println("NoEEPROM");
}
else {
relayValFan = EEPROM.read(0);
digitalWrite(FanRelay,relayValFan);
FanStart = true;
// Serial.println("EEPROM");
}
}
void toggleLight() // Function for light
{
if (LightStart == true )
{
relayValLight ^= 1; // xor current value with 1 (causes value to toggle)
digitalWrite(LightRelay, relayValLight);
EEPROM.write(1,relayValLight);
// Serial.println("NoEEPROM");
}
else {
relayValLight = EEPROM.read(1);
digitalWrite(LightRelay,relayValLight);
LightStart = true;
// Serial.println("EEPROM");
}
}
void AllOff() //Function to turn all lights off
{
relayValFan = 0;
relayValLight = 0;
digitalWrite(LightRelay, LOW);
digitalWrite(FanRelay,LOW);
EEPROM.write(0,relayValFan);
EEPROM.write(1,relayValLight);
}
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.