NodeMCU MQTT Relay keep swith ON When restart


#1

Hello all,
I need help with sample MQTT sketch code for 4ch relay because my codes keep turning relay ON when device restart or reboot so i have manualy switch off from app side.
Thanks all :slight_smile:

This is my code

}
CAYENNE_IN(6) //------------------- RELAY 2
{
// get value sent from dashboard
int currentValue = getValue.asInt(); // 0 to 1
// assuming you wire your relay as normally open
if (currentValue == 0 ) {
digitalWrite(D6, HIGH);
} else {
digitalWrite(D6, LOW);
}
}


#2

Hi @marcx.han

Which board are you using?
I found a workaround to this: Storing the last value to EEPROM, so when the device restarts, it reads the previously stored value. The last replies of this post might help (that’s how I did it with a NodeMCU Esp8266 :slight_smile: )


Cheers!
Marc


#3

You could also put a virtual write in your setup block that just sets it LOW every time after cayenne connects. May or may not work depending on what your setup is like. Here is a example that I use in one of my temp stations using EEPROM and a virtual write to sync up the state after a reboot (from sleep).

EEPROM.begin(512);  

buttonEnabled = EEPROM.read(eepromAddress);    // checks if it is in a sleep cycle
sleepDisabled = digitalRead(sleepDisablePin);     // checks for sleep cycle bypass

Cayenne.begin(username, password, clientID, ssid, wifiPassword);

if (sleepDisabled == 0)       // stops sleep cycle if jumper LOW
{
	sleepNow = 0;
	buttonEnabled = 0;
	Cayenne.virtualWrite(0, 0, "digital_sensor", "d");  // syncs sleep cycle status to sleep button on dashboard, in this case off
}

#4

Thanks for your help @spacefolder @vapor83.
@spacefolder now im using arduino nano with esp8266, i will try using your code to nodemcu later.
how to put your code to nano?


#5

Pretty much all Arduino devices can use the same libraries (exceptions being the processors, but most libraries are ported for all variants) so it should work the same on the nano as well. I don’t have a nano, but I know @vapor83 uses nano’s, maybe he would know?