Samples

A collection of example applications that show how to use Thingsboard.

Temperature upload over MQTT using NodeMCU and DHT11 sensor

Introduction

Thingsboard 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-thingsboard page and getting-started guide.

This sample application performs collection of temperature and humidity values produced by DHT11 sensor. Collected data is pushed to Thingsboard for storage and visualization. The purpose of this application is to demonstrate Thingsboard data collection API and visualization capabilities.

The DHT11 sensor is connected to NodeMCU. NodeMCU push data to Thingsboard server via MQTT protocol. Data is visualized using built-in customizable dashboard. The application that is running on NodeMCU is written using Lua scripting language which is quite simple and easy to understand.

Once you complete this sample/tutorial, you will see your sensor data on the following dashboard.

image

Prerequisites

You will need to Thingsboard server up and running. Use either Live Demo or Installation Guide to install Thingsboard.

List of hardware and pinouts

image

image

Wiring schema

image

NodeMCU Pin DHT-11 Pin
NodeMCU 3.3V DHT-11 VCC
NodeMCU GND DHT-11 GND (-)
NodeMCU D5 DHT-11 Data (S)

Programming the NodeMCU device

We need to download and build firmware with Lua interpreter for NodeMCU. This process is described in official documentation and there are multiple way to do this. You can use cloud build service for this purpose, however, we will use Docker Image.

Firmware download

Use following commands to clone official github repository for NodeMCU firmware.

$ mkdir -p ~/samples/nodemcu
$ cd ~/samples/nodemcu
$ git clone https://github.com/nodemcu/nodemcu-firmware.git

There is ability to customize firmware by changing two files:

Please find and update line below to specify custom baud rate.

...
#define BIT_RATE_DEFAULT BIT_RATE_115200
...

In our case all necessary modules included by default. However, please check that these modules are uncommented.

...
define LUA_USE_MODULES_DHT
...
define LUA_USE_MODULES_MQTT
...

Building firmware using Docker

The easiest way to build nodemcu firmware is by using prepared docker container for that task.

Please visit docker installation page and install docker on your machine.

After installation you need to download docker image from docker hub by command:

$ sudo docker pull marcelstoer/nodemcu-build 

Eventually build the firmware by next command:

$ sudo docker run --rm -ti -v ~/samples/nodemcu/nodemcu-firmware:/opt/nodemcu-firmware marcelstoer/nodemcu-build

As the result binary firmware located in the ~/samples/nodemcu/nodemcu-firmware/bin folder.

Application source code

Our application consists of three .lua files:

resources/config.lua
wifi_mode = 1
wifi_ssid = "YOUR_WIFI_SSID_HERE"
wifi_pass = "YOUR_WIFI_PASSWORD_HERE"
mqtt_ip = "YOUR_THINGSBOARD_HOST_OR_IP_HERE"
mqtt_port = 1883
access_token = "DHT11_DEMO_TOKEN"
resources/dht11.lua
-- init mqtt client with keepalive timer 120sec
m = mqtt.Client("esp8266", 120, access_token, "password", 1)

print("Connecting to MQTT broker...")
m:connect(mqtt_ip, mqtt_port, 0, 1, function(client) print("Connected to MQTT!") end,
    function(client, reason) print("Could not connect, failed reason: " .. reason) end)

m:on("offline", function(client) print("MQTT offline") end)

pin = 5

print("Collecting Temperature and Humidity...")
tmr.alarm(2, 10000, tmr.ALARM_AUTO, function()
    status, temp, humi, temp_dec, humi_dec = dht.read(pin)
    if status == dht.OK then
        -- Integer firmware using this example
        print(string.format("DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
            math.floor(temp),
            temp_dec,
            math.floor(humi),
            humi_dec))
        m:publish("v1/devices/me/telemetry", string.format("[{\"temperature\":%d}, {\"humidity\":%d}]", math.floor(temp), math.floor(humi)), 0, 0, function(client) print("Data sent") end)
    elseif status == dht.ERROR_CHECKSUM then
        print("DHT Checksum error.")
    elseif status == dht.ERROR_TIMEOUT then
        print("DHT timed out.")
    end
end)
resources/init.lua
function startup()
    if file.open("init.lua") == nil then
        print("init.lua deleted")
    else
        print("Running")
        file.close("init.lua")
        tmr.unregister(0)
        dofile("dht11.lua")
    end
end

-- setup wifi
function setup_wifi(mode, ssid, pass)
    wifi.setmode(mode)
    wifi.sta.config(ssid, pass, 1)
end

--init.lua
wifi.sta.disconnect()

if file.exists("config.lua") then
    print("Loading configration from config.lua")
    dofile("config.lua")
end

setup_wifi((wifi_mode or wifi.AP), (wifi_ssid or "node_esp8266"), (wifi_pass or "_esp8266_"))

print("connecting to wifi...")
tmr.alarm(1, 1000, tmr.ALARM_AUTO, function()
    if wifi.sta.getip() == nil then
        print("IP unavaiable, Waiting...")
    else
        tmr.unregister(1)
        print("Config done, IP is " .. wifi.sta.getip())
        print("Waiting 10 seconds before startup...")
        tmr.alarm(0, 10000, 0, startup)
    end
end)

Flashing the firmware

Before flashing firmware we need to figure out what serial interface using to communicate with NodeMCU.

$ dmesg
...
[845270.901509] usb 3-3: ch341-uart converter now attached to ttyUSB0
...

In our case /dev/ttyUSB0 is used for communication.

In order to flash firmware for NodeMCU, please download and install following utilities

Upload nodemcu firmware using command:

$ sudo ./esptool.py -b 115200 write_flash --flash_mode dio --flash_size 32m 0x0 ~~/samples/nodemcu/nodemcu-firmware/bin/nodemcu_integer_master_*.bin --verify

Upload application files using following commands:

$ sudo ./luatool.py --port /dev/ttyUSB0 -b 115200 --src config.lua --dest config.lua -v
$ sudo ./luatool.py --port /dev/ttyUSB0 -b 115200 --src dht11.lua --dest dht11.lua -v
$ sudo ./luatool.py --port /dev/ttyUSB0 -b 115200 --src init.lua --dest init.lua -v

Troubleshooting

Sometimes you can observe frequent blinking of the blue led after firmware upload. This is probably related to missing initialization data. Use following command to fix this:

$ sudo ./esptool.py -b 115200 write_flash --flash_mode dio --flash_size 32m 0x3fc000 ~/samples/nodemcu/nodemcu-firmware/bin/esp_init_data_default.bin --verify

Sometimes you are not able to upload lua files. Try to reset device and executing command again within first 10 seconds after reset. If no success, try to delete init.lua code from NodeMCU:

$ sudo ./luatool.py --port /dev/ttyUSB0 -b 115200 --delete init.lua

Data visualization

In order to simplify this guide we have included “Temperature & Humidity Demo Dashboard” to the demo data that is available in each Thingsboard installation. Of course, you can modify this dashboard: tune, add, delete widgets, etc. You can access this dashboard by logging in as a tenant administrator. Use

in case of local Thingsboard installation.

Once logged in, open Dashboards->Temperature & Humidity Demo Dashboard page. You should observe demo dashboard with live data from your device (similar to dashboard image in the introduction).

Next steps

Browse other samples or explore guides related to main Thingsboard features:

Your feedback

Don’t hesitate to star Thingsboard on github to help us spread the word. If you have some questions about this sample - post it on the forum.