Objectives
- Set up NodeMCU to communicate to an MQTT server
- Set up an MQTT server on Raspberry Pi
- Send data from NodeMCU to Raspberry Pi
Things
- NodeMCU
- Breadboard
- Raspberry Pi
- Micro USB cable
Let’s begin!
MQTT is a communication protocol used to communicate between connected devices. Devices can publish data and several other devices can subscribe to the data published by other devices. In our case, the NodeMCU will publish data and the Raspberry Pi will be subscribed to the NodeMCU’s data.
Note: If for any reason, you do not have Arduino IDE or NodeMCU installed on your Arduino IDE, follow the steps in this unit.
Setting up the NodeMCU for MQTT Communication
Install PubSubClient by Nick O’Leary on the Arduino IDE
Step 1: Navigate to Sketch->Include library->Manage libraries…
Step 2: Search for PubSubClient
Step 3: Install the library PubSubClient by Nick O’Leary
Interfacing NodeMCU with IR sensor (analog)
Setting up Raspberry Pi for MQTT Communication
We will install paho MQTT to use in Python and Mosquitto to use from the terminal.
Update everything by typing following command,
sudo apt-get update
sudo apt-get install build-essential python-dev python-openssl
Now let’s install a package called Mosquitto which is an MQTT Client. We can do this by running the command
sudo apt-get install mosquitto mosquitto-clients
In order to install paho enter the following command in your terminal.
pip install paho-mqtt
The mqtt client is now installed.
nano nodemcu.py
Copy paste the following code into the editor. Make sure to change the IP address to the address of your Raspberry Pi.
To run the code, execute the following command
python nodemcu.py