IoT Hub
IoT Hub Documentation
Guides > Hardware samples > ESP8266 > ESP8266 GPIO control over MQTT using IoT Hub
Getting Started Documentation
API FAQ

On this page

ESP8266 GPIO control over MQTT using IoT Hub

Introduction

IoT Hub is an open-source server-side platform that allows you to monitor and control IoT devices. It is free for both personal and commercial usage and you can deploy it anywhere. If this is your first experience with the platform we recommend to review what-is-iothub page and getting-started guide.

This sample application will allow you to control GPIO of your ESP8266 device using IoT Hub web UI. We will observe GPIO control using LEDs connected to the pins. The purpose of this application is to demonstrate IoT Hub RPC capabilities.

The application that is running on ESP8266 is written using Arduino SDK which is quite simple and easy to understand. ESP8266 offers a complete and self-contained Wi-Fi networking solution. ESP8266 pushes data to IoT Hub server via MQTT protocol by using PubSubClient library for Arduino. Current GPIO state and GPIO control widget is visualized using built-in customizable dashboard.

The video below demonstrates the final result of this tutorial.





Prerequisites

You will need to have IoT Hub server up and running. The easiest way is to use Live Demo server.

The alternative option is to install IoT Hub using Installation Guide. Windows users should follow this guide. Linux users that have docker installed should execute the following commands:

1
2
3
4
5
mkdir -p ~/.mytb-data && sudo chown -R 799:799 ~/.mytb-data
mkdir -p ~/.mytb-logs && sudo chown -R 799:799 ~/.mytb-logs
docker run -it -p 9090:9090 -p 7070:7070 -p 1883:1883 -p 5683-5688:5683-5688/udp -v ~/.mytb-data:/data \
-v ~/.mytb-logs:/var/log/thingsboard --name mytb --restart always thingsboard/tb-postgres

These commands install IoT Hub and load demo data and accounts.

IoT Hub UI will be available using the URL: http://localhost:8080. You may use username tenant@thingsboard.org and password tenant. More info about demo accounts is available here.

List of hardware and pinouts

image

  • USB to TTL

    image

    image

  • Breadboard

  • 2 female-to-female jumper wires

  • 7 female-to-male jumper wires

  • 2 LEDs

  • 3.3V power source (for example 2 AA batteries)

Wiring schemes

Programming/flashing scheme

ESP8266 Pin USB-TTL Pin
ESP8266 VCC USB-TTL VCC +3.3V
ESP8266 CH_PD USB-TTL VCC +3.3V
ESP8266 GND (-) USB-TTL GND
ESP8266 GPIO 0 USB-TTL GND
ESP8266 RX USB-TTL TX
ESP8266 TX USB-TTL RX
LED 1 Pin USB-TTL Pin
cathode USB-TTL GND
LED 1 Pin ESP8266 Pin
anode ESP8266 GPIO 2

The following picture summarizes the connections for this project in programming/debug mode:

image

Final schema (Battery Powered)

ESP8266 Pin 3.3V power source
ESP8266 VCC VCC+
ESP8266 CH_PD VCC+
ESP8266 GND (-) VCC-
LED 1 Pin ESP8266 Pin
anode ESP8266 GPIO 2
LED 1 Pin 3.3V power source
cathode VCC-
LED 2 Pin ESP8266 Pin
anode ESP8266 GPIO 0
LED 2 Pin 3.3V power source
cathode VCC-

The final picture:

image

IoT Hub configuration

Note IoT Hub configuration steps are necessary only in case of local IoT Hub installation. If you are using Live Demo instance all entities are pre-configured for your demo account. However, we recommend reviewing this steps because you will still need to get device access token to send requests to IoT Hub.

Provision your device

This step contains instructions that are necessary to connect your device to IoT Hub.

Open IoT Hub Web UI (http://localhost:8080) in browser and login as tenant administrator

  • login: tenant@thingsboard.org
  • password: tenant

Go to “Devices” section. Click “+” button and create a device with the name “ESP8266 Demo Device”.

image

Once device created, open its details and click “Manage credentials”. Copy auto-generated access token from the “Access token” field. Please save this device token. It will be referred to later as $ACCESS_TOKEN.

image

Click “Copy Device ID” in device details to copy your device id to the clipboard. Paste your device id to some place, this value will be used in further steps.

Provision your dashboard

Download the dashboard file using this link. Use import/export instructions to import the dashboard to your IoT Hub instance.

Programming the ESP8266

Step 1. ESP8266 and Arduino IDE setup.

In order to start programming ESP8266 device, you will need Arduino IDE installed and all related software.

Download and install Arduino IDE.

After starting Arduino IDE, open the preferences from the ‘file’ menu.

image

Paste the following URL to the “Additional board managers URL”: http://arduino.esp8266.com/stable/package_esp8266com_index.json

Close the screen by clicking the OK button.

Now we can add the board ESP8266 using the board manager.

In the menu tools, click on the menu option Board: “Most likely Arduino UNO”. There you will find the first option “Board Manager”.

Type in the search bar the 3 letters ESP. Locate and click on “esp8266 by ESP8266 Community”. Click on install and wait for a minute to download the board.

image

Note that this tutorial was tested with the “esp8266 by ESP8266 Community” version 2.3.0.

In the menu Tools “Board “Most likely Arduino UNO” three new boards are added.

Select “Generic ESP8266 Module”.

Prepare your hardware according to the Programming/flashing scheme. Connect USB-TTL adapter with PC.

In the menu Tools, select the corresponding port of the USB-TTL adapter. Open the serial monitor (by pressing CTRL-Shift-M or from the menu Tools). Set the key emulation to “Both NL & CR” and the speed to 115200 baud. This can be set at the bottom of the terminal screen.

Step 2. Install Arduino libraries.

Open Arduino IDE and go to Sketch -> Include Library -> Manage Libraries. Find and install the following libraries:

Note that this tutorial was tested with the following versions of the libraries:

  • PubSubClient 2.6
  • ArduinoJson 5.8.0

Step 3. Prepare and upload a sketch.

Download and open esp8266-gpio-control.ino sketch.

Note You need to edit following constants and variables in the sketch:

  • WIFI_AP - name of your access point
  • WIFI_PASSWORD - access point password
  • TOKEN - the $ACCESS_TOKEN from IoT Hub configuration step.
  • thingsboardServer - IoT Hub HOST/IP address that is accessible from within your wifi network. Specify “iothub.magenta.at” if you are using live demo server.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <ESP8266WiFi.h>

#define WIFI_AP "YOUR_WIFI_AP"
#define WIFI_PASSWORD "YOUR_WIFI_PASSWORD"

#define TOKEN "ESP8266_DEMO_TOKEN"

#define GPIO0 0
#define GPIO2 2

#define GPIO0_PIN 3
#define GPIO2_PIN 5

char thingsboardServer[] = "iothub.magenta.at";

WiFiClient wifiClient;

PubSubClient client(wifiClient);

int status = WL_IDLE_STATUS;

// We assume that all GPIOs are LOW
boolean gpioState[] = {false, false};

void setup() {
  Serial.begin(115200);
  // Set output mode for all GPIO pins
  pinMode(GPIO0, OUTPUT);
  pinMode(GPIO2, OUTPUT);
  delay(10);
  InitWiFi();
  client.setServer( thingsboardServer, 1883 );
  client.setCallback(on_message);
}

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

  client.loop();
}

// The callback for when a PUBLISH message is received from the server.
void on_message(const char* topic, byte* payload, unsigned int length) {

  Serial.println("On message");

  char json[length + 1];
  strncpy (json, (char*)payload, length);
  json[length] = '\0';

  Serial.print("Topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  Serial.println(json);

  // Decode JSON request
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& data = jsonBuffer.parseObject((char*)json);

  if (!data.success())
  {
    Serial.println("parseObject() failed");
    return;
  }

  // Check request method
  String methodName = String((const char*)data["method"]);

  if (methodName.equals("getGpioStatus")) {
    // Reply with GPIO status
    String responseTopic = String(topic);
    responseTopic.replace("request", "response");
    client.publish(responseTopic.c_str(), get_gpio_status().c_str());
  } else if (methodName.equals("setGpioStatus")) {
    // Update GPIO status and reply
    set_gpio_status(data["params"]["pin"], data["params"]["enabled"]);
    String responseTopic = String(topic);
    responseTopic.replace("request", "response");
    client.publish(responseTopic.c_str(), get_gpio_status().c_str());
    client.publish("v1/devices/me/attributes", get_gpio_status().c_str());
  }
}

String get_gpio_status() {
  // Prepare gpios JSON payload string
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& data = jsonBuffer.createObject();
  data[String(GPIO0_PIN)] = gpioState[0] ? true : false;
  data[String(GPIO2_PIN)] = gpioState[1] ? true : false;
  char payload[256];
  data.printTo(payload, sizeof(payload));
  String strPayload = String(payload);
  Serial.print("Get gpio status: ");
  Serial.println(strPayload);
  return strPayload;
}

void set_gpio_status(int pin, boolean enabled) {
  if (pin == GPIO0_PIN) {
    // Output GPIOs state
    digitalWrite(GPIO0, enabled ? HIGH : LOW);
    // Update GPIOs state
    gpioState[0] = enabled;
  } else if (pin == GPIO2_PIN) {
    // Output GPIOs state
    digitalWrite(GPIO2, enabled ? HIGH : LOW);
    // Update GPIOs state
    gpioState[1] = enabled;
  }
}

void InitWiFi() {
  Serial.println("Connecting to AP ...");
  // attempt to connect to WiFi network

  WiFi.begin(WIFI_AP, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
}


void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    status = WiFi.status();
    if ( status != WL_CONNECTED) {
      WiFi.begin(WIFI_AP, WIFI_PASSWORD);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("Connected to AP");
    }
    Serial.print("Connecting toIoT Hub node ...");
    // Attempt to connect (clientId, username, password)
    if ( client.connect("ESP8266 Device", TOKEN, NULL) ) {
      Serial.println( "[DONE]" );
      // Subscribing to receive RPC requests
      client.subscribe("v1/devices/me/rpc/request/+");
      // Sending current GPIO status
      Serial.println("Sending current GPIO status ...");
      client.publish("v1/devices/me/attributes", get_gpio_status().c_str());
    } else {
      Serial.print( "[FAILED] [ rc = " );
      Serial.print( client.state() );
      Serial.println( " : retrying in 5 seconds]" );
      // Wait 5 seconds before retrying
      delay( 5000 );
    }
  }
}

Connect USB-TTL adapter to PC and select the corresponding port in Arduino IDE. Compile and Upload your sketch to the device using “Upload” button.

After the application is uploaded and started it will try to connect to IoT Hub node using mqtt client and upload current GPIOs state.

Autonomous operation

When you have uploaded the sketch, you may remove all the wires required for uploading including USB-TTL adapter and connect your ESP8266 and LEDs directly to the power source according to the Final wiring schema.

Troubleshooting

In order to perform troubleshooting, you should assemble your hardware according to the Programming/flashing scheme. Then connect USB-TTL adapter with PC and select port of the USB-TTL adapter in Arduino IDE. Finally, open “Serial Monitor” in order to view the debug information produced by serial output.

Data visualization

Finally, open IoT Hub Web UI. You can access this dashboard by logging in as a tenant administrator.

In case of local installation:

  • login: tenant@thingsboard.org
  • password: tenant

In case of live-demo server:

  • login: your live-demo username (email)
  • password: your live-demo password

See live-demo page for more details how to get your account.

Once logged in, open Dashboards->ESP8266 GPIO Demo Dashboard page. You should observe demo dashboard with GPIO control and status panel for your device. Now you can switch status of GPIOs using control panel. As a result, you will see LEDs status change on the device and on the status panel.

Below is the screenshot of the “ESP8266 GPIO Demo Dashboard”.

image

See also

Browse other samples or explore guides related to main IoT Hub features:

Next steps

  • Getting started guides - These guides provide quick overview of main IoT Hub features. Designed to be completed in 15-30 minutes.