Controlling Relay using mqtt

hello guys,
i want to control my relay by mqtt broker, it's already subcribe the data from Soil Moisture Sensor, but the relay is always off

this is the logic i use

this is the callback function

void mqttCallback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();


  if (String(topic) == DeviceConfig.MqttSub) { // DeviceConfig.MqttSub = /command
    Serial.print("Changing output to ");
    if(messageTemp == "ON"){
      digitalWrite(AIO_SENSOR_PIN_3, HIGH);
      Serial.println("ON");
    }
    else if(messageTemp == "OFF"){
      digitalWrite(AIO_SENSOR_PIN_3, LOW); //AIO_SENSOR_PIN_3 expands to pin32 esp
      Serial.println("OFF");
    }
  }
}

and the value already sended
image

but the relay state is not affected at all

can you guys help me please?

At first glance, the piece of code you have posted looks OK.

I assume digitalWrite(AIO_SENSOR_PIN_3, HIGH); maps to an actual pin?

If I was doing it, I would have used the <ArduinoJson.h> library in your sketch as you could send json from your flow which would give you much more flexibility in decoding a number of different commands.
So, for example, you could send commands like...

msg.payload = {"relay":"main","action":"on"};
or
msg.payload = {"relay":"secondary","action":"off"};

The reason I say this is... you are bound to add extra relays or LEDs to your system. Plan ahead.

PS: It's not normal to start a topic-name with a /
Maybe you can change it to just... command (in your flow and in your sketch).

PPS: If you write a simple test-sketch (like the 'blink' sketch), can you turn the relay On and Off ?

What are you running the sketch on ? i.e. arduino uno, mini, ESP8266 etc etc Do you have a Fritzing schematic so we can see how that side looks ?

Craig

One of my IoT students was asking about nearly the same question that you posted on the forum.
He was using a Wemos D1 Mini - not sure what you are using. But I'm sure it could be adapted.

I've posted what we did on the forum as I think it might go some way to solving your problem.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.