Now let's publish a message using mosquitto_pub
and receive it in the ESP8266.
For this the ESP8266 needs to subscribe to the same topic on which mosquitto_pub
will publish the message. Let's call the topic outdoor/light
and it will publish on 0
or 1
values. If the ESP8266 receives the value as 1
, it will turn on a LED connected to GPIO 12 and if it will receives a 0
, it will turn off that LED:
#include <ESP8266WiFi.h> #include <PubSubClient.h>
Update these with values suitable for your network:
const char* wifi_network= "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; const char* mqtt_serv_address = "YOUR_MQTT_SERVER_IP"; const int mqtt_port_number = 1883; #define OUTDOOR_LIGHT 12 WiFiClient espClient; PubsubClient client(espClient); long lastMsg; = 0;
Start the connection to the Wi-Fi network and set the name of the function that will be called when a message is received from the MQTT broker, as follows:
void setup...