A Simple IoT Project using NodeMCU

By June 29, 2016IoT
Adafruit BMP280 sensor: https://www.adafruit.com/products/2651

At a recent conference, I showed a simple demo for the ESP8266 using NodeMCU. This demo connected to Wi-Fi, synchronized the time with an internet time server, and then read temperature and air pressure from a sensor every 5 seconds and published the values to a MQTT broker. It was essentially a fully functional IoT solution (minus a lot of the exception handling and compensation that a more polished app would include).

For the temperature and barometer, I used a BMP280 sensor available on a small board from Adafruit that supports both SPI and I2C. NodeMCU supports communication with both SPI and I2C devices directly. But, there is also a module that was contributed to the open source project that hides the details of using I2C to query sensor values.

To connect to Wi-Fi, I showed how to just start up enduser_setup in automatic mode. If Wi-Fi had previously been configured and the Access Point is accessible by the ESP8266, then enduser_setup will shut itself down and report success. Otherwise, it will start up its own access point and serve a web page. This allows for Wi-Fi to be configured without needing to connect to the ESP8266 over a serial connection (an important consideration if you are ever distributing a device to end-users).

Once connected, the demo fetches the time using SNTP. This is necessary if the device is going to provide its own timestamps for data, since the real-time clock in the ESP does not continue to work after power loss.

After the time has synchronized, the demo then connects to a MQTT broker, initializes the BMP280 (by specifying the GPIO used for I2C clock and data), and then enters into a 5-second loop of reading barometer data and publishing a JSON-encoded message to MQTT.

What’s important to note is that each subsequent step in the process is executed as a success callback from the previous step. This is the nature of the Non-OS SDK from Espressif, and is very similar in nature to JavaScript and Node.js.

 

The following two tabs change content below.