IoT CONFERENCE Blog

Monitoring your freezer with the NodeMCU board

Defrosting

Apr 1, 2022

A nightmare: the freezer in the basement has broken down and we only discover the mishap weeks later. All frozen food is spoiled and can only be disposed of. Wouldn't it be great if we had a little watchdog that monitors the chest's temperature and gives a loud early warning if there's a malfunction? Node-RED and the NodeMCU board make it possible.

NodeMCU

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/