Introduction: RaspberryPi and NodeMCU(esp8266)-MQTT

About: Sharpening my axe

We are going to setup MQTT server and client on Raspberry Pi using Mosquitto and paho-mqtt libraries. We will read a button and if it is pressed we will Toggle LED on Arduino side.

Whereas, on Arduino we will use Adafruit MQTT library. We will use a sensor like LDR (You can use any other sensor), read it and publish it as soon as it changes to Raspberry Pi.

We need:

Raspberry Pi

NodeMCU

Step 1: Adding Libraries for Esp8266

Go to "Manage Libraries..." using your Arduino IDE and search for "MQTT" by Adafruit.

After successful installation, Add "MQTT_NodeMCU.ino" from following link:

Arduino Code

Make following changes by replacing wifi ssid, password and RPi IP Address.

#define WLAN_SSID       "#397" <br>#define WLAN_PASS       "farmhouse397" 

#define MQTT_SERVER      "192.168.0.108"

#define "led_pin"

#define "sensor_input"

Upload the sketch and open Serial Monitor at 115200

Step 2: Install MQTT Sever and Client on Raspberry Pi

First, Install Mosquitto server using:

sudo apt-get install mosquitto

Install Mosquitto Client using:

sudo apt-get install mosquitto-clients

You can validate Installation using:

systemctl status mosquitto.service

Now, we'll install paho-MQTT using:

sudo apt-get install python python-pip<br>sudo pip install RPi.GPIO paho-mqtt

Use these commands to publish -messages from raspberry pi (-hostname) to esp8266-leds (-topic).

mosquitto_pub -h raspberrypi -t "/leds/esp8266" -m "ON"

mosquitto_pub -h raspberrypi -t "/leds/esp8266" -m "OFF"

-h == > host name ==> raspberrypi (unless you have changed it)

-t == > topic

-m == > message

Step 3: Run Python Script

You can download MQTT_Pi from

https://github.com/anuragvermaa/MQTT_NodeMCU

If everything is fine, you should be able to see sensor data in terminal.

Press Ctrl+C to exit.