Posts Tagged ‘ESP8266’
MQTT Communication with Arduino using ESP8266 ESP-01
I was doing some experiments with Arduino connected to WiFi using ESP8266 module. The priority of my experiment was to establish MQTT communication with my local MQTT server and Arduino. I tried so many Arduino libraries for ESP8266 but none of them are compatible with PubSubClient, a good MQTT library for Arduino. Today I come across a library called WiFiEsp, it has similar footprints of Arduino WiFi library, and it can work with PubSubClient. This post deals with how to utilize both PubSubClient and WifiEsp libraries to establish MQTT communication with an MQTT server.
Connecting ESP8266 to Arduino
-
I powered ESP8266 directly from my Arduino’s 5V. You shouldn’t do that, it may damage the wifi module as it deals with 3.3v. This wifi module need more current than Arduino’s 3.3v pin can provide, so connecting Arduino 3.3v to Wifi module will not work. A good option is to connect Arduino 5v to a 3.3v voltage regulator like LM1117/LD117 and power the wifi module from LM*. Connect both VCC and CH_PD pin of ESP to 3.3v power.
-
ESP8266 GND to Arduino GND. If powering ESP externally then Arduino and ESP should have a common GND.
-
ESP8266 TXD to Arduino RXD, in the below sketch I used Softserial and connected to D2.
-
ESP8266 RXD to Arduino TXD. Arduino Pin supply 5v and can damage the wifi module. So I used two resistors to create a voltage divider (Google search and you will get it). In the below sketch I used Softserial and connected to D3.
Arduino Sketch
I decided to write a sketch to see the MQTT in action. Below sketch is just a combination of samples provided in WifiEsp and Pubsubclient. I just combined both sample codes to verify the communication, so nothing special. The end result is, Arduino could establish MQTT connection to my MQTT server and send and receive messages for subscribed topics.
#include <WiFiEsp.h> #include <WiFiEspClient.h> #include <WiFiEspUdp.h> #include "SoftwareSerial.h" #include <PubSubClient.h> IPAddress server(10, 0, 0, 2); char ssid[] = "XYZ"; // your network SSID (name) char pass[] = "pwd"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status // Initialize the Ethernet client object WiFiEspClient espClient; PubSubClient client(espClient); SoftwareSerial soft(2,3); // RX, TX void setup() { // initialize serial for debugging Serial.begin(9600); // initialize serial for ESP module soft.begin(9600); // initialize ESP module WiFi.init(&soft); // check for the presence of the shield if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue while (true); } // attempt to connect to WiFi network while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network status = WiFi.begin(ssid, pass); } // you're connected now, so print out the data Serial.println("You're connected to the network"); //connect to MQTT server client.setServer(server, 1883); client.setCallback(callback); } //print any message received for subscribed topic void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i=0;i<length;i++) { Serial.print((char)payload[i]); } Serial.println(); } void loop() { // put your main code here, to run repeatedly: if (!client.connected()) { reconnect(); } client.loop(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect, just a name to identify the client if (client.connect("arduinoClient")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish("command","hello world"); // ... and resubscribe client.subscribe("presence"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }
For testing MQTT communication, I wrote a Server and a Client couple of months ago, both are node js apps and can run in my development machine. Server uses Mosca and Client uses MQTT module.
Below is the code for Server and Client.
Server
var mosca = require('mosca'); var ascoltatore = { //using ascoltatore type: 'mongo', url: 'mongodb://localhost:27017/mqtt', pubsubCollection: 'ascoltatori', mongo: {} }; var moscaSettings = { port: 1883, backend: ascoltatore, persistence: { factory: mosca.persistence.Mongo, url: 'mongodb://localhost:27017/mqtt' } }; var server = new mosca.Server(moscaSettings); server.on('ready', setup); server.on('clientConnected', function (client) { console.log('client connected', client.id); }); // fired when a message is received server.on('published', function (packet, client) { console.log('Published', packet.payload); }); // fired when the mqtt server is ready function setup() { console.log('Mosca server is up and running'); }
As you can see, server uses Mongodb to persist the client connection, run a mongodb instance before running MQTT server.
Client
var mqtt = require('mqtt'); var client = mqtt.connect('mqtt://10.0.0.2', {clientId:'nodeapp'}); client.on('connect', function () { client.subscribe('command'); client.publish('presence', 'Hello mqtt'); }); client.on('message', function (topic, message) { console.log('from mqtt ' + message.toString()); });
Happy coding…