NodeMCU
Our project’s core component is the NodeMCU board. The board is inexpensive to order on Amazon [1]. An ESP8266 microcontroller is installed on the NodeMCU board. This has a WiFi interface, which helps us establish a connection to the WLAN. Table 1 shows the ESP8266’s technical data. The NodeMCU board provides us with an interface that lets us conveniently program the ESP8266 via USB. Programming the microcontroller is done via the Arduino IDE.
32-Bit-RISC-CPU | Tensilica Xtensa LX106 with 80 MHz |
Program memory | 64 KB |
Data memory | 96 KB |
External Flash (optional) | 512 KB to 4 MB |
GPIO | 10 Pins; possible interfaces: SPI, I²C, I²S, UART; DMA and IRQ can be used |
Wi-Fi | – IEEE 802.11 b/g/n
– WEP or WPA/WPA2 Authentication – Wi-Fi Direct (P2P), softAP – integrated TCP/IP protocol stack |
ADC | 1x 10 Bit Converter |
Antenna | integrated |
Power output | +19.5dBm in 802.11b mode |
Size | 17.2×12.3mm |
Standby power consumption | <1.0mA |
Table 1: ESP8266 technical data
Arduino IDE set-up
Installing the Arduino IDE is quite simple. Download the files suitable for your operating system from the project homepage [2] and follow the installation instructions. Windows users need to install an additional driver, which is already available for all Linux-based operating systems. You can download the driver from GitHub [3]. Please start the Arduino IDE now. As the name suggests, it was originally developed for programming Arduino boards, but programming other microcontrollers is possible with special board managers. To include the board manager for the NodeMCU board, you must perform the following steps: First, another board manager URL must be entered. From this URL, download the board administrator for the NodeMCU board. In the menu, under FILE| PREFERENCES, enter the following URL in the ADDITIONAL BOARD MANAGER URLs field and save it by clicking OK: http://arduino.esp8266.com/stable/package_esp8266com_index.json. In the next step, we’ll install the board manager for the NodeMCU board by searching for “ESP8266” under the menu item TOOLS | BOARD: “<ANY BOARD NAME>” | BOARD MANAGER…Then, install the ESP8266 community’s board manager. Depending on your Internet connection, it may take a moment for the installation to complete. After that, close the installation window.
TO NEWSLETTER
Stay tuned on IoT’s latest News
The ESP8266 community board manager supports many different ESP8266 modules, including the NodeMCU board. Now, we need to select the NodeMCU 1.0 (ESP-E12 module) from the menu item TOOLS| BOARD| ESP8266 Boards (2.7.4). Now, we can perform a small test and see if everything’s worked so far. For this, connect the NodeMCU board with our PC’s USB interface and load a test program into the controller. As a test, we’ll use an existing example program. Open the Blink example from the menu (FILE | EXAMPLES| 01.Basics | BLINK). This program makes the LED installed on the ESP8266 blink every second. To load the program into the controller and start it, click the UPLOAD icon (the right arrow, in the top left under the navigation bar). It takes a moment to start the program. If you get an error message after clicking the UPLOAD icon, please check that you’ve selected the correct serial post. The interface can be selected under TOOLS| PORT. Its designation may vary depending on your operating system and computer structure (example: Linux: /dev/ttyUSB0; Windows: COM1).
After our first NodeMCU board and IDE test was successful, we can start adding the libraries that our project needs. There’s a library for querying the DS18B20 temperature sensor and another that provides WebSockets. To add libraries, select SKETCH | INCLUDE LIBRARY | MANAGE LIBRARIES… from the menu. In the search field, enter “DS18B20”. Then select the library by Mathias Munk Hansen and install it.
After the installation is complete, search for “WebSockets2_Generic”. Here, you’ll see that only one library can be installed. After the WebSocket library is finished installing, close the window. The IDE preparations are now complete; next, we turn to the sensor’s hardware.
Hardware set-up
When building the hardware, we need to keep one important point in mind. A freezer is like a Faraday cage. If we put a microcontroller in the freezer, it won’t have a chance to connect to the WLAN. So, we need to place it outside the freezer. But, the temperature sensor has to be inside the freezer. That means we need an extension cable for our sensor so we can use it inside the freezer. We’ll use a simple flat ribbon cable as our extension, since we can easily run it through the freezer’s seals without a big temperature loss. Usually, you’d use an analog sensor for measuring the temperature. In our case, this could be tricky because cable length affects the measurement results. The circuit would need to be individually calibrated and adjusted for each application. Not only would it be a lot of work, but it would also unnecessarily complicate the circuit. Apart from that, you need the right measuring devices for calibrating the circuit. The program would also have to calculate the correct temperature from the analog measured values based on the sensor’s characteristic curve. All in all, it’s a lot of effort, but what alternative do we have? We could use a digital sensor that’s already factory-calibrated. With digital data transmission, the line length is irrelevant for the measured value. Digital sensors are only slightly more expensive than analog ones. But when you consider how much work this can save, they’re definitely worth the money. For this project, we’ll use the DS18B20 temperature sensor [4]. A ten-pack of sensors costs about 9 euros on Amazon. A waterproof version (a ten-pack) is available for about 17 euros [5].
The DS18B20 transmits its measured values serially to our microcontroller. This means we need three lines connecting the sensor to our microcontroller: two for the power supply and one for data transmission. For our data signal to be generated cleanly, we need a pull-resistor between the data line and the positive voltage supply. This resistor’s value is 4.7 kiloohms; Figure 1 shows the arrangement’s circuit diagram.
Fig. 1: Sensor’s circuit diagram
The ribbon cable’s individual wires are soldered to the DS10B20. Then, we use a heat shrink tubing to insulate individual wires from each other—don’t forget to pull the heat shrink tubing over the wires before soldering (Fig. 2). To mechanically protect the DS18B20, pack it into a small housing. Then, the case is sealed with silicone. An old paint pen cap does a good job here. Now, we come to the power supply. We have several possibilities. We can work with a 3-volt button cell directly at the 3V connector. Or we can use a battery pack with about 5 volts at the VIN connector, or—last but not least—a simple USB power supply. There’s always a chance that the batteries will discharge without us noticing, and then our nice sensor won’t work. No matter what kind of power supply you choose, it’s always a good idea to take advantage of the microcontroller’s power-saving features as much as possible. To use them, connect pins D0 and RST on the NodeMCU board. But this connection interferes with the board’s automatic reset. If there are any problems with the connection when uploading the program, manually reset it with the small button on the board. After uploading the program, the hardware reset can also be disturbed, so manual reset helps here. Figure 3 shows the finished setup.
Fig. 2: DS18B20 soldered to the cable
Fig. 3: The finished setup with the DS18B20 and NodeMCU board
Node-RED
As mentioned at the beginning, the sensor will transmit its measured values to Node-RED. First, let’s take a look at what functions it can perform in our project. The Node-RED software was developed by IBM and can be used to easily create IoT flows in the browser from a graphical interface. Flows are composed of individual nodes. These can send messages to each other. Since Node-RED is based on Node.js, messages are usually in JSON format. Over 3,200 nodes can be used directly in flows. Nodes can have different functions, many simply provide interfaces to protocols and devices. But some nodes perform specific operations on the messages. If there really isn’t a suitable node for a specific functionality, then the function node can be used to integrate its own code into the flow. The project’s homepage [6] is a good starting point for learning more about Node-RED. The complete documentation and plenty of instructions are available there. If problems arise, the forum is the right place to get help.
Of course, Node-RED needs hardware to be executed on. In principle, any computer can be used. Since our setup should always be active, we have to consider two things: if the hardware is suitable for 24/7 operation and how high its energy demand is. Even small servers can burn 100 or more euros in electricity in a year. However, a Raspberry Pi has a reasonable power consumption and enough computing power to host Node-RED. But the popular mini-computer’s operational reliability isn’t good—or is it? Once you start looking specifically, you’ll quickly find Raspberry Pis designed for industrial use. These devices are reliable and can run round the clock without burning much power. We’ll use the RevPi here. It’s an industrial Raspberry Pi from the company Kunbus. Node-RED is factory-installed on it, so we can start right away with our project. Besides the existing software, the device offers many other advantages. To learn more about the RevPi, take a look at the product homepage [7].
A GLIMPSE INTO IoT
SMART DATA SOLUTIONS
Now let’s look at the steps we need to set up Node-RED to process data from our temperature sensor. Since we’re using the RevPi as the host for Node-RED in this example, we’ll briefly show the steps needed to activate it. “The gods of IT security” put a log-in in front of every application. The ReviPi’s log-in page can be seen in Figure 4. The user is “admin” and the password is on the RevPi’s page. After we’ve successfully logged in, click on the SERVICES tab. There we can activate the two Node-RED relevant services (Fig. 5). Please don’t forget to save your changes with the SAVE ALL button. On the APPS tab (Fig. 6), we have the option to start Node-RED in the browser by clicking the START button. On the left side, we can see all the nodes that we can currently use in a flow. The middle area contains the flow. Here, the nodes can be placed with drag-and-drop. The node connections can be dragged with the mouse. The connection points are the gray “nubs” on the nodes. They light up when they’re in focus. Nubs on the right side are outputs, while nubs on the left side are inputs.
Fig. 4: Log-in for the RevPi
Fig. 5: Activating the Node-RED services
Fig. 6: Starting Node-RED
The nodes still have two status indicators that are important for working. First, there is the red triangle. It indicates that the node is not yet configured. Not every node has to be configured—the debug node is an example of this. Then there’s the blue circle on a node that tells us that this node is not deployed yet. We can edit flows without affecting the running version of the flow. After clicking the DEPLOY button, the changes become active and all blue circles disappear.
Now, we’ve come to the right area. Here you can view information about the selected node and the debug nodes’ output. Let’s start by setting up the flow for monitoring our freezer. Now is the time to decide which protocol to use between the sensor and Node-RED. In the IoT world, there are an incredible amount of protocols that can be used for data transmission. To keep it short, we decide to use WebSockets because it has good support for the protocol for both Node-RED and NodeMCU. The protocol is very lightweight and easy to test. Here, Node-RED already has a suitable node, which we can use directly. On the right, you can find the WEBSOCKET in Node under NETWORK. Simply drag it into our flow. In order to see what data the sensor is sending over the WebSocket, connect the WebSocket node’s output to a debug node. This flow is seen in Figure 7. Here we see that both nodes are not deployed yet. We can also see that the WebSocket node needs to be configured. Double-click a node to start configuring it. The dialog to configure the node opens (Fig. 8). There is no listener configured for the socket yet. Clicking on the pencil opens another dialog where we must specify the listener’s path. You can use any URL here. There’s no rule against descriptive names, so let’s choose /house/basement/freezer. Figure 9 shows this configuration. Now, click on ADD and then DONE. It’s finished; we created a WebSocket for receiving data. Before we can test how the socket works, we need to deploy the flow first. A few moments after clicking the DEPLOY button, the flow is active. Of course, more complex flows take a little longer to deploy.
Fig. 7: Flow for debugging data on the WebSocket
Fig. 8: Configuration dialog for the WebSocket flow
Listing 1: The program in the sensor
#include <OneWire.h>
#include <DS18B20.h>
#include <WebSockets2_Generic.h>
#include <ESP8266WiFi.h>
// Define Parameters
#define DS18B20_PIN D2
#define SSID “<YOUR_SSID>”
#define PASSWORD “<YOUR_PASSWORD>”
#define WS_HOST “<YOUR_NODE_RED_HOST>”
#define WS_PORT 1880
#define WS_PATH “/House/Basement/Freezer”
#define INTERVALL 30e6
using namespace websockets2_generic;
OneWire oneWire(DS18B20_PIN);
DS18B20 sensor(&oneWire);
WebsocketsClient client;
void setup() {
float temp;
WiFi.begin(SSID, PASSWORD);
Serial.begin(115200);
sensor.begin();
sensor.setResolution(12);
for (int i=0;i<10;i++){
sensor.requestTemperatures();
while (!sensor.isConversionComplete())delay(100);
temp=temp+sensor.getTempC();
}
temp=temp/10;
if(WiFi.status() == WL_CONNECTED){
client.connect(WS_HOST, WS_PORT, WS_PATH);
client.send((String)temp);
Serial.print(“Send Temperature:”);
Serial.println(temp);
delay(100);
client.close();
}
ESP.deepSleep(INTERVALL);
}
void loop() {
}
Extend flow
Now let’s return to our Node-RED installation. The goal is to trigger an easily recognizable alarm with the help of Node-RED. In the first step, we’ll extend the flow so it can send messages through Telegram. We can easily install the necessary node. For this, click on the burger menu in the upper right corner. Then, select MANAGE PALETTE. This opens up the dialog for managing nodes. As shown in Figure 10, select the INSTALL tab and search for “node-red-contrib-telegrambot”. By clicking the INSTALL button, the node will be downloaded and included in our available nodes. We can already create a bot in Telegram during installation.
Fig. 10: Installing additional nodes
Creating a bot in Telegram is very easy. Start a chat with the BotFather and create a new bot with its help. The BotFather is also a bot itself. It understands a command set for creating, managing, and deleting bots. To see an overview (Fig. 11) of the displayed commands, simply enter the command /help. Initiate the dialog for creating a bot with the command /newbot. The BotFather asks us to name the bot. We should pick a descriptive name to make it easier to find later. It needs a username that ends in “bot”. After we’ve entered all the necessary information, we’ll receive an access token from the BotFather. Keep this token safe; we’ll need it later to access the bot.
Fig. 11: A command overview can be called with /help
Further configuration steps will be completed in Node-RED. The Telegram node installation should now be complete. Select the sender node in the Telegram group. To fully configure the node, we must first add a new Telegram bot (Fig. 12). As a bot name and token, enter the values received from the BotFather. We need the bot’s chatId to be able to send messages to it. The easiest and fastest way is to take a Telegram receiver node in Node-RED and connect it to a debug node (Fig. 13). Now when you send a message to the Telegram bot, the correct Telegram message will look like Listing 2.
Fig. 12: Connecting a Telegram bot with Node-RED
Fig. 13: Determining the chatId with a debug node
Listing 2: Telegram message
{“chatId”:1234567890,
“messageId”:42,
“type”:”message”,
“content”:”test”,
“date”:1619778376}
With the help of this pattern, we can now build a function (Listing 3) that generates a message when a certain threshold value is reached. Then we can send this message with a Telegram sender node. The transmitter node is configured with the already-existing bot (Fig. 14). That’s how easy it is to get messages to your cell phone with Node-RED. Make sure that you’re using your own chatId.
Listing 3: Function for evaluating the sensor data and generate the message
if(msg.payload>-10){
text=”ALARM: Temperature too high: “+msg.payload
msg.payload={
“chatId”:1234567890,
“type”:”message”,
“content”:text
}
return msg;
}
Fig. 14: Flow for sending the alarm
But maybe your smartphone’s battery is dead when the bad news is transmitted. So, we should look for an additional alerting option. Wouldn’t it be great if a signal lamp started to shine? There’s nothing easier than that: simply include an IKEA Trådfri lamp in our flow. Node-RED is wonderfully consistent. Adding a node for IKEA Trådfri is just as easy as the Telegram node. To do so, simply search for “node-red-contrib-ikea-tradfri” and install the node as usual. But the Trådfri lighting system must already be entirely set up before we can continue. You can find the instructions on how to do this on the IKEA homepage [8]. Now, drag a “tradfri-light-control” node into the flow and start configuring it. As with the Telegram bot, first we need to create a new Trådfri configuration (Fig. 15). For this, we need the IP of the gateways and the code printed on the Trådfri gateway. After entering both, click AUTHENTICATE and then ADD. We can find the gateway’s IP in our routers list of DHCP devices. Our gateway’s name starts with “GW-”, followed by a twelve-digit HEX code. Figure 16 shows the completed flow to turn a Trådfri lamp on and off depending on sensor values. The two switch nodes route the message from the sensor to the “alarm on” or “alarm off” branch depending on the message’s payload. At this point in the flow, the message is structured so that the tradfri light control node can process it, but it throws cryptic errors because it can’t do anything with a number (the temperature) as input. So, we used two small function nodes to reformat the message appropriately (Listing 4). Interestingly, the function can be used for turning the lamp on and off. It’s really only about the message’s structure here. We switch the lamp on and off with the settings in the tradfri-light-control nodes.
Fig. 15: Creating a configuration for the Trådfri nodes
Fig. 16: Flow for controlling a Trådfri lamp
Listing 4: Customizing the message to avoid error messages from the Trådfri Node
msg.payload = {
state:’on’,
};
delete msg.topic;
return msg;
As you can see, building and running an IoT application with Node.RED is incredibly easy. With a huge selection of nodes, you’ll always find the right functionality for your problem. The learning curve for using Node-RED is quite steep.
Conclusion
We began our little journey into the world of IoT with a plausible disaster scenario. At the end of this article, we now have a solution that you can flexibly extend to master every conceivable problem. The Node MCU sensor can be extended as needed, so it can also process other environmental values or status information. With a little effort, it can even be used to switch consumers. Using Node-RED opens up countless possibilities for communication and data processing. With just a few clicks, we can integrate an additional device. Last but not least, with the RevPi we have industrial-grade hardware with digital and analog inputs and outputs out of the box. Of course, Node-RED can address these directly. But, let’s face it. This is a lot of effort just to monitor the temperature of a freezer. But if you view this project as the basis for your own home automation, then you can achieve a lot with this setup.
Links & Literature
[1] Order a NodeMCU Board: https://amzn.to/3swePfC
[2] Download Arduino IDE: https://www.arduino.cc/en/software
[3] Windows NodeMCU Driver: https://github.com/nodemcu/nodemcu-devkit/tree/master/Drivers
[4] Order DS18B20: https://amzn.to/3dNnUfj
[5] Waterproof DS18B20: https://amzn.to/3dJWYx1
[6] Node-RED Project: https://nodered.org
[7] RevPi product homepage: https://revolutionpi.com/revpi-compact/
[8] Instructions for setting up the Trådfri: https://www.ikea.com/us/en/customer-service/product-support/smart-lighting/