'Control Relay by MQTT Publish Subcribe
sorry for my bad english, but i'll try my best
i have a code like this
void mqttCallback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic, DeviceConfig.MqttSub) == 0)
{
Serial.print("Recvd relay command parse code: ");
StaticJsonDocument<100> doc;
DeserializationError error = deserializeJson(doc, (char *)payload);
Serial.println(error.code());
if (error == DeserializationError::Ok)
{
if (doc.containsKey("state") && doc["state"].is<int>())
{
DeviceConfig.RelayOn = (doc["state"].as<int>() == 1);
Serial.print("Changing state: ");
Serial.print(DeviceConfig.RelayOn );
Serial.println();
}
}
}
}
it means if the broker send data like {state : 1}, it automactically changing state turn on, or {state : 0} to turn off, it works if i see on serial monitor, the state status is changed, but the relay is not affected at all
this is the loop function
void loop()
{
mqttReconnect();
if (client.connected() && millis() - lastSendMs >= (DeviceConfig.MqttPubSec * 1000))
{
Serial.print("Publishing:");
String json = composeSensorJson();
Serial.println(json);
Serial.println(client.publish(DeviceConfig.MqttPub, json.c_str()) ? "OK" : "FAIL");
lastSendMs = millis();
}
if (DeviceConfig.Device == Relay) {
digitalWrite(AIO_SENSOR_PIN_3, DeviceConfig.RelayOn ? LOW : HIGH);
}
client.loop();
}
why the relay is not working
this is the serial monitor if the state is 1
and this is the monitor if state is 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|