MQTT on the ESP-8266

It’s time for the fun stuff now.  Building some sensors that can talk to my local MQTT broker built in a router.  I’m starting with the ESP-8266.  I decided to use the ESP-8266 because I have a few, they are fairly popular and versatile, so why not?

The particular model I am using is the ESP-12-Q from AI-Thinker, I managed to solder two sets of pin headers onto the top side of the device.  I chose to do this so I would not cover up the pin labels on the underside of the board.  If I were to do this again however, I would put the headers on the bottom side of the circuit board. The lower header is at an angle due to interference with the chip cover and is very weak, but it’ll do for now.  20170118_151004-1

I am using the following reference materials:

I’m examining the following three stages:

  1. Initial Setup – I’m programming the ESP-8266 with code that I’ve written to enable features like MQTT, serial communication, OTA updates, etc.
  2. Protyping Sensors – I’m attatching different sensors and actuators, both analogue and digital to the ESP-8266 and having it report the sensor values either via serial communication, MQTT or other means
  3. IoT Operations – I’m using a combination of the ESP-8266, sensors, actuators and a power source to have a remotely operating connected IoT device.

Hardware connections and initial testing

esp8266-12e

The above picture shows the available pins on the ESP board that I’m using.  I’m starting using a FTDI Basic USB to serial adapter to program the ESP.  I’ve connected it as shown below, using a separate 3v3 supply because the ESP draws an average of 80 mA  and up to 170 mA while transmitting, whereas the FT232RL in the FTDI Basic can only supply a maximum current of 24 mA.  The connection setup used for programming is shown below.

programming-mode

To run the ESP, the GPIO0 pin is pulled high and the chip is reset.  It can be reset, either by connecting the REST pin to GND or by cycling power to the entire board.

In this project, the ESP will connect to an Arduino Mega using the serial port.  The Mega will send data packets to the ESP, which will then send them on to the MQTT broker.  For debugging purposes, all of the serial communications between the Mega and the ESP will be mirrored on the Mega’s USB serial port.

MQTT Code

Starting with the following basic code to connect the ESP to the MQTT broker.

#include "ESP8266WiFi.h"
#include "PubSubClient.h"

const char* ssid = "Your_SSID";
const char* password = "Your_Wifi_pswd";
const char* mqtt_server = "10.10.10.0";
const char* clientID = "YourID";
const char* mqtt_username = "Your_MQTT_Username";
const char* mqtt_password = "Your_MQTT_Pswd";

uint8_t MAC_array[6];
char MAC_char[18];

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];

Here we are using the ESP8266WiFi and the PubSubClient Libraries.  The constant strings, ssid, password, mqtt_server, clientID, mqtt_username, and mqtt_password need to be set to match the wifi and mqtt broker settings.  The MAC_array and MAC_char are used to store the mac address of the ESP8266.

Lastly instances of WiFiClient and PubSubClient are initialized, allocating some space to hold message data.

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}

The setup function, above, starts the serial port, sets up the WiFi and then sets theMQTT server parameters.  The function to setup the WiFi is shown below.

void setup_wifi() {

delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

The Wifi.begin() and the while loop in the setup_wifi() function are the primary actions. The WiFi.begin() starts the wifi and connects to the given ssid. The while loop checks to ensure that a connection has been made successfully.

Thats all of the setup functions, there are two remaining functions, the standard loop() and a reconnect() function. In these, most of the operations occur. The loop() function is shown below.

void loop() {

if (!client.connected()) {
reconnect();
}
client.loop();

long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;

snprintf (msg, 75, "hello world !");
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
}

It starts by checking the connection and reconnecting if required. client.loop() is the built in handler for mqtt messages and needs to be called regularly. The remainder of the code publishes the “hello world !” message to the topic “outTopic” every 2 seconds. The reconnect() function, shown below, attempts to reconnect to the mqtt broker until a successful connection is made.

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientID, mqtt_username, mqtt_password)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

That’s a basic setup which created an ESP8266 based MQTT publisher.  After uploading the sketch and adjusting the connection so that the ESP is in run mode (see below), I tested it out.

operating-mode

 

Next time, I will look at subscribing to a topic and setting up the topics so that they make sense and follow a reasonable convention.

Advertisements

2 thoughts on “MQTT on the ESP-8266

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s