Connecting the IoT Remote Gate Opener to MQTT

By snorlaxprime

Now that we have a reasonable understanding about MQTT, we can connect our IoT Gate Remote from the previous post to the MQTT broker.

The idea is to have our Remote Gate opener listen to the message in the MQTT broker. Looking at our previous example, we have setup 2 topics in the message broker, “/homeautomation” and “/hello”, we can expand the “/homeautomation” into


When a message is send to “/homeautomation/gate” topic, our ESP8266 will get the message and we can act on it, which mean we can open or close the gate.

So we need to modify the code so that we can subscribe to this topic. This can be done with the following:

MQTTClient client; 
// MQTT info
 const char* thehostname = "broker.shiftr.io";
 const char* user = "tokenusername";
 const char* user_password = "tokenpassword";
 const char* id = "ESP8266";

   while (!client.connect(id, user, user_password)) {

Once this you had subscribe to the topic, we need to modify the code to perform the action when we received the message. In this example let us assume the message that we are going to receive is “OPEN”. Assuming we have the following code in the Setup() section:

void setup() {  
  client.begin(thehostname, net);

And to act on the message, we need to process the message in the messageReceived() function as below:

void messageReceived(String &topic, String &payload) {
   Serial.println("incoming: " + topic + " - " + payload);
if (payload == "OPEN"){
// open the door
digitalWrite(LEDpin,LOW); //LED ON
} else if (payload == "CLOSE") {
// close the door

Now you should be able to control the Remove Gate from the internet. We can test this by posting the “OPEN” and “CLOSE” message to the topic.

I hope you enjoy this post, if you have any questions please don’t hesitate to ask and subscribe to my blog to get more frequent update on projects that I am currently working on.