Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
ESP8266 Home Automation Projects

You're reading from  ESP8266 Home Automation Projects

Product type Book
Published in Nov 2017
Publisher Packt
ISBN-13 9781787282629
Pages 196 pages
Edition 1st Edition
Languages
Authors (2):
Catalin Batrinu Catalin Batrinu
Profile icon Catalin Batrinu
Constantin Tambrea Constantin Tambrea
Profile icon Constantin Tambrea
View More author details
Toc

Receiving MQTT messages in the ESP8266


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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}