Programming With Node Red Ebook
Programming With Node Red Ebook
Programming
with Node-RED
● 327
Programming with Node-RED
Design IoT Projects with Raspberry Pi,
Arduino and ESP32
Dogan Ibrahim
● All rights reserved. No part of this book may be reproduced in any material form, including
photocopying, or storing in any medium by electronic means and whether or not transiently or incidentally
to some other sue of this publication, without the written permission of the copyright holder except in
accordance with the provisions of the Copyright Designs and Patents Act 1988 or under the terms of a
licence issued by the Copyright Licencing Agency Ltd., 90 Tottenham Court Road, London, England W1P
9HE. Applications for the copyright holder's permission to reproduce any part of the publication should be
addressed to the publishers.
● Declaration
The author and publisher have used their best efforts in ensuring the correctness of the information
contained in this book. They do not assume, or hereby disclaim, any liability to any party for any loss or
damage caused by errors or omissions in this book, whether such errors or omissions result from negligence,
accident or any other cause..
● ISBN 978-1-907920-88-2
Elektor is part of EIM, the world's leading source of essential technical information and electronics products for pro
engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops
and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social
media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Chapter 1 • Raspberry Pi 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.4 Help. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
●5
Programming with Node-RED
4.17 Project 9 – Getting the weather reports – Display the local weather report . . . . . . 70
4.22 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
●6
5.4.1 Using a context variable to flash the LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.6 Project 24 – Displaying local temperature and humidity on the LCD. . . . . . . . . . . 120
6.9 Project 27 – DHT11 temperature and humidity sensor with LCD Display. . . . . . . . 124
●7
Programming with Node-RED
8.6 Project 36 – Using gauges to display the temperature and humidity . . . . . . . . . . 158
8.10 Project 40 – Using switch and text nodes to control an LED . . . . . . . . . . . . . . . 165
9.3 Project 43 – Controlling multiple LEDs from a mobile phone – UDP based
communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
9.7 Project 47 – Sending the temperature and humidity to the mobile phone –
TCP based communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
●8
10.3 Project 51 – Reading contents of a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
11.4 Project 55 – Receiving GPS data – Extracting the latitude and longitude. . . . . . . 208
11.7 Project 58 – Connecting Raspberry Pi and Arduino Uno using USB ports . . . . . . . 220
11.8 Project 59 – Sending serial data from Raspberry Pi to Arduino over RF Radio . . . 222
12.10 Project 64 – Random flashing LED lights having random colours . . . . . . . . . . . 238
12.13 Project 66 – Scrolling the pressure readings on the LED matrix . . . . . . . . . . . . 242
●9
Programming with Node-RED
13.4 Project 68 – Displaying the ambient temperature in the debug window . . . . . . . 248
13.6 Project 70 – Displaying the ambient temperature as gauge and chart . . . . . . . . 251
● 10
18.6 The ESP8266 processor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
18.10 Project 79 – Controlling an LED using ESP8266 NodeMCU with MQTT – LED
connected to ESP8266 NodeMCU . . . . . . . . . . . . . . . . . . . . . . . . 293
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
● 11
Programming with Node-RED
● 12
Preface
Preface
It is becoming important for microcontroller users to adapt to new technologies quickly and
learn the architecture and use of high-performance 32-bit microcontrollers. Several manu-
facturers offer 32-bit microcontrollers as general-purpose processors in embedded applica-
tions. ARM architecture is currently one of the most frequently used 32-bit microcontroller
architectures in mobile devices, such as in mobile phones, iPads, games consoles, and in
many other portable devices.
Raspberry Pi is based on ARM architecture and it is currently one of the most commonly
used single-board computers used by students, engineers, and hobbyists. There are hun-
dreds of Raspberry Pi based projects available on the internet
The Internet of Things (IoT) is becoming a major application area of embedded systems.
As a result, more people are becoming interested in learning about embedded design and
programming. In addition, we can see that more technical colleges and universities are
moving away from legacy 8-bit and 16-bit microcontrollers and introducing 32-bit embed-
ded microcontrollers into their curriculums. Some IoT applications demand precision, high
processing power, and very low power consumption.
Node-RED is an open-source visual editor for wiring the Internet of Things produced by
IBM. Node-RED comes with a large number of nodes to handle a variety of tasks. The
required nodes are selected and joined together to perform a particular task. Node-RED
is based on flow type programming where nodes are configured and joined together to
form an application program. There are nodes for doing very complex tasks, including web
access, Twitter, E-mail, HTTP, Bluetooth, MQTT, controlling GPIO ports, etc. The nice thing
about Node-RED is that the programmer does not need to learn how to write complex
programs. For example, an email can be sent by joining a few nodes together and writing
a few lines of code.
The aim of this book is to teach how Node-RED can be used in projects. The main proces-
sor used in the majority of projects in this book is Raspberry Pi 4. Chapters are included
to show how Node-RED can be used with Arduino Uno, ESP32 DevKitC, and the ESP8266
NodeMCU microcontroller development boards.
● 13
Programming with Node-RED
Many example projects are given in the book. All projects have been fully tested and were
working at the time of writing this book. Users can select flow programs of the projects
from the book website and configure them to suit their own applications. The operation of
each flow program is fully described in the book.
I hope you enjoy reading this book and are then able to use Node-RED happily in your
future projects.
● 14
Chapter 1 • Raspberry Pi 4
Chapter 1 • Raspberry Pi 4
1 .1 Overview
Raspberry Pi has recently become one of the most popular and most powerful single-board
computers used by students, hobbyists, and professional engineers. Raspberry Pi 4 is the
latest and the most powerful version of Raspberry Pi. In this chapter, we will be looking at
the basic specifications and requirements of the Raspberry Pi 4 computer. What is included
in this chapter can easily be applied to other models in the Raspberry Pi family.
Figure 1 shows the Raspberry Pi 4 board with its major components identified.
● 15
Programming with Node-RED
RAM: There are 3 versions of Raspberry Pi 4 depending on the amount of DDR4 RAM re-
quired: 1GB, 2GB, and 4GB.
USB Ports: Raspberry Pi 4 includes 2 x USB 3.0, 2 x USB 2.0, and 1 x USB-C ports. USB
3.0 data transfer rate is 4,800 Mbps (megabits per second), while USB 2.0 can transfer at
up to 480Mbps, i.e. 10 times slower than the USB 2.0. The USB-C port enables the board
to be connected to a suitable power source.
Ethernet: The Ethernet port enables the board to be connected directly to an Ethernet port
on a router. The port supports Gigabit connections (125Mbps).
HDMI: Two micro HDMI ports are provided that support up to 4K screen resolutions. HDMI
adapters can be used to interface the board to standard size HDMI devices.
GPIO: A 40-pin header is provided as the GPIO (General Purpose Input Output). This is
compatible with the earlier GPIO ports.
Audio and Video Port: A 3.5mm jack type socket is provided for stereo audio and com-
posite video interface. Headphones can be connected to this port. External amplifier de-
vices will be required to connect speakers to this port. This port also supports composite
video, enabling TVs, projectors, and other composite video compatible display devices to
be connected to the port.
CSI Port: This is the camera port (Camera Serial Interface), allowing a compatible camera
to be connected to the Raspberry Pi.
DSI Port: This is the display port (Display Serial Interface), allowing a compatible display
(e.g. 7 inch Raspberry Pi display) to be connected to the Raspberry Pi.
PoE Port: This is a 4-pin header, allowing the Raspberry Pi to receive power from a net-
work connection.
Micro SD Card: This card is mounted at the cardholder placed at the bottom of the board
and it holds the operating system software as well as the operating system and user data.
Requirements of the Raspberry Pi 4
As listed below, a number of external devices are required before the Raspberry Pi can be
used:
• Power supply
• Micro SD card
● 16
Chapter 1 • Raspberry Pi 4
Power Supply: A 5V 3A power supply with a USB-C type connector is required. You may
either purchase the official Raspberry Pi 4 power supply (Figure 1.2) or use a USB-C adapt-
er to provide power from an external source.
Micro SD Card: It is recommended to use a micro SD card with a capacity of at least 8GB,
although higher capacity (e.g. 16GB or 32GB) is better as there will be room to grow in the
future. A Class 10 (or faster) card is recommended.
Operating System: You can purchase the operating system pre-loaded on a micro SD
card, known as NOOBS (New Out Of Box Software) which requires minimum configuration
before it is fully functional. The alternative is to purchase a blank micro SD card and upload
the operating system on this card. The steps to prepare a new micro SD card with the op-
erating system is given in the next Chapter.
USB Keyboard and Mouse: You can either use a wireless or wired keyboard and mouse
pair. If using a wired pair, you should connect the keyboard to one of the USB ports and the
mouse to another USB port. If using a wireless keyboard and mouse, you should connect
the wireless dongle to one of the USB ports.
● 17
Programming with Node-RED
Display: A standard HDMI compatible display monitor with a micro HDMI to standard HDMI
adapter can be used. Alternatively, a VGA type display monitor with a micro HDMI to VGA
adapter or DVI-D adapter can be used. If you have an old TV with a composite video inter-
face, then you can connect it to the Raspberry Pi 3.5mm port with a TRRS type connector.
You may also consider purchasing additional parts, such as a case, CPU fan, and so on. The
case is very useful as it protects your Raspberry Pi electronics. The working temperature of
the CPU can go as high as 80 degrees Centigrade. Using a fan (see Figure 1.3) makes the
CPU more efficient as it can lower its temperature by about 50%.
1 .3 .1 Setup option 1
As shown in Figure 1.4, in this option various devices are connected directly to the Raspber-
ry Pi 4. Depending on what type of display monitor we have, we can use an HDMI display,
VGA monitor, DVI-D monitor, or TV. Notice that depending on the external USB devices
used, you can use either the USB 2.0 or the USB 3.0 ports.
● 18
Chapter 1 • Raspberry Pi 4
1 .3 .2 Setup option 2
In this option, shown in Figure 1.5, a powered hub is used to connect the USB devices.
Summary
In this chapter, we have learned about the main parts and their functions of the Raspberry
Pi 4 board. In addition, we have learned how to configure Raspberry Pi 4.
In the next chapter, we will be learning how to install the latest Raspberry Pi operating
system, Raspbian Buster, on a new blank micro SD card.
● 19
Programming with Node-RED
2 .1 Overview
In the last chapter, we had a look at some of the hardware features of Raspberry Pi 4 and
learned how to set up the hardware using various external devices. In this chapter, we will
be learning how to install the latest Raspberry Pi operating system, Raspbian Buster, on
an SD card.
• Download the Buster image to a folder on your PC (e.g. C:\RPIBuster) from the
following link by clicking the Download ZIP under section Raspbian Buster with
desktop and recommended software (see Figure 2.1). At the time of writing
this book the file was called: 2019-07-10-raspbian-buster-full .img. You may
have to use the Windows 7Zip software to unzip the download since some of the
features are not supported by older unzip software.
https://www.raspberrypi.org/downloads/raspbian/
• Put your blank micro SD card into the card slot on your computer. You may need
to use an adapter to do this.
● 20
Chapter 2 • Installing the Raspberry Pi operating system
• Download the Etcher program to your PC to flash the disk image. The link is (see
Figure 2.2):
https://www.balena.io/etcher/
• Double click to Open Etcher, and click Select image. Select the Raspbian Buster
file you just downloaded.
• Click Flash (see Figure 2.3). This may take several minutes, wait until it is fin-
ished. The program will then validate and unmount the micro SD card. You can
remove your micro SD card after it is unmounted.
• You are now ready to use your micro SD card on your Raspberry Pi 4.
● 21
Programming with Node-RED
• Connect your Raspberry Pi 4 to a HDMI monitor (you may need to use an adapter
cable for mini HDMI to standard HDMI conversion), connect a USB keyboard, and
power up the Raspberry Pi.
• You will see the startup menu displayed on the monitor. Click Next to get started.
• Select the Wi-Fi network and enter the password of your Wi-Fi router.
• Click on the Wi-Fi icon at the top right-hand side of the screen and note the Wire-
less IP address of your Raspberry Pi (notice that this IP address is not static and
it can change next time you power-up your Raspberry Pi).
• You should now be ready to use your Raspberry Pi 4 (see Desktop in Figure 2.4).
Notice that the IP address of your Raspberry Pi can also be seen in your router. You can also
get the IP address of your Raspberry Pi using your mobile phone. There are several pro-
grams free of charge that can be installed on your mobile phone that will show you the IP
addresses of all the devices connected to your router. In this section, the use of the Android
apps called Who's On My Wi-Fi – Network Scanner by Magdalm is used to show how
the IP address of your Raspberry Pi can be displayed. Running this program will display the
Raspberry Pi Wireless IP address under the heading Raspberry Pi Trading Ltd. In addi-
tion to the IP address, other parameters such as MAC address, gateway address, IP mask,
etc are all displayed by this program.
2 .3 Remote access
It is much easier to access the Raspberry Pi remotely over the Internet, for example using
a PC rather than connecting a keyboard, mouse, and display to it. Before being able to ac-
cess your Raspberry Pi remotely, we have to enable the SSH and the VNC by entering the
following command at a terminal session:
● 22
Chapter 2 • Installing the Raspberry Pi operating system
Go to the configuration menu and select Interface Options. Go down to P2 SSH (see
Figure 2.5) and enable SSH. Click <Finish> to exit the menu.
You should also enable VNC so that your Raspberry Pi can be accessed graphically over the
Internet. This can be done by entering the following command at a terminal session:
Go to the configuration menu and select Interface Options. Go down to P3 VNC and en-
able VNC. Click <Finish> to exit the menu. At this stage, you may want to shut down your
Raspberry Pi by clicking the Applications Menu on Desktop and selecting the Shutdown
option.
2 .4 Using Putty
Putty is a communications program that is used to create a connection between your PC
and Raspberry Pi. This connection uses a secure protocol called SSH (Secure Shell). Putty
doesn't need to be installed as it can just be stored in any folder of your choice and run
from there.
https://www.putty.org/
Simply double click to run it and the Putty startup screen will be displayed. Click SSH and
enter the Raspberry Pi IP address, then click Open (see Figure 2.6). The message shown in
Figure 2.7 will be displayed the first time you access your Raspberry Pi. Click Yes to accept
this security alert.
● 23
Programming with Node-RED
You will be prompted to enter the username and password. Notice that the default user-
name and password are:
username: pi
password: raspberry
You now have a terminal connection with the Raspberry Pi and you can type in commands,
including sudo commands. You can use the cursor keys to scroll up and down through the
commands you've previously entered in the same session. You can also run programs al-
though not graphical programs.
2 .4 .1 Configuring Putty
By default, the Putty screen background is black with white foreground characters. In this
book, we used a white background with black foreground characters, with the character
size set to 12 points bold. The steps to configure Putty with these settings are given below.
Notice that in this example the settings are saved with the name RPI4 so that they can be
recalled whenever Putty is re-started:
● 24
Chapter 2 • Installing the Raspberry Pi operating system
• Restart Putty
• Set the Default Foreground and Default Bold Foreground colours to black
(Red:0, Green:0, Blue:0)
• Set the Default Background and Default Bold Background to white (Red:255,
Green:255, Blue:255)
• Set the Cursor Text and Cursor Colour to black (Red:0, Green:0, Blue:0)
• Select Appearance under Window and click Change in Font settings. Set the
font to Bold 12.
• Select Session and give a name to the session (e.g. RPI4) and click Save.
• Click Open to open the Putty session with the saved configuration
• Next time you re-start Putty, select the saved session and click Load followed by
Open to start a session with the saved configuration
pi$raspberrypi:~ $ vncserver :1
The steps to install and use VNC Viewer on your PC are given below:
• There are many VNC Viewers available, but the recommended one is TightVNC
which can be downloaded from the following web site:
https://www.tightvnc.com/download.php
● 25
Programming with Node-RED
• Download and install TightVNC software for your PC. You will have to choose a
password during the installation.
• Start TightVNC Viewer on your PC and enter the Raspberry Pi IP address (see
Figure 2.8) followed by :1. Click Connect to connect to your Raspberry Pi.
2 .6 Summary
In this chapter, we have learned how to install the latest Raspberry Pi operating system
on an SD card. Now that the software has been installed and our Raspberry Pi is working,
in the next chapter, we will look at some of the important commands of the Raspberry Pi
operating system.
● 26
Chapter 3 • Using the command line
3 .1 Overview
Raspberry Pi operating system is based on a version of the Linux operating system. Linux
is one of the most popular operating systems in use today. Linux is very similar to other
operating systems, such as Windows and Unix. Linux is an open operating system based
on Unix and has been developed collaboratively by many companies and universities since
1991. In general, Linux is harder to manage than some other operating systems like Win-
dows but offers more flexibility and wider configuration options. There are several popular
versions of the Linux operating system such as Debian, Ubuntu, Red Hat, Fedora and so on.
In this chapter we shall be looking at some of the commonly used Raspberry Pi commands
that we can enter from the command line. The commands entered by the user are shown
in bold for clarity.
The root directory is identified by the "/" symbol. Under the root, we have directories
named such as bin, boot, dev, etc, home, lib, lost+found, media, mnt, opt, proc,
and many more. The important directory as far as the users are concerned is the home
directory which contains subdirectories for each user of the system. The full path to the
home directory is /home/pi. We can move to our home directory from any other directory
by entering the command cd ~
Some useful directory commands are given below. Command pwd displays the user home
directory:
pi@raspberrypi:~ $ pwd
/home/pi
pi@raspberrypi:~ $
To show the directory structure, enter the command ls / as shown in Figure 3.1.
To show the subdirectories and files in our home directory, enter ls as shown in Figure 3.2.
● 27
Programming with Node-RED
The ls command can take a number of arguments. Some examples are given below:
To display the subdirectories and files in a single row:
pi@raspberrypi:~ $ ls -1
To display the file type, enter the following command. Note that directories have a "/" after
their names, executable files have a "*" character after their names:
pi@raspberrypi:~ $ ls -F
pi@raspberrypi:~ $ ls –m
pi@raspberrypi:~ $ ls –m –F
Subdirectories are created using command mkdir followed by the name of the subdirecto-
ry. In the following example, subdirectory myfiles is created in our working directory (see
Figure 3.3).
3 .3 File permissions
One of the important arguments used with the ls command is "-l" (lower case letter l)
which displays the file permissions, file sizes, and when they were last modified. In the
example in Figure 3.4, each line relates to one directory or file. Reading from right to left,
the name of the directory or the file is on the right-hand side. The date the directory or
the file was created is on the left-hand side of its name. Next comes the size in bytes. The
characters at the beginning of each line are about the permissions. i.e. who is allowed to
use or modify the file or the subdirectory.
● 28
Chapter 3 • Using the command line
The first pi in the example shows who the user of the file (or subdirectory) is, and the sec-
ond word pi shows the group name that owns the file (or subdirectory). In this example,
both the user and the group names are pi.
The permissions can be analysed by breaking down the characters into four chunks for
File type, User, Group, World. The first character for a file is "-", and for a directory, it is
"d". Next comes the permissions for the User, Group, and World. The permissions are as
follows:
• Read permission (r): the permission to open and read a file or to list a directory
• Write permission (w): the permission to modify a file, or to delete or create a
file in a directory
• Execute permission (x): the permission to execute the file (applies to execut-
able files), or to enter a directory
The three letters rwx are used as a group and if there is no permission assigned then a "-"
character is used.
d: it is a directory
rwx: user (owner) can read, write, and execute
r-x: group can read and execute, but cannot write (e.g. create or delete)
r-x: world (everyone else) can read and execute, but cannot write
● 29
Programming with Node-RED
The chmod command is used to change the file permissions. Before going into details of
how to change the permissions, let us look and see what arguments are available in chmod
for changing the file permissions.
The available arguments for changing file permissions are given below. We can use these
arguments to add/remove permissions or to explicitly set permissions. It is important to
realize that if we explicitly set permissions then any unspecified permissions in the com-
mand will be revoked:
+: add
-: remove
=: set
r: read
w: write
x: execute
To change the permissions of a file we type the chmod command, followed by one of the
letters u, g, o, or a to select the people, followed by the + - or = to select the type of
change, and finally followed by the filename. An example is given below. In this example,
subdirectory Music has the user read and write permissions. We will be changing the per-
missions so that the user does not have read permission on this file:
● 30
Chapter 3 • Using the command line
In the following example, rwx user permissions are given to subdirectory Music:
To change our working directory the command cd is used. In the following example we
change our working directory to Music:
pi@raspberrypi ~$ cd /home/pi/Music
pi@raspberrypi ~/Music $
pi@raspberrypi ~$
to change our working directory to Music, we can also enter the command:
pi@raspberrypi ~$ cd ~/Music
pi@raspberrypi ~/myfiles $
pi@raspberrypi ~/Music $ cd ~
pi@raspberrypi ~$
to find out more information about a file we can use the file command. For example:
● 31
Programming with Node-RED
the –R argument of command ls lists all the files in all the subdirectories of the current
working directory. An example is shown in Figure 3.7.
3 .4 Help
Man
To display information on how to use a command, we can use the man command. As an
example, to get help on using the mkdir command:
NAME
Mkdir – make directories
SYNOPSIS
Mkir [OPTION]…DIRECTORY…
DESCRIPTION
Create the DIRECTORY(ies), if they do not already exist.
-m, --mode=MODE
Set file mode (as in chmod), not a=rwx – umask
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Help
The man command usually gives several pages of information on how to use a command.
We can type q to exit the man command and return to the operating system prompt.
The less command can be used to display a long listing one page at a time. Using the up
and down arrow keys, we can move between pages. An example is given below. Type q to
exit:
● 32
Chapter 3 • Using the command line
pi@raspberrypi ~$
3 .6 File operations
Copying a file
To make a copy of a file, use the command cp. In the following example, a copy of file
mytestfile .txt is made and the new file is given the name test .txt:
Wildcards
We can use wildcard characters to select multiple files with similar characteristics. e.g. files
having the same file-extension names. The "*" character is used to match any number of
characters. Similarly, the "?" character is used to match any single character. In the exam-
ple below all the files with extensions " .txt" are listed:
pi@raspberrypi ~$ ls *.txt
The wildcard characters [a-z] can be used to match any single character in the specified
character range. An example is given below which matches any files that start with letters
o, p, q, r, s, and t, and with the " .txt" extension:
pi@raspberrypi ~$ ls [o-t]*.txt
Renaming a file
You can rename a file using the mv command. In the example below, the name of file test .
txt is changed to test2 .txt:
● 33
Programming with Node-RED
Deleting a file
The command rm can be used to remove (delete) a file. In the example below file test2 .
txt is deleted:
pi@raspberrypi ~$ rm test2.txt
The argument –v can be used to display a message when a file is removed. Also, the –i
argument asks for confirmation before a file is removed. In general, the two arguments are
used together as –vi. An example is given below:
Removing a directory
A directory can be removed using the rmdir command:
● 34
Chapter 3 • Using the command line
The echo command can also be used to write a line of text to a file. An example is shown
below:
Matching a string
The grep command can be used to match a string in a file. An example is given below
assuming that the file lin .dat contains sting a line of text. Notice that the matched word
is shown in bold:
Similarly, the tail command is used to display the last 10 lines of a file. The format of this
command is as follows:
● 35
Programming with Node-RED
Figure 3.9 Command: cat /proc/cpuinfo (only part of the output is shown)
Command uname –s displays the operating system Kernel name, which is Linux. Com-
mand uname –a displays complete detailed information about the Kernel and the operat-
ing system.
Command cat /proc/meminfo displays information about the memory on your Pi. Infor-
mation such as the total memory and free memory at the time of issuing the command are
displayed.
Command whoami displays the name of the current user. In this case, it displays pi.
A new user can be added to your Raspberry Pi using the command useradd. In the ex-
ample in Figure 3.10, a user called Johnson is added. A password for the new user can be
added using the passwd command followed by the username. In Figure 3.10, the pass-
word for user Johnson is set to mypassword (not displayed for security reasons). Notice
that both the useradd and passwd are privileged commands and the keyword sudo must
be entered before these commands. Notice that the –m option creates a home directory
for the new user.
We can log in to the new user account by specifying the username and the password.
● 36
Chapter 3 • Using the command line
pi@raspberrypi ~$ dpkg –l
…………………………….
…………………………….
pi@raspberrypi ~$
We can also find out if a certain software package is already installed on our computer. An
example is given below which checks whether or not software called xpdf (PDF reader) is
installed. In this example xpdf is installed and the details of this software are displayed:
If the software is not installed, we get a message similar to the following (assuming we are
checking to see if a software package called bbgd is installed):
Figure 3.11 shows a typical system resource display obtained by entering the following
command (Enter Ctrl+Z to exit):
pi@raspberrypi ~$ top
pi@raspberrypi ~$
● 37
Programming with Node-RED
Some of the important points in Figure 3.11 are summarized below (for lines 1 to 5 of the
display):
The process table gives the following information for all the processes loaded to the system:
● 38
Chapter 3 • Using the command line
The ps command can be used to list all the processes used by the current user. An example
is shown in Figure 3.12.
the command ps –ef gives a lot more information about the processes running in the sys-
tem.
Killing a process
There are many options for killing (or stopping) a process. A process can be killed by spec-
ifying its PID and using the following command:
Disk usage
The disk free command df can be used to display the disk usage statistics. An example is
shown in Figure 3.13. option –h displays in human-readable form.
3 .9 Shutting down
Although you can disconnect the power supply from your Raspberry Pi when you finish
working with it, it is not recommended since there are many processes running on the sys-
tem and it is possible to corrupt the file system. It is much better to shut down the system
in an orderly manner.
● 39
Programming with Node-RED
The following command will stop all the processes and make the file system safe and then
turn off the system safely:
The system can also be shut down and then restarted after a time by entering the following
command. Optionally, a shutdown message can be displayed if desired:
3 .10 Summary
This Chapter has described the use of a number of important Linux commands. You should
be able to get further information on each command and other Linux commands from the
internet and from other books on Raspberry Pi and Linux.
In the next chapter, we shall see how to install Node-RED software on our Raspberry Pi
computer.
● 40
Chapter 4 • Installing Node-RED software on Raspberry Pi
4 .1 Overview
In the last chapter, we have seen how to use some of the common Raspberry Pi command
line commands from a terminal. In this chapter, we will be installing Node-RED software on
our Raspberry Pi SD card.
If Node-RED is not installed on your Raspberry Pi, you can easily install it by entering the
following command:
At the time of writing this book, the default version of Node-RED pre-installed with the
Raspbian Buster operating system was v0.20.6 and this was not the latest version. If
Node-RED is already installed on your Raspberry Pi, you can upgrade to the latest version
(recommended) by entering the following command (see link: https://nodered.org/docs/
getting-started/raspberrypi):
After upgrading Node-RED, the latest version at the time of writing this book was v1.0.3
and this is the version used in all examples in this book.
You can start Node-RED by entering the following command in the command mode (char-
acters entered by the user are in bold for clarity):
pi@raspberrypi:~ $ node-red-start
When started, you should see some messages scrolling in your screen, where part of the
messages is shown in Figure 4.1.
● 41
Programming with Node-RED
Notice that this is a service type application and therefore it can be accessed from any-
where on the network and from other computers as well. To do this, we have to know the
IP address of our Raspberry Pi. This can be found by entering the following command at
the command prompt:
pi@raspberrypi:~ $ ifconfig
The IP address of our Raspberry Pi in this example is 192.168.1.202 as shown in Figure 4.2
(only part of the output is shown here).
We can now enter the following command on our web browser to display the Node-RED
startup screen:
http://192.168.1.202:1880
● 42
Chapter 4 • Installing Node-RED software on Raspberry Pi
When started, you should see the Node-RED startup screen as in Figure 4.3. When Node-
RED is started as a service, pressing Cntrl+C does not stop the service as it keeps running
in the background.
Notice that, if you are using a browser on the same computer that Node-RED is running,
then you can access Node-RED using the following URL:
http://localhost:1880
● 43
Programming with Node-RED
The node categories, also called the Node Palettes consists of following sections:
• input
• output
• function
• social
• storage
• analysis
• advanced
• Raspberry Pi
• network
pi@raspberrypi:~ $ node-red-start
• Enter the following URL into your web browser to display the Node-RED screen
(you will have to enter the IP address of your own Raspberry Pi):
http://192.168.1.202:1880
• From the node palette, Click on inject node on the left-hand side and drag it to
the workspace.
• Double click on this node, click on Payload, select String and enter the following
string Hello World! As shown in Figure 4.6:
● 44
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Click Done
• Add node debug by clicking on debug node and dragging it to the right-hand side
of the inject node already in the workspace
• Wire the two nodes together. Place the mouse cursor over the inject nodes out-
put port (a small gray square on the right-hand side of the node), then left-click
and drag a wire over to the input port of the Debug node. A wire should now
connect the two nodes as shown in Figure 4.7
• Click the Deploy button at the top right-hand side of the screen
• Click the small gray square on the right-hand side of node debug to activate the
node. You should see the message Successfully activated: debug displayed
by the console window
• Click the inject nodes button, which is the small square coming out from the left-
hand side of the node. Clicking the button will inject the message into the flow
and to the debug node. The output should be displayed on the debug window as
shown in Figure 4.8
● 45
Programming with Node-RED
Notice that, if you place a wrong node on the workspace, you can click on the node and then
use the keyboard delete button to remove it.
In this example, we first created an inject node. The inject node can be used to manually
trigger a flow by clicking the nodes button within the workspace. It can also be used to au-
tomatically trigger flows at regular intervals. We then stored the string Hello World! In this
node. Next, we created a debug node and connected the two nodes together and activated
the debug node. By triggering the inject node, the string is sent to the debug node and is
displayed in the debug window. The Debug node can be used to display messages in the
Debug sidebar within the editor. In addition to the displayed messages, the debug sidebar
includes information about the time the message was received and also the ID of the Debug
node that sent the message. Clicking on the ID reveals the node that sent the message.
Modified program
We can modify the flow program, for example, to display the string every 5 seconds. The
steps to do this are given below:
• Set the Repeat Interval to every 5 seconds (Figure 4.9) and click Done
● 46
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Click Deploy
• Click the inject nodes button. You should see the message displayed every 5
seconds as in Figure 4.10
• From the node palette, Click on inject node on the left-hand side and drag it to
the workspace.
• Double click on this node, click on Payload, select String and enter the following
string THE DATE AND TIME ARE:. Select the Repeat interval to 1 second as
shown in Figure 4.11.
● 47
Programming with Node-RED
• Click Done
• Add node function by clicking on function node and dragging it to the right-hand
side of the inject node already in the workspace
• Wire the two nodes together. Click on the function node and enter the following
as shown in Figure 4.12. Click Done:
msg.payload=new Date();
return msg;
• Add node debug by clicking on debug node and dragging it to the right-hand side
of the inject node already in the workspace.
● 48
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Click the small gray square at the right-hand side of node debug to activate the
node. You should see the message Successfully activated: debug displayed
by the console window
• Click the inject nodes button. You should see the date and time displayed every
second in the following format (see Figure 4.14):
We have learned in this example that the function node allows JavaScript code to be run
against the messages that are passed through it. A function node receives data from its
left, processes the data and outputs from its right.
A function node can have multiple outputs. To create more than one output, double click
on the function node and set Outputs at the bottom left corner to the required value.
Additionally, a function node can create a library by saving your functions. This is done by
double-clicking the function node and then clicking the book icon next to Name. Here, you
will be given options to Open an existing library or to Save the function in a library.
Flow names
We can add new flows by clicking the + sign at the top right-hand side of the screen. The
name of a flow can be changed as follows:
• Click the menu on the far top right-hand side of the screen
● 49
Programming with Node-RED
• Change the name of the existing flow as required and then click DONE.
Modified program
We can modify the function in the above flow program, for example just to display the local
time in the following format:
Time = hh:mm:ss
• Insert an inject node to repeat every second with the string THE CURRENT TIME
• Insert a function node and enter the following statements inside this function
node and click DONE:
• Join all three nodes. Click Deploy and activate the debug node
● 50
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Click the inject nodes button. You should see the time updating every second in
the Debug window as in the format shown in Figure 4.16.
var person = {firstname: "Dogan", surname: "Ibrahim", age: 50, height: 160};
The Node-RED message object is called msg and it has the following properties: payload,
topic, and _msgid.
payload: this property by default stores the payload of the message. The payload can take
the following values (see link: https://nodered.org/docs/user-guide/messages):
By default, the Debug node displays the msg .payload property of a message but can be
configured to display any property or the whole message.
When using a function node, we can store a new text string in variable msg as follows:
_msgid: this is an ID that can be used to identify and track the progress of the message
through a flow.
● 51
Programming with Node-RED
• Create a change node and set the msg.payload to 10 (this is the degrees Celsi-
us) as shown in Figure 4.17. Click DONE
var F = msg.payload;
var C = F*1.8+32;
msg.payload = F + "C = "+ C.toString() + "F";
return msg;
• Create a debug node and join all four nodes together as shown in Figure 4.18.
• Click Deploy
• Activate the debug node and then click the inject nodes button. You should see
10ºC is converted into 50ºF in the Debug node as shown in Figure 4.19
● 52
Chapter 4 • Installing Node-RED software on Raspberry Pi
In this example, we have used a change node. The change node provides the following
functionalities:
With the set operation, we can set a value to msg.payload. This value can be a string or a
number as in the above example, or it can come from another message.
● 53
Programming with Node-RED
There are many nodes available in the standard Node-RED, and it is not possible to look at
all of them in detail in this book. There are also third-party nodes, created and distributed
by several firms. We will only look at the nodes and make ourselves familiar with the nodes
that we will be using in projects with our Raspberry Pi. We can summarize that the nodes
are the fundamental parts of node-RED and some of their application areas are:
• Accessing the GPIO pins of the Raspberry Pi. This enables us to undertake pro-
jects using various sensors and actuators connected to the Raspberry Pi
• Sending and receiving data packets from the Internet. This enables us, for ex-
ample, to carry out remote control operations, for example, to control equipment
over the Wi-Fi
• Sensing and receiving data from the Cloud. This application enables us to devel-
op IoT based applications with the help of Node-RED and Raspberry Pi
4 .8 .1 Exporting flows
Press CTRL and at the same time Click each node in the flow that you want to export. You
will see the clicked nodes as highlighted. If you wish to export all nodes in the workspace,
then click CTRL+A. Then, click Menu -> Export . You will be presented with a window as in
Figure 4.22. Click Copy to clipboard . There are three tabs on the window with the select-
ed nodes tab selected. You can if you wish, change it to export the entire flow or all flows in
the workspace, by selecting current flow or the all flows tabs respectively. You should now
open a file in a text editor and paste the contents of the JASON flow data into this file using
Paste, or CTRL+V. Finally, give a name to the file and save it in a folder of your choice.
● 54
Chapter 4 • Installing Node-RED software on Raspberry Pi
4 .8 .2 Importing aflow
A JASIN formatted flow file must be opened in a text editor and the flow data copied into it
using CNTRL+C . Then you should go to Menu->Import and paste the file from the clip-
board into the window. The new flow can be imported into an existing flow, or into a new
flow. Finally, click the Import button to import the flow. If you find that the Import button
doesn't work (e.g. the button colour is not changed), then it is probable that the file you
are trying to import is not a valid JSON file.
inject: this node injects a timestamp or text into a message The node can be con-
figured either to inject manually or at regular intervals.
● 55
Programming with Node-RED
catch: If a node gives an error while handling a message, it is probable that the
flow will halt. The catch node can be used to catch the errors and return messages
about the error.
mqtt in: this node connects to an MQTT broker and subscribes to messages from
the specified topic
http in: this node creates an HTTP end-point for creating web services
tcp: this node is used to establish TCP communications on a specified port. It ac-
cepts incoming TCP requests
udp: this node is used to establish communication using the UDP protocol. It ac-
cepts incoming UDP packets
serial in: this node reads serial data from the serial port of the local device. The
node can be configured to read at specific times.
debug: This node is used to view messages on the Debug window. The node can
be configured to display either the entire message or just the msg.payload
mqtt out: this node connects to an MQTT broker and publishes messages
http response: this node sends responses back to the HTTP requests received
from HTTP input node.
http request: this node sends HTTP requests and returns the response
udp: this node sends UDP messages to the configured UDP host where the IP ad-
dress and port number are specified. Broadcast is supported
serial out: this node sends data to the defined serial port of the local device. The
node can be configured to send some control characters such as newline after a
message
● 56
Chapter 4 • Installing Node-RED software on Raspberry Pi
template: this node is useful for constructing messages and configuration files
where name:value pairs are inserted into the template
delay: this node delays messages by a random or specific time
trigger: this node can be used as a watchdog timer. It can also be used to create
two output messages with time intervals when an input message is received
http request: this node is used to construct and then send an HTTP request to a
given URL
tcp request: this node sends msg.payload to a TCP server and expects a re-
sponse. The node is configurable, for example, it can be configured to wait for a
specific character, or to return immediately
change: this node can be used to set, change, or delete the properties of incoming
messages
range: this node maps numerical input data to new output data
csv: this node parses msg.payload and converts to or from CSV format. The input
can be a string in which case a JavaScript object is outputted. If on the other hand,
the input is a JavaScript object, then a CSV formatted string is outputted
html: this node is used to extract data from an html type document in msg.payload
json: this node converts to or from a JSON object and JavaScript object
xml: this node converts to or from XML format and JavaScript object
random: this node generates a random number between a high and a low value
smooth: this node is used for various functions such as max, min, mean, high,
and low pass filter
rbe: this is the rbe (Report By Exception) node which generates message if its
input is different from the previous input
● 57
Programming with Node-RED
email in: this node is used to read new emails as they arrive at the localhost. It
can be configured to read repeatedly
twitter out: this node Tweets the msg.payload on the configured user account.
Text and binary (image) messages can be sent
tail: this node tails a file and injects the contents into the flow
file in: this node reads the specified file and sends it contents as msg.payload
sentiment: this node analyses the msg.payload and scores incoming words using
the AFINN-165 wordlist, and attaches a sentiment.score property to the msg
watch: this node watches a folder for changes and sends events when files are
added, changed. created or deleted
feedparse: this node monitors an RSS/Atom feed for new entries and if there are
new entries, it delivers them as messages
exec: this node calls to a system command and provides stdout, stderr, and the
return code
rpi gpio in: this is the Raspberry Pi input node. Depending on the state of the in-
put, this node generates a msg.payload with either a 0 or 1. We shall be using this
node in the Raspberry Pi based projects in later Chapters
rpi gpio out: this is the Raspberry Pi output node. The selected hardware pin of
Raspberry Pi is set HIGH or LOW depending on whether msg.payload is 0 or 1. We
shall be using this node in the Raspberry Pi based projects in later Chapters
● 58
Chapter 4 • Installing Node-RED software on Raspberry Pi
rpi mouse: this is the Raspberry Pi mouse button node. The node generates a 0 or
1 when the selected mouse button is clicked and released. A USB mouse is required
rpi keyboard: this node is used to capture keystrokes from a USB keyboard
Sense HAT: this is the Raspberry Pi Sense HAT input (or output) node. There are
two nodes with the same name: one for the input, and the other one for the output
• Create a random node and name it as Dice. Double click to edit it and set to
generate whole integer numbers between 1 and 6 as shown in Figure 4.23. Click
Done
• Join all three nodes as shown in Figure 4.24 and click Deploy
• Click the inject nodes button. You should see a number between 1 and 6 dis-
played in the Debug window. Every time you click the inject nodes button, a
random number will be generated and displayed between 1 and 6 as shown in
Figure 4.25
● 59
Programming with Node-RED
.
Figure 4.25 The Debug window
• Create two random nodes with the names Dice1 and Dice2. Double click to edit
them and set to generate whole integer numbers between 1 and 6 for both nodes
as in the previous project.
• Create a join node with the name join payloads. Double click this node and
edit as shown in Figure 4.26. Notice that the message parts are set to 2 and are
separated with a space character. Click Done
● 60
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Join the five nodes as shown in Figure 4.27, and click Deploy
• Click the inject nodes button to generate two random numbers next to each
other in the Debug window as shown in Figure 4.28.
● 61
Programming with Node-RED
Notice here that, if the After a number of message parts in node join was set to 1, then
the two dice numbers would not have been displayed next to each other as shown in Figure
4.29.
inchTocm: this node injects a number to the function to convert inches to cm. In
this example, the value (topic) is set to 12 inches for demonstration purposes
mTocm: this node injects a number to the function to convert meters to cm. In this
example, the value (topic) is set to 2 m for demonstration purposes
● 62
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Create a function node named Conv, and enter the following code inside the
function (see Figure 4.30) and click Done:
if(conv == "inchTocm")
{
msg.payload = number+"inch = "+number*2.54+"cm";
}
else if(conv == "cmToinch")
{
msg.payload = number+"cm = "+ number/2.54+"inch";
}
else if(conv == "mTocm")
{
msg.payload = number+"m = "+number *100+"cm";
}
return msg;
● 63
Programming with Node-RED
• Create a debug node and then connect all 5 nodes together as shown in Figure
4.31. Then, click Deploy.
• Click one of the inject nodes buttons to display the conversion in the Debug
window as shown in Figure 4.32. In this figure, the inchTocm and mTocm nodes
are clicked.
● 64
Chapter 4 • Installing Node-RED software on Raspberry Pi
When the button of inject node First is clicked, the message First node clicked is dis-
played by debug node Debug1
When the button of inject node Second is clicked, the message Second node clicked is
displayed by debug node Debug2
When the button of inject node Third is clicked, the message Third node clicked is dis-
played by debug node Debug3
Node Topic
1 First
2 Second
3 Third
• Create a function node named Func, set its Outputs to 3, and enter the follow-
ing code inside the function (see Figure 4.33). Notice that in a statement involv-
ing several if statements, it might be more readable to use a switch statement.
Now click Done:
if(conv == "First")
{
var msg1 = {payload: "First node clicked"};
return [msg1,null,null];
}
else if(conv == "Second")
{
var msg2 = {payload: "Second node clicked"};
return [null,msg2,null];
}
else if(conv == "Third")
{
var msg3 = {payload: "Third node clicked"};
return [null,null,msg3];
}
● 65
Programming with Node-RED
• Click one of the inject nodes buttons to display a message. Figure 4.35 shows
the messages displayed in the Debug window when inject nodes First and Third
were clicked.
● 66
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Create a smooth node named Mean, as shown in Figure 4.37, click Done, and
set the following parameters:
Property: msg.payload
Action: Return the mean value
Over the last 4 values
Treat: All msg as one stream
● 67
Programming with Node-RED
The Action is set to return the mean (average) of 4 input numbers. Treat is configured so
that all the 4 input numbers are treated as one stream. The Reduce parameter is set to
output only the calculated mean value and not the intermediate values.
• Click the buttons of the four inject nodes, starting from the top node. You will
notice that no output id produced until the last inject node is clicked. The result is
(3+7+8+2) / 4 = 5) is displayed in the Debug window as shown in Figure 4.38.
● 68
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Create a function node named Squares and enter the following statements in-
side this function (Figure 4.40). The function displays the heading SQUARES OF
NUMBERS and then calculates and displays the squares of numbers from 1 to 5:
var k;
var m;
● 69
Programming with Node-RED
• Create a debug node named Debug. Join all 3 nodes and click Deploy
• Click the inject nodes button and you should see the squares of numbers dis-
played as shown in Figure 4.41.
In this flow program, the send statement is used to output messages to the output of the
function independent of the return values. i.e. output is not returned by the function, Here
the function returns a null but the actual data from the function is output using the send
statement.
• Click the Install tab and enter the following in the search path (see Figure 4.42)
node-red-node-openweathermap
● 70
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Click install inside the right-hand side of the box displaying node-red-node-
openweathermap
• Click Close
Now that the openweathermap node is installed, we have to register and get an API key
before we can use this node to get the local weather reports. An API key can be obtained
as follows:
• A new API key will be sent to the email address that you provided
We are now ready to create and use our flow program. The steps are given below:
• Double click on the node and enter your API key, select the current weather and
enter your city and country as shown in Figure 4.43. Name the node as Local
Weather. Click Done
● 71
Programming with Node-RED
• Click, drag, and drop a debug node. Join the three nodes as shown in Figure 4.44.
Click Deploy
• Click inject nodes button. You should see the JASON formatted local weather
report displayed in the Debug window as shown in Figure 4.45
● 72
Chapter 4 • Installing Node-RED software on Raspberry Pi
As you can see, the report is very comprehensive, it shows that the weather was cloudy,
the temperature at the time of making the request was 6.1ºC, the humidity was 87%, at-
mospheric pressure was 1020 mbars, the wind speed was 3.1m/s and so on. The city where
this report is generated for and its co-ordinates are given at the bottom part of the report.
In the next project, we will add a function node and see how we can display only the current
temperature in the Debug window.
• Create a function node and name it as Temperature. Double click this node
and enter the following statements (see Figure 4.46):
var T;
T = msg.payload.tempc;
msg.payload = "Current temperature= "+T+ " Degrees C";
return msg;
• Create a debug node. Join the 4 nodes together as in Figure 4.47. Click Deploy.
• Click inject nodes button. You should see the current temperature displayed in
the Debug window as shown in Figure 4.48
● 73
Programming with Node-RED
If the email node is not available in your Node Palette, you can install it as follows:
node-red-node-email
• Close Manage palette. You should now have 2 email nodes in the Node-RED
screen Node Palette
You can also install the email node by the following commands:
cd ~/.node-red
npm i node-red-node-email
Now that the email node is installed, we can carry on to create our flow program. The steps
are given below:
• Click, drag and drop the email node (the one with an envelope picture on its
right-hand side) to the workspace. Double click and configure as shown in Figure
4.49
● 74
Chapter 4 • Installing Node-RED software on Raspberry Pi
• Set the To field to the destination email address (you can specify more than one
email addresses by separating them with commas), set the Userid to the email
account from where the message will be sent from, and finally, set the password
of this Userid account.
• Click Done
• If you are using a Gmail account, you will have to enable less secure access
via your Google account settings. Alternatively, enter the following to your web
browser:
myaccount.google.com/u/1/lesssecureapps
• Click the inject node button. The current temperature will be sent to the email
address you specified. Figure 4.51 shows the mail sent to the author's email
address.
● 75
Programming with Node-RED
You can modify this project if you wish so that the temperature is sent at regular intervals
to your email address. To do this, edit the inject node and set the repetition interval to the
required value.
If the twitter node is not available in your Node Palette, you can install it as follows:
node-red-node-twitter
• Close Manage palette. You should now have 2 twitter nodes in the Node-RED
screen Node Palette: twitter in and twitter out
You can also install the twitter node using the following commands:
cd ~/.node-red
npm i node-red-node-twitter
Now that the twitter node is installed, we can carry on to create our flow program. The
steps are given below:
• Create a function node (Figure 4.52), name it as TempPress, and enter the
following statements inside this node:
● 76
Chapter 4 • Installing Node-RED software on Raspberry Pi
var T;
T = msg.payload.tempc;
P = msg.payload.pressure;
msg.payload = "T= "+T+ " Degrees P="+P+" mbars";
return msg;
• Click, drag and drop a twitter out node and name it as Tweeter. Double click
to configure this node. Enter your Twitter ID (e.g. @DoganIbrahim7) as shown
in Figure 4.53
• Click the pen symbol on the right-hand side of the Twitter ID. You will be present-
ed with a screen where you have to enter your Twitter credentials. This requires
registering at the Twitter site (developer.twitter.com/en/apps) and getting the
following four keys unique to your application:
API Key, API secret Key, Access token, Access token secret
• Enter your Twitter ID and then copy and paste the four keys you obtained from
the Twitter site (see Figure 4.54). Click Done to close the node data
● 77
Programming with Node-RED
• Now, join the 4 nodes as shown in Figure 4.55, and click Deploy
• Click the inject nodes button. The local temperature and atmospheric pressure
readings will be sent to your twitter account as shown in Figure 4.55 which was
copied from the author's mobile phone.
Figure 4.55 Temperature and atmospheric pressure sent to the twitter account
The default settings file has most of its lines commented out. You can enable the comment-
ed lines but it is recommended that you know exactly what you are ding before enabling
the commented lines. To enable a comment line, just remove the two slash characters (//)
in front of the required line.
Additionally, there is a Settings option in the Menu when Node-RED is up and running,
● 78
Chapter 4 • Installing Node-RED software on Raspberry Pi
where the user View, Keyboard, and Palette options can be configured as shown in Fig-
ure 4.56.
4 .22 Summary
In this chapter, we have learned how to start Node-RED software on Raspberry Pi. In addi-
tion, we have learned how to use some Node-RED nodes in various flow programs. Several
examples and projects are given in this chapter to make the reader familiar with some of
the important concepts of Node-RED.
In the next chapter, we will be learning how to use Node-RED to access Raspberry Pi GPIO
pins, and how to interface sensors and actuators to Raspberry Pi, and how to control them
from Node-RED based flow programs.
● 79
Programming with Node-RED
5 .1 Overview
All versions of Raspberry Pi include a socket for connecting external devices, such as sen-
sors, LEDs, actuators, etc. In this chapter, we will look at how external devices connected
to Raspberry Pi can be accessed from Node-RED flow programs, by developing projects
using Node-RED.
All the projects given in this chapter will include the following sections to make it easy for
the reader to understand how these projects are developed:
• Title
• Description of the project
• Aim
• Background information (where necessary)
• Block diagram (where necessary)
• Circuit diagram
• Node-RED flow program with a full description
• Suggestions for additional work (where necessary)
Before going into the details of the projects, it is worthwhile to look at the Raspberry Pi
GPIO connector. This is a 40-pin dual-in-line 2.54mm wide connector as shown in Figure
5.1.
● 80
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
The GPIO provides 26 general purpose bi-directional I/O pins. Some of the pins have mul-
tiple functions. For example, pins 3 and 5 are the GPIO2 and GPIO3 input-output pins
respectively. These pins can also be used as the I2C bus I2C SDA and I2C SCL pins respec-
tively. Similarly, pins 9,10,11,19 can either be used as general-purpose input-output, or as
the SPI bus pins. Pins 8 and 10 are reserved for UART serial communication.
Two power outputs are provided: +3.3V and +5.0V. The GPIO pins operate at +3.3V logic
levels (not like many other computer circuits that operate with +5V). A pin can either be
an input or an output. When configured as an output, the pin voltage is either 0V (logic
0) or +3.3V (logic 1). Raspberry Pi is normally operated using an external power supply
(e.g. a mains adapter) with +5V output and minimum 2A current capacity. A 3.3V output
pin can supply up to 16mA of current. The total current drawn from all output pins should
not exceed the 51mA limit. Care should be taken when connecting external devices to the
GPIO pins as drawing excessive currents or short-circuiting a pin can easily damage your
Raspberry Pi. The amount of current that can be supplied by the 5V pin depends on many
factors such as the current required by the Pi itself, current taken by the USB peripherals,
camera current, HDMI port current, and so on.
● 81
Programming with Node-RED
When configured as an input, a voltage above +1.7V will be taken as logic 1, and a voltage
below +1.7V will be taken as logic 0. Care should be taken not to supply voltages greater
than +3.3V to any I/O pin as large voltages can easily damage your Pi.
Aim: The aim of this project is to show how an LED can be connected to a GPIO port pin
and how it can be controlled from a Node-RED flow program.
Background information: The forward voltage of a typical LED is around 1.8V. The cur-
rent through the LED depends on the required light intensity and the type of LED used. In
general, 3mA should give enough visible light for small LEDs. Because the output voltage
of a GPIO pin is +3.3V we have to use a current limiting resistor in series with the LED. The
value of the current limiting resistor is calculated as:
R = (3.3V – 1.8V / 3mA = 500 Ohm. We can choose a 470 Ohm resistor
Be careful that the LED has two pins: anode (long pin) and cathode (short pin). The cathode
pin must be connected to ground (see Figure 5.3).
Circuit diagram: Figure 5.4 shows the circuit diagram of the project where the anode of
the LED is connected to pin GPIO 2 of the Raspberry Pi through a current limiting resistor.
● 82
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Node-RED flow program: Figure 5.5 shows the flow program. In this program, two
inject nodes and a rpi gpio out node are used.
• Create another inject node with the configuration as shown in Figure 5.7
• Create a rpi gpio out node with the configuration as shown in Figure 5.8, set the
Type to Digital output, Initialize pin state to 0, and name it as LED. Click Done
● 83
Programming with Node-RED
• Join the 3 nodes together as shown in Figure 5.5, and click Deploy.
• Connect the LED to Raspberry Pi as shown in Figure 5.4. The circuit was built on
a breadboard and connected to Raspberry Pi GPIO connector using jumper wires
as shown in Figure 5.9.
• Click the button of inject node ON, you should see the LED turning ON. Click the
button of inject node OFF, and this time the LED should turn OFF
● 84
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
As shown in Figure 5.10, you can, if you wish, connect debug nodes to the flow so that the
state of the LED can be displayed at any time in the Debug window. Figure 5.11 shows the
LED state as the LED is turned ON or OFF.
Description: In this project, we will connect an LED to one of the Raspberry Pi GPIO pins
as in the previous project, and then flash the LED every second.
Aim: The aim of this project is to show how an LED connected to a GPIO port pin can be
flashed using a trigger node.
Node-RED flow program: Figure 5.12 shows the flow program. In this program an inject
node, a trigger node, and a rpi gpio out node are used.
• Create an inject node which runs regularly every 2 seconds, whose configuration
is shown in Figure 5.13. Click Done.
● 85
Programming with Node-RED
• Create a trigger node to send out 1, wait for 1 second and then send out 0, with
the configuration as shown in Figure 5.14. Click Done.
• Create the rpi gpio out node as in the previous project. Join the 3 nodes, and
click Deploy.
• Click the inject node's button. You should see the LED flashing every second.
In this project, the inject node activates the trigger node every two seconds, which in turn
controls the LED by turning it ON for a second, and OFF for a second.
You could insert a debug node to the flow program (Figure 5.15) so that the state of the
LED can be displayed. Additionally, you can see the timing accuracy of the project in the
Debug window. This is shown in Figure 5.16.
● 86
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
The function in this example will make use of context variables. A context variable is a static
storage variable in a node that does not lose its value between calls.
Figure 5.17 shows the flow program using a function. In this example, the inject node is
given the name Every second and it is configured to repeat every second. The function
node is given the name Toggle LED and its contents are as follows:
if(context.led == 0)
context.led = 1;
else
context.led = 0;
msg.payload = context.led;
return msg;
● 87
Programming with Node-RED
Description: In this project, we will connect two LEDs to our Raspberry Pi GPIO port pins
and then flash these LEDs alternately every second.
Aim: The aim of this project is to show how more than one LED connected to GPIO port
pins and also how these LEDs can be flashed alternately using trigger nodes.
Circuit diagram: The LEDs are connected to Raspberry Pi port pins GPIO 2 and GPIO 3 as
shown in Figure 5.18.
Node-RED flow program: Figure 5.19 shows the flow program. In this program an inject
node, two trigger nodes, and two rpi gpio out node are used, one for each LED.
• Create a trigger node to send out 1, wait for 1 second and then send out 0, with
the configuration as shown in Figure 5.14, name it as 1->0, and click Done.
• Create another trigger node to send out 0, wait for 1 second and then send out
1, name it as 0->1, and click Done.
• Create a rpi gpio out node as in the previous project and set the GPIO pin num-
ber to 2
• Create another rpi gpio out node as before, and set the GPIO pin number to 3
● 88
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Click Deploy
• Click the inject node's button. You should now see the two LEDs flashing alter-
nately every second.
In this project, the trigger node 1->0 outputs a falling signal level, while node 0->1 out-
puts a rising signal level. The result is that when one LED is ON, the other one id OFF, and
vice-versa. The inject node activates the trigger node every two seconds as before.
As in Project 13, you can create two debug nodes and attach to the outputs of the two
trigger nodes to display the state of the two LEDs.
The function in this example is configured to have two outputs, and it will make use of two
context variables as was described in section 5.4.1.
Figure 5.20 shows the flow program using a function. In this example, the inject node is
given the name Every second and it is configured to repeat every second.
The function node is given the name Toggle LEDs and its contents are as follows (see
Figure 5.21):
if(context.led1 == 0)
{
context.led1 = 1;
context.led2 = 0;
}
else
{
context.led1 = 0;
context.led2 = 1;
}
● 89
Programming with Node-RED
Click the inject node's button. You should see the two LEDs flashing alternately every
second.
Notice how the LED data for each LED is sent to the corresponding outputs of the function
in the return statement. Figure 5.22 shows the project constructed on a breadboard.
Description: This is a simple temperature alarm system. A small active buzzer is connect-
ed to one of the GPIO ports of the Raspberry Pi. The local temperature is read from the
weather site as in Project 9, and if it is above a pre-defined threshold value then the buzzer
is activated. The threshold value is taken to be 30ºC in this project, but it can be changed
any other value if desired. The temperature is checked at every minute.
● 90
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Aim: The aim of this project is to show how a simple temperature alarm system can be
designed with Node-RED, using Raspberry Pi and a small buzzer as the hardware.
Background information: Small buzzers (also known as piezoelectric buzzers) are used
commonly in electronic alarm projects. These buzzers are operated with any voltage from
+3V to +5V. There are two types of buzzers: active buzzers, and passive buzzers. Active
buzzers have built-in electronic circuits and they sound at a fixed frequency when a DC
voltage is applied across their terminals. Usually, the sound frequency of these buzzers is
around 1kHz. It is very easy to use the active buzzers since they can easily be connected to
the output port pin of the Raspberry Pi. Passive buzzers, on the other hand, require a wave-
form (usually PWM or sinewave) to be applied across their terminals, and the frequency of
the generated sound depends on the frequency of the applied waveform. Although it may
be more difficult to use passive buzzers, they have the advantages that the sound frequen-
cy can easily be changed, for example, they can be used in simple electronic organ projects
to generate sounds at different frequencies. In this project, an active buzzer is used.
Block diagram: Figure 5.23 shows the block diagram of the project.
Circuit diagram: The circuit diagram of the project is shown in Figure 5.24. The buzzer is
connected directly to port pin GPIO 2 of the Raspberry Pi 4.
Node-RED flow program: Figure 5.25 shows the flow program. In this program 4 nodes
are used: an inject node that repeats every minute, an openweathermap node that gets
the local weather report, a function node that extracts the current temperature from the
● 91
Programming with Node-RED
weather report and sends out 1 to the rpi gpio out node to activate the buzzer if the tem-
perature is greater than 30ºC, otherwise, 0 is sent to the rpi gpio out node to deactivate
the buzzer.
• Create an inject node with the name 1m interval, and set the repeat interval
to 1 minute
• Create a function node with the name Check Temperature, and enter the
following statements into this node (see Figure 5.26). Here, if the temperature
is greater than 30ºC then the buzzer is activated, otherwise, the buzzer is deac-
tivated:
var T;
T = msg.payload.tempc;
if(T > 30)
msg.payload = 1;
else
msg.payload = 0;
return msg;
• Create a rpi goio out node named Buzzer, and set the GPIO pin to 2
• Click the inject node's button. The local temperature report will now be obtained
every minute and if it is greater than 30ºC then the buzzer will sound
● 92
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
You can modify the hardware easily, for example by replacing the buzzer with a relay so
that a heater can be turned ON or OFF, or an LED can be used to indicate visually when an
alarm condition occurs. Additionally, a debug node can be connected to the output of the
function node to display the status of the buzzer (1 or 0 will be displayed in the Debug
window)
Description: In this project, we will control a Raspberry Pi GPIO port remotely by sending
an email. A small active buzzer is connected to one of the GPIO ports of the Raspberry
Pi. The buzzer is activated by sending the command ON by email. Similarly, the buzzer is
deactivated by sending the command OF by email.
Aim: The aim of this project is to show how a Raspberry Pi GPIO port can be controlled
remotely by sending an email.
Block diagram: The block diagram of the project is as shown in Figure 5.23.
Circuit diagram: The circuit diagram of the project is as shown in Figure 5.24, where the
buzzer is connected directly to port pin GPIO 2 of the Raspberry Pi 4.
Node-RED flow program: Figure 5.27 shows the flow program. In this program 3 nodes
are used: an email in node that gets emails at regular intervals, a function node that
sends 1 or 0 to its output depending on whether the user command is ON or OF respective-
ly, and a rpi gpio out node to control the buzzer.
• Click, drag and drop the email in node to the workspace. Configure this node as
shown in Figure 5.28 and click Done. The node is configured to check for incom-
ing emails every 10 seconds. The emails are expected to come to the Gmail ac-
count with username: dogantest99@gmail.com, where the password should also
be specified (you will have to replace these to your own Gmail account details)
● 93
Programming with Node-RED
• Create a function node named ON/OF, having the following statements (see Fig-
ure 5.29). Here, function substr is used to extract the first two characters of the
received email command. If the command is ON, then 1 is returned to activate
the buzzer. Otherwise, if the command is OF, then 0 is returned to deactivate
the buzzer. Click Done:
if(cmd == "ON")
return On;
else if(cmd == "OF")
return Off;
● 94
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create a rpi gpio out node and set the port number to GPIO 2. Join the 3 nodes
and click Deploy
The program now should check the email account every 10 seconds. You should see the
words connecting and fetching displayed under the email in node just before the ac-
count is checked. In this project, the buzzer should sound when an email is sent to account
dogantest@gmail.com with the mail content having the word ON. Similarly, the buzzer
should stop sounding when the word OF (note it is OF and not OFF) is sent by email.
Just a reminder, if you are using a Gmail account, you will have to enable less secure
access via your Google account settings. Alternatively, enter the following to your web
browser:
myaccount.google.com/u/1/lesssecureapps
The buzzer in this project can be replaced for example with a relay if desired so that elec-
trical equipment (e.g. home appliances) can be controlled remotely by sending emails from
anywhere in the world.
Description: In the previous project we have seen how to control a Raspberry Pi GPIO port
remotely by sending emails. The problem here is that when we send a command to the
Raspberry Pi we are not sure whether or not the GPIO port has taken the required value.
In this project, we read the state of the GPIO port and send an email to confirm the state
of the port pin. The confirmation is very important in some applications, for example, if we
wish to activate our home boiler using a relay, we want to make sure that the boiler has
actually been activated.
If the command ON is sent to activate the buzzer, then the message Buzzer is ON will be
sent to the specified email address when the buzzer is actually turned ON. If on the other
hand command OF is sent, then the message Buzzer is OFF will be sent to the specified
email address.
Aim: The aim of this project is to show how the state of a GPIO port pin can be read and
then a message can be sent to an email account to confirm the state of the GPIO port pin.
Block diagram: The block diagram of the project is as shown in Figure 5.23.
Circuit diagram: The circuit diagram of the project is as shown in Figure 5.30. Here, the
buzzer is connected directly to port pin GPIO 2 of the Raspberry Pi 4 as in the previous
project, and GPIO 2 is connected to GPIO 3 where GPIO 3 is configured as an input in
Node-RED. The state of the buzzer will be read by GPIO 3 and a message will be sent to
an email account.
● 95
Programming with Node-RED
Node-RED flow program: Figure 5.31 shows the flow program. In this program 6 nodes
are used: 3 nodes to receive the email and control the buzzer accordingly, and 3 nodes to
send the state of the buzzer port to the specified email address.
• The first 3 nodes used to receive emails is same as in the previous project and
are not repeated here again (only the name of the email in node is changed)
• The next 3 nodes are used to receive the state of port GPIO 3 and send an email
to the specified address.
• Click rpi gpio in node, drag and drop it to the workspace. Name this node as
GPIO 3 and set it to receive the state of port GPIO 3 as shown in Figure 5.32,
click Done. This port will receive the state of port pin GPIO 2 which is connected
to GPIO 3.
● 96
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create a function node, name it as Buzzer State, enter the following state-
ments, and click Done (Figure 5.33):
if(msg.payload == "1")
msg.payload = "Buzzer is ON"
else
msg.payload = "Buzzer is OFF"
return msg;
• Click on email out node, drag and drop it in the workspace and name it as Send
Mail. Configure this node as shown in Figure 5.34. The state of the buzzer is sent
to email address: d.ibrahim@btinternet.com from email address: dogantest99@
gmail.com (you should enter your own email addresses and passwords)
● 97
Programming with Node-RED
• Join the nodes as in Figure 5.31, and click Deploy. To test the program, send
command ON to email address dogantest99@gmail.com, and the buzzer should
be activated. At the same time, the message Buzzer is ON will be sent to email
address d.ibrahim@btinternet.com (you should use your own email addresses
and passwords).
Description: In this project, we will control 4 Raspberry Pi GPIO ports remotely by sending
an email. Four LEDs are connected to the Raspberry Pi GPIO ports through current limiting
resistors. The LEDs are turned ON/OFF by sending email commands in the following form:
Aim: The aim of this project is to show how multiple GPIO ports of the Raspberry Pi can be
controlled remotely by sending Email messages.
Block diagram: Figure 5.35 shows the block diagram of the project.
● 98
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Circuit diagram: The circuit diagram of the project is shown in Figure 5.36. The LEDs
are connected to the following Raspberry Pi port pins through 470 Ohm current limiting
resistors:
Port pin number 9 of the Raspberry Pi is the ground pin that is connected to the cathode
pins of all the LEDs.
Node-RED flow program: Figure 5.37 shows the flow program. In this program 6 nodes
are used: an email in node to check and get the email at regular intervals, a function
node with 4 outputs to decode the user commands, and 4 rpi gpio out nodes to control
the 4 LEDs.
● 99
Programming with Node-RED
• Create email in node as in the previous projects and name it as Receive Email
• Create a function node named ON/OFF with the following statements (see
Figure 5.38). Variable cmd extracts the first 3 characters of the command and
for valid commands, it has the value of ON= or OF=. Variable port extracts the
required LED number and for valid commands, it has the values of 1, 2, 3, or 4.
Notice how multiple outputs are handled in the function:
if(cmd == "ON=")
{
if(port == "1")
return [On, null, null, null];
else if(port == "2")
return [null, On, null, null];
else if(port == "3")
return [null, null, On, null];
else if(port == "4")
return [null, null, null, On]
}
if(cmd == "OF=")
{
if(port == "1")
return [Off, null, null, null];
else if(port == "2")
return[null, Off, null, null];
else if(port == "3")
return [null, null, Off, null];
else if(port == "4")
return [null, null, null, Off]
}
● 100
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Figure 5.38 Configuring the function (only part of the code is shown)
• Create 4 rpi gpio out nodes, one for each of the LEDs, LED1, LED2, LED3, and
LED4. Set the port pin names to GPIO 2, GPIO 3, GPIO 4 and GPIO 17 re-
spectively and clear the initial states of the ports to 0. An example for GPIO 17
is shown in Figure 5.39. Click Done for each node.
● 101
Programming with Node-RED
• Join the nodes as shown in Figure 5.37 and click Deploy. To test the program,
connect the hardware as in Figure 5.36 and send an email for example with the
contents of ON=2. LED2 should turn ON. Send an email with OF=2 and this time
LED2 should turn OFF
The LEDs used in this project can be replaced with relays if desired so that electrical equip-
ment can easily be controlled remotely by sending emails.
Figure 5.40 shows the project constructed on a breadboard where the LEDs are connected
to the Raspberry Pi using jumper wires.
Just a reminder, if you are using a Gmail account, you will have to enable less secure
access via your Google account settings as described in earlier projects using the email
nodes.
Description: In this project, we will simulate a set of traffic lights. 3 LEDs are connected
to the GPIO ports of the Raspberry Pi: a Red LED, an Orange LED, and a Green LED. The
LEDs are turned ON and OFF as in the following PDL sequence:
DO FOREVER
Turn Red LED ON for 17 seconds
Turn Red and Orange LED ON for 3 seconds
● 102
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Aim: The aim of this project is to show how a simple traffic light simulator program can be
developed with Node-RED using 3 LEDs connected to a Raspberry Pi.
Block diagram: Figure 5.41 shows the block diagram of the project.
Circuit diagram: The circuit diagram of the project is shown in Figure 5.42. The LEDs
are connected to the following Raspberry Pi port pins through 470 Ohm current limiting
resistors:
Port pin number 9 of the Raspberry Pi is the ground pin that is connected to the cathode
pins of all the LEDs.
Node-RED flow program: Figure 5.43 shows the flow program. In this program 11 nodes
are used: an inject node to start the simulation, 4 delay nodes to generate the required
timing delays, 3 trigger nodes, and 3 rpi gpio out nodes.
● 103
Programming with Node-RED
• Create 4 delay nodes as shown in Figure 5.43. These nodes will generate the
required delay timings. For example, when the Red LED is triggered to stay ON
for 20 seconds. After a delay of 17 seconds, the Orange LED is also turned ON
so that both the Red and Orange are ON for 3 seconds. After this time the Green
LED is triggered to stay ON for 15 seconds, and after this time the Orange LED is
turned ON for 3 seconds, and then back to the Red LED. This sequence is repeat-
ed forever. Figure 5.44 shows a typical delay node configuration.
• Create 3 trigger nodes that send out 1, wait for the specified time, and then
send out 0. Figure 5.45 shows as an example of how the 20s trigger node is
configured.
● 104
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create 3 rpi gpio out nodes for the GPIO pins GPIO 2, GPIO 3, and GPIO 4, and
name them as RED, ORANGE, and GREEN respectively. As an example, Figure
5.46 shows the configuration of node GREEN.
• Join all the nodes as shown in Figure 5.43, and click Deploy. Click the button
of node inject to start the simulation. You should see the 3 LEDs simulating the
traffic lights with the timing as specified at the beginning of this project.
● 105
Programming with Node-RED
Notice that in this project the comment node is also introduced. This node helps us to write
comments about a project. In this example project, the contents of the comment node are
shown in Figure 5.47.
Description: This is a very simple project where a push-button switch (button for short)
and an LED are connected to the Raspberry Pi. The project turns ON the LED when the
button is pressed.
Aim: The aim of this project is to show how a button can be used in a Node-RED based
project.
Buttons can be used in two modes: Normally LOW, and normally HIGH. In a normally LOW
mode, the output state of the button is at logic 0 by default and goes to logic 1 when the
button is pressed. The output stays at this state until the button is released. The circuit
diagram in Figure 5.48 shows a normally LOW button.
● 106
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
In a normally HIGH button, the state of the button is at logic 1 by default and goes to logic
0 when the button is pressed. The output stays at this state until the button is released.
The circuit diagram in Figure 5.49 shows a normally HIGH button.
The button used in this project is a small component having 4 pins as shown in Figure 5.50.
Actually, the button is a 2 pin device where the pins are paralleled for convenience.
Mechanical switches have bouncing problems. This happens because when a switch is tog-
gled, its mechanical contacts bounce (move from one state to another state) until they
settle. Although this settling time may seem to be very small (around 10ms), it is actually
a very long time when the processing time of a microcontroller is considered. Special switch
debouncing circuits can be used to eliminate this bouncing effect. Luckily, the rpi gpio in
node provides a parameter to set the switch debouncing time so that the switch contacts
are not read until this time expires. This makes sure that the correct switch output state is
read by the microcontroller.
Block diagram: Figure 5.51 shows the block diagram of the project.
● 107
Programming with Node-RED
Circuit diagram: The circuit diagram of the project is shown in Figure 5.52 where the LED
is connected to port pin GPIO 2. Port pin GPIO 3 is connected to one side of the button,
while the other side of the button is connected to the ground pin of Raspberry Pi.
Node-RED flow program: Figure 5.53 shows the flow program. In this program 2 nodes
are used:
• Create a rpi gpio in node and mane it as BUTTON, set the pin name to GPIO 3,
and set the resistor to pulldown.
• Create a rpi gpio out node and name it as LED, set the pin name to GPIO 3, and
initialize the pin level to 0
• Join the two nodes as shown in Figure 5.51, and click Deploy.
You should see that the LED is ON, and pressing the button turns OFF the LED.
Notice that in this flow program we want the opposite. i.e. the LED should be OFF normally,
and pressing the button should turn it ON. A modified flow program that will work correctly
is shown in Figure 5.54
● 108
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create a rpi gpio in node as above and name it as BUTTON, set the pin name
to GPIO 3, and set the resistor to pulldown
• Create a switch node and name it as IF 1 or 0. Configure this node such that if
the input is 1, direct it to the top output, otherwise, direct it to the second out-
put. To direct to the second output, click add, and select otherwise as shown in
Figure 5.54. Click Done.
• Create a change node and name it as Set to 0. Configure this node to return 1
as shown in Figure 5.56. Click Done
• Create another change node and name it as Set to 1 and set the output to 1.
Click Done
• Create a rpi gpio out node and name it as LED, set the pin name to GPIO 3, and
initialize the pin level to 0
You should now see that the LED is OFF, and pressing the button turns the LED ON.
● 109
Programming with Node-RED
Description: This is a very simple project where the brightness of an LED is altered by
changing the average voltage and hence average current through the LED.
Aim: The aim of this project is to show how a PWM waveform can be generated using
Node-RED.
A PWM waveform is basically a positive square waveform where the ON time (also called
the MARK) and the OFF time (also called the SPACE) can be changed. Figure 5.58 shows
a typical PWM waveform with a period of the T. The ratio of the ON time to the period is
known as the Duty Cycle of the waveform and by changing the duty cycle we can effectively
change the average voltage supplied to the load.
● 110
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
The duty cycle is commonly represented as a percentage. For example, a 50% duty cycle
corresponds to the situation where the ON time is equal to the OFF time. In a 100% duty
cycle, the waveform is always ON (i.e. there is no OFF time). Similarly, in a 25% duty cycle,
the duration of the ON time is a quarter of the period of the waveform. Figure 5.59 shows
PWM waveforms with different duty cycles.
Circuit diagram: The circuit diagram of the project is as in Figure 5.4 where an LED is
connected to port pin GPIO 2 of Raspberry Pi.
Node-RED flow program: Figure 5.60 shows the flow program. In this program, 6 nodes
are used: 5 inject nodes with different duty cycle settings and a rpi gpio out node.
• Create 5 inject nodes, set the payloads to numeric values of 2, 5, 10, 50, 100.
These will be the duty cycles of the PWM waveform. Name each inject node with
their corresponding duty cycles as shown in Figure 5.60. For example, the con-
figuration of the node with a 50% duty cycle is shown in Figure 5.61
● 111
Programming with Node-RED
• Create a rpi gpio out node and name it as LED, set the port name to GPIO 2, and
set the Type to PWM output as shown in Figure 5.61. Click Done
Join the nodes as in Figure 5.60. Click inject node 2% and you should see that the LED is
very dim. Clicking higher duty cycles should make the LED brighter.
5 .13 Summary
In this chapter, we have learned how to connect external components to Raspberry Pi GPIO
ports and then how to access these components from Node-RED programs.
In the next chapter, we will be looking at how to connect an LCD to our Raspberry Pi and
we will also develop further projects using an LCD.
● 112
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
6 .1 Overview
In microcontroller systems, the output of a measured variable is usually displayed using
LEDs, 7-segment displays, or LCD type displays. LCDs have the advantages that they can
be used to display alphanumeric or graphical data. Some LCDs have 40 or more character
lengths with the capability to display several lines. Some other LCD displays can be used to
display graphics images. Some modules offer colour displays while some others incorporate
backlighting so that they can be viewed in dimly lit conditions.
There are basically two types of LCDs as far as the interface technique is concerned: par-
allel LCDs and serial LCDs. Parallel LCDs (e.g. Hitachi HD44780) are connected to a micro-
controller using more than one data line and the data is transferred in parallel form. It is
common to use either 4 or 8 data lines. Using a 4 wire connection saves I/O pins but it is
slower since the data is transferred in two stages. One of the most commonly used parallel
LCD standard is the HD44780.
The programming of a parallel LCD is usually a complex task and requires a good under-
standing of the internal operation of the LCD controllers, including the timing diagrams.
Fortunately, most high-level languages provide special library commands for displaying
data on alphanumeric as well as on graphical LCDs. All the user has to do is connect the LCD
to the microcontroller, define the LCD connection in the software, and then send special
commands to display data on the LCD.
Serial LCDs are connected to the microcontroller using only a few data lines. Serial LCDs are
much easier to use but they cost more than the parallel ones. One of the most commonly
used serial LCDs makes use of the I2C bus protocol where only two wires are required for
communication, namely SDA (data) and SCL (clock). There is a master device on the bus
and there can be a number of slave devices where each device has a unique address so
that it can be identified. Figure 6.1 shows a typical I2C bus with a master and two slave
devices. Notice that the bus must be terminated with pull-up resistors to the power supply.
Interested readers should be able to find many articles, application notes, and data sheets
on the Internet on I2C. In this chapter, we will be using an I2C based LCD in Node-RED
based Raspberry Pi projects.
Figure 6.1 I2C Bus structure with a master and 2 slave devices
● 113
Programming with Node-RED
It is recommended to use SCL1 in I2C based applications. The two I2C lines are internally
pulled-up to +3.3V power supply using 1.8K resistors.
The I2C on your Raspberry Pi 4 must be enabled using the raspi-config utility before it can
be used. The steps are:
• Select Yes to enable the I2C interface, and click OK and exit from raspi-config
utility
Some of the I2C devices operate with +5V. It is important to be careful when connecting
such devices to your Raspberry Pi since the voltage at the I/O pins of the Raspberry Pi must
not exceed +3.3V, otherwise, the Raspberry Pi can be damaged. It is safe to connect an I2C
device that operates with +5V to your Raspberry Pi if the device does not have any internal
pull-up resistors on its I2C lines. If the I2C lines of the device are connected internally to
+5V, then you must not connect such a device to your Raspberry Pi without using voltage
level converters circuits to lower the voltage from +5V to +3.3V.
● 114
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
6 .3 I2C LCD
The commonly available I2C LCD consists of a standard HD44780 compatible 16x2 char-
acter display that is operated in 4-bit mode. A small board is plugged-in at the back of the
LCD board. This board has a PCF8574 chip that converts I2C serial data to parallel form for
the LCD display. Although the slave address of the LCD can be changed from 0x20 to 0x27,
its default value is 0x27. The LCD module operates with +5V and it has no internal pull-up
resistors on its I2C lines. The module can therefore directly be connected to the Raspberry
Pi I2C lines.
To test the LCD module and find its slave address follow the steps given below:
• Connect the SDA and SCL pins of the LCD modules to GPIO 2 and GPIO 3 port
pins of the Raspberry Pi respectively
• Connect the Vcc and GND pins of the LCD module to +5V and GND pins of the
Raspberry Pi respectively
• You should get a display similar to the one shown in Figure 6.3. Notice in this
figure that the slave address of your LCD module is 0x27
• If the address of the LCD module is not displayed it means that there are some
errors. You should check your connections and try again. You may also have to
install the I2C tools by entering the following commands:
● 115
Programming with Node-RED
A compatible I2C LCD node must be installed so that it is available in the Node-RED palette.
The steps to install it are as follows:
• Start Node-RED and click Menu -> Manage palette and then click Install
The LCD node can be used for LCDs having up to 4 lines, and it accepts an object msg .
payload .msgs. If the object passed does not contain 4 lines the difference is filled with
blank lines. The following points are important while using this LCD node:
• msg must be a string no more than 20 characters long. Scrolling will be done if
more than 20 characters are sent to the LCD.
If there is an error in the data sent to the LCD then an error message will be displayed on
the LCD screen.
An example is given below to show how the LCD node can be used.
Example
Develop a flow program to display the text Hello From at the top row and My LCD in the
second row.
Solution
The required flow program is shown in Figure 6.5.
● 116
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create a function node and name it as Display. Enter the following statements
inside this node (see Figure 6.6).
msg.payload={msgs:[
{msg:"Hello From"},
{msg:"My LCD"}
]};
return msg;
The message in the first part of the statement enclosed with {} is sent to the top row, and
the second message enclosed with {} is sent to the bottom row of the LCD.
• Click, drag and drop the LCD20x4 I2C node to the workspace and change its
name to LCD . Set the I2C address to 0x27 and click Done
• Join the nodes as shown in Figure 6.5, and click Deploy. You should see the text
displayed as shown in Figure 6.7
The LCD object format for a two-row LCD (16 x 2) is as follows (see link: https://flows.
nodered.org/node/node-red-contrib-lcd20x4-i2c):
msg.payload = {
msgs: [
{
msg: "string",
● 117
Programming with Node-RED
pos: number,
center: "boolean"
},
{
msg: "string",
pos: number,
center: "boolean"
},
]
};
The data to be displayed is entered after the keyword msg. The first message is for the top
row, and the second message is for the bottom row of the LCD.
Description: In this project, the current time is displayed on the LCD every second in the
following format:
Current Time
Time=hh:mm:ss
Aim: The aim of this project is to show how the current time can be extracted and then
displayed on the LCD every second.
Circuit diagram: Figure 6.8 shows the circuit diagram of the project. The LCD is directly
connected to the I2C pins of the Raspberry Pi.
Node-RED flow program: Figure 6.9 shows the flow program which consists of 3 nodes:
an inject node, a function node, and an LCD20x4 I2C node.
● 118
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create an inject node named Click, and set its interval to one second
• Create a function node named Display, and enter the following commands (see
Figure 6.10), click Done. Variable LocalTime extracts the current local time.
Variable Tim constructs the string Time=hh:mm:ss. The first row of the LCD
displays the text Current Time, and the second row displays the actual time:
return msg;
• Create an LCD20x4 I2C node named LCD and set the I2C Address to 0x27
• Join all 3 nodes as shown in Figure 6.9, click Deploy. Click the button of the in-
ject node. You should see the time displayed on the LCD every second as shown
in Figure 6.11
● 119
Programming with Node-RED
Description: In this project, the current weather forecast is received and the local temper-
ature and humidity are displayed on the LCD every 10 seconds.
Aim: The aim of this project is to show how the local temperature and humidity can be
displayed on the LCD.
Circuit diagram: The circuit diagram of the project is the same as in Figure 6.8.
Node-RED flow program: Figure 6.12 shows the flow program which consists of 4 nodes:
an inject node to request reading every 10 seconds, an openweathermap node to get
the local weather map, a function node to extract the local temperature and humidity, and
an LCD20x4 I2C node to display the temperature and humidity.
• Create an openweathermap node and name it as Temp & Hum. Set the API
key and set your local city and country names. Click Done
• Create an LCD20x4 I2C node and name it as LCD. Set the I2C address to 0x27
as before and click Done
• Click the button of the inject node. You should see the local temperature and
humidity displayed on the LCD as shown in Figure 6.13.
Description: In this project, two random numbers are generated between 1 and 6 and
are displayed on the LCD every time the button of the inject node is clicked. The numbers
are displayed for 5 seconds. After this time the display is cleared and message Ready is
displayed. At this point, the user can click the button of the inject node to generate two new
● 120
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
random numbers. This project can be used in games that are played with dice.
Aim: The aim of this project is to show how two random numbers can be generated and
then combined and displayed on the LCD.
Circuit diagram: The circuit diagram of the project is the same as in Figure 6.8.
Node-RED flow program: Figure 6.14 shows the flow program which consists of 8 nodes:
an inject node to start generating two random numbers, 2 random nodes to generate
two random numbers between 1 and 6, a join node to join the two generated numbers, a
function node to format the numbers for displaying on the LCD, a delay node to generate
5 seconds of delay so that the message Ready can be displayed after 5 seconds, and a
function node which actually displays the message Ready.
• Create two random nodes and name them as Random 1 and Random 2. Set
the nodes to generate random numbers between 1 and 6, click Done
• Create a join node and configure it as shown in Figure 6.15. This node will join
the two random numbers into an array. Click Done.
• Create a function node and name it as Display. Enter the following statements
into this node (see Figure 6.16). These statements extract the two numbers from
the array and combine them into a single variable called disp. The contents of
disp are then displayed on the first row of the LCD. Click Done.
● 121
Programming with Node-RED
• Create an LCD20x4 I2C node and name it as LCD. Set the I2C address to 0x27
as before and click Done
• Create a function node and name it as Ready . Enter the following statements
into this node. This node will display the message Ready on the LCD:
msg.payload={msgs:[
{msg:"Ready"}
]};
return msg;
• Join all the nodes as shown in Figure 6.14 and click Deploy.
• Click the button of the inject node. You should see two numbers generated be-
tween 1 and 6. After 5 seconds the display will clear and message Ready will be
displayed so that clicking the button again will generate a new set of numbers.
Figure 6.16 shows an example output on the LCD.
Description: This is an event counter project. Events are assumed to occur when port pin
GPIO 15 of Raspberry Pi goes from logic 1 to logic 0. In the project, events are simulated
by connecting a push-button switch to GPIO 15 and by pressing the button. The program
counts the events occurring and displays the total at any time on the LCD.
Aim: The aim of this project is to show how a simple event counter program can be devel-
oped using Node-RED.
Circuit diagram: The two-button pins are connected to GPIO 15 and to ground respec-
tively.
● 122
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Node-RED flow program: Figure 6.17 shows the flow program which consists of 3 nodes:
a rpi gpio in node to receive the button inputs, a function node to update the counts, and
an LCD20x4 I2C node to display the count.
• Create a rpi gpio in node and name it as BUTTON. Set the pin number GPIO 15,
set Resistor to pullup and Debounce to 25ms. Notice that Debounce is set to
25ms to eliminate the contact bouncing problems associated with the mechanical
switches as described in Chapter 5. Click to read the initial state of the pin. Click
Done
• Create a function node and name it as Display. Enter the following statements
inside this node (see Figure 6.18). Notice that we are using a context variable
here. The statement:
var count=context.get('count') || 0;
means that if count does not exist in the context object, then make variable
count zero, otherwise assign the stored value to count. The value of count is in-
cremented every time the button is pressed (i.e. msg.payload goes to 0). Count
is then converted into string and sent to the LCD:
var count=context.get('count') || 0;
if(msg.payload == 0)
{
count++;
context.set('count',count);
var cnt = "Events = " + count.toString();
msg.payload={msgs:[
{msg:cnt}
]};
return msg;
}
else
return null;
● 123
Programming with Node-RED
• Create an LCD20x4 I2C node and name it as LCD. Set the I2C address to 0x27
and click Done
• Join all the nodes as in Figure 6.17 and click Deploy. Every time the button is
pressed, the event count will be incremented by one and the total value will be
displayed on the screen as shown in Figure 6.19.
Description: In this project, we use the popular DHT11 digital sensor to measure the am-
bient temperature and humidity and display them on the LCD every 5 seconds.
Aim: The aim of this project is to show how the DHT11 temperature and humidity sensor
can be used in a Node-RED project.
Block diagram: Figure 6.20 shows the block diagram of the project.
Background information: DHT 11 (or DHT22) is one of the popular and most commonly
used digital temperature and humidity sensors. The sensor basically has 3-pins as shown
in Figure 6.21. Although some sensor versions have 4 pins, one of the pins is not used. The
● 124
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
DHT11 is made up of two parts: a capacitive humidity sensor, and a thermistor temperature
sensor. Because the output is digital, the chip also includes an ADC to convert the analog
signals into digital.
• 3V to 5V power supply
• Low cost
• 2.5mA max current (during conversion)
• 20 - 80% humidity range with 5% accuracy
• 0 - 50°C temperature range with ±2°C accuracy
• 1 Hz sampling rate (once every second)
DHT22 is similar to DHT11, it has the same size and shape, but it offers wider measurement
ranges and is also more accurate than the DHT11. In this project, we will be using a DHT11.
Installing the DHTxx Node-RED node: The steps to install the DHTxx (i.e. DHT11 and
DHT22) Node-RED node are as follows:
• You should see a new node called rpi-dht22 in the Node Palette
We are now ready to develop our flow-program to read and display the ambient tempera-
ture and humidity.
● 125
Programming with Node-RED
Circuit diagram: The circuit diagram of the project is shown in Figure 6.23. The I2C LCD is
connected to Raspberry Pi as in the earlier projects in this Chapter. The DHT11 is connected
to the Raspberry Pi as follows:
Node-RED flow program: Figure 6.24 shows the flow program which consists of 3 nodes:
a rpi gpio in node to receive the button inputs, a function node to update the counts, and
an LCD20x4 I2C node to display the count.
• Create an inject node with the name Click and set the interval to 5 seconds
● 126
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create a rpi-dht22 node and configure it as shown in Figure 6.25. Set the Sen-
sor model to DHT11, Pin numbering to BCM GPIO, and the pin number to 15
(GPIO 15), click Done
• Create a function node and name it as Display. Enter the following statements
inside the function (see Figure 6.26). Variables T and H receive the temperature
and humidity readings respectively from the DHT11 every 5 seconds. Temper-
ature is displayed at the top row, while the humidity is displayed at the bottom
row of the LCD:
T = msg.payload;
H = msg.humidity;
Temp = "T = " + T + "C";
Hum = "H = " + H + "%";
msg.payload={msgs:[
{msg: Temp},
{msg: Hum}
]};
return msg;
● 127
Programming with Node-RED
• Create the LCD node as before, join all the nodes and click Deploy.
• Click the button of the inject node. You should see the temperature and humidity
updated and displayed every 5 seconds (see Figure 6.27)
Notice that if you connect a debug node to the output of node rpi-dht22, you will only see
the temperature displayed in the payload. If, however, you set the Output of the debug
node to complete msg object, you will see both the temperature and the humidity dis-
played as shown in Figure 6.28
Figure 6.29 shows the circuit built on a breadboard and connected to the Raspberry Pi using
jumper wires.
● 128
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Description: In this project, an ultrasonic distance sensor module is used and the distance
to any obstacle in front of the sensor is displayed on the LCD.
Aim: The aim of this project is to show how an ultrasonic sensor can be used in a Node-
RED project.
● 129
Programming with Node-RED
The measurement range of the HC-SR04 sensor is 2cm to 400cm. The basic principle of
operation of the ultrasonic sensor module is as follows (see Figure 6.31):
Therefore,
or,
Distance to object (in cm) = (duration of echo time in µs) * 0.017
For example, if the duration of the echo signal is 294 microseconds then the distance to the
object is calculated as follows:
● 130
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Installing the ultrasonic sensor Node-RED node: The steps to install the HC-SR04
sensor Node-RED node are as follows:
• You should see a new node called rpi srf in the Node Palette
• We are now ready to develop our flow-program to read and display the distance
Block diagram: The block diagram of the project is shown in Figure 6.32.
Circuit diagram: Figure 6.33 shows the circuit diagram. Raspberry Pi port pins GPIO 15
and GPIO 18 are connected to the Trig and Echo pins of the sensor respectively. Notice
that the sensor operates with +5V and its Echo output voltage level goes up to +5V. This
is too high for the Raspberry Pi inputs and as a result, a resistive potential divider circuit is
used to lower the sensor output voltage to +3.3V. The VCC and GND pins of the sensor are
connected to +5V and GND pins of Raspberry Pi respectively.
Node-RED flow program: Figure 6.34 shows the flow program which consists of 3 nodes:
a rpi srf node to read the distance from the sensor, a function node to format the data to
be displayed, and an LCD node.
● 131
Programming with Node-RED
• Click, drag and drop the rpi srf node into the workspace. Configure it as shown
in Figure 6.35. Note that by default the distance is measured every 0.5 seconds,
but this can be changed if desired. Set the pin numbers to where the Trig and
Echo pins are connected on the Raspberry Pi. It is important to be careful here
since the pin numbers required here are the physical pin numbers of the header
and not the GPIO pin names. In this project, Trig and Echo pins are connected to
GPIO pins 15 and 18 respectively, which correspond to physical pin numbers 10
and 12 respectively.
• Create a function node and mane it as Distance. Enter the following state-
ments into this node (see Figure 6.36). Here, variable Distance is loaded with
the actual measured distance in centimeters. The first row of the LCD displays
a heading, while the second row displays the measured distance. Click Done:
● 132
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create the LCD node as before, join all 3 nodes and click Deploy . You should see
the distance displayed on the LCD. Place something in front of the sensor and you
should see the distance changing (see Figure 6.37)
Figure 6.38 shows the circuit built on a breadboard (notice in this figure that the author had
no 2K resistors and used 2x1K resistors instead).
● 133
Programming with Node-RED
Description: In this project, an ultrasonic distance sensor module is used, as in the previ-
ous project. Additionally, an active buzzer is used such that if the distance to any obstacle
is less than 20cm then the buzzer is activated. This project can be used in mobile robotic
applications or to aid while parking your car.
Aim: The aim of this project is to show how an ultrasonic sensor can be used together with
a buzzer in a Node-RED project.
Circuit diagram: The circuit diagram of the project is shown in Figure 6.40, where an
active buzzer is connected to port pin GPIO 23. The remainder of the circuit is the same as
in Figure 6.33.
Node-RED flow program: Figure 6.41 shows the flow program which consists of 3 nodes:
a rpi srf node to read the distance from the sensor, a function node to format the data to
control the buzzer, and a rpio gpio out node which is connected to the buzzr.
● 134
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create a rpi srf node as in the previous project, but set the Repeat interval to a
lower value, e.g. 0.25 second
• Create a function node and enter the following statements. If the distance to
any obstacle is less than 20cm then the output is set to 1 to activate the buzzer:
• Create a rpi gpio out node and name it as Buzzer. Set the Pin to GPIO 23, and
initialize the pin state to 0
• Join all 3 nodes, and click Deploy. Place an object close to the ultrasonic module
and you will hear the buzzer sounding. When the object is removed, the buzzer
should stop sounding.
Description: In this project, it is assumed that two ultrasonic distance sensor modules are
attached to the front and rear of a vehicle. Additionally, an active buzzer is used such that
if the distance to any obstacle at the front or rear of the vehicle is less than 20cm then the
buzzer is activated. This project can be used to aid while parking your car.
Aim: The aim of this project is to show how two ultrasonic distance sensor modules can be
used together with a buzzer in a Node-RED project.
Circuit diagram: The circuit diagram of the project is shown in Figure 6.43. One of the
ultrasonic sensor modules and the buzzer are connected as in the previous project. The Trig
and Echo pins of the second ultrasonic buzzer module are connected to Raspberry Pi port
pins GPIO 24 and GPIO 25 respectively (physical pins 18 and 22).
● 135
Programming with Node-RED
Node-RED flow program: Figure 6.44 shows the flow program which consists of 5 nodes:
2 rpi srf nodes, one for each ultrasonic distance sensor module, a join node to join the two
outputs into an array, a function node to format the output for the buzzer, and a rpi gpio
out node to control the buzzer.
• Create the two rpi srf nodes and set their pins to 10,12 and 18,22. Set the
Repeat times to 0.25 second in each one
• Create a join node and configure as shown in Figure 6.45. This node joins the
two inputs into an array that can be manipulated in the function node
• Create a function node and enter the following statements inside this node, click
Done:
● 136
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Create a rpi gpio out node and set the pin number to GPIO 23
• Join all the nodes as in Figure 6.44, click Deploy. Place objects close to either
sensor and you should hear the buzzer sounding.
Figure 6.46 shows the circuit built on a breadboard ready for testing.
In the remaining parts of this chapter, we will see how an HD44780 type parallel LCD can
be used with Node-RED projects.
● 137
Programming with Node-RED
5 R/W Read/Write
6 E Enable
7 D0 Data bit 0
8 D1 Data bit 1
9 D2 Data bit 2
10 D3 Data bit 3
11 D4 Data bit 4
12 D5 Data bit 5
13 D6 Data bit 6
14 D7 Data bit 7
15 A Anode (light)
16 K Cathode (light)
VSS is the 0V supply or ground. The VDD pin should be connected to the positive supply.
Although the manufacturers specify a 5V D.C supply, the modules will usually work with as
low as 3V or as high as 6V.
Pin 3 is named VEE and this is the contrast control pin. This pin is used to adjust the con-
trast of the display and it should be connected to a variable voltage supply. A potentiometer
is normally connected between the power supply lines with its wiper arm connected to this
pin so that contrast can be adjusted.
Pin 4 is the Register Select (RS) and when this pin is LOW, data transferred to the display
is treated as commands. When RS is HIGH, character data can be transferred to and from
the module.
Pin 5 is the Read/Write (R/W) line. This pin is pulled LOW in order to write commands or
character data to the LCD module. When this pin is HIGH, character data or status informa-
tion can be read from the module.
Pin 6 is the Enable (E) pin which is used to initiate the transfer of commands or data be-
tween the module and the microcontroller. When writing to the display, data is transferred
only on the HIGH to LOW transition of this line. When reading from the display, data be-
comes available after the LOW to HIGH transition of the enable pin and this data remains
valid as long as the enable pin is at logic HIGH.
Pins 7 to 14 are the eight data bus lines (D0 to D7). Data can be transferred between the
microcontroller and the LCD module using either a single 8-bit byte or as two 4-bit nibbles.
In the latter case, only the upper four data lines (D4 to D7) are used. 4-bit mode has the
advantage that four fewer I/O lines are required to communicate with the LCD.
A simple project is given below for completeness, which illustrates how a parallel LCD can
be used in a Node-RED based project.
● 138
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
Description: In this project, a parallel LCD is connected to the Raspberry Pi and the mes-
sage Hello There is displayed on the LCD.
Aim: The aim of this project is to show how a parallel LCD can be used in a Node-RED
based project.
Circuit diagram: Figure 6.47 shows the circuit diagram of the project. The LCD is connect-
ed to Raspberry Pi as follows:
Notice that a 10K potentiometer must be connected to the VEE (or Vo) pin to set the LCD
contrast.
Installing the parallel LCD node: The steps to install the parallel LCD node to Node-RED
palette are given below:
● 139
Programming with Node-RED
• You should see a new node named rpi lcd in the Node Palette
• The node rpi lcd requires to specify where the following LCD pins are connected
to:
Node-RED flow program: Figure 6.48 shows the flow program which consists of 4 nodes:
an inject node, 2 function nodes, where each one sends text to each line of the LCD, and
the rpi lcd control node.
• Create two function nodes and name them as Row 1 and Row 2. These func-
tions contain the text to be displayed on the LCD. Row 1 sends the text for the
top row of the LCD, while Row 2 sends the text for the second row of the LCD.
The contents of Row 1 function is:
• Data to the LCD must be sent as strings. For Row 1, start the data with 1:, for
Row 2 start the data with 2: and so on. String clr: clears the screen.
Interested readers can get more information from the following link:
https://flows.nodered.org/node/node-red-node-pilcd
• Create the rpi lcd node. Configure the node as shown in Figure 6.49.
● 140
Chapter 5 • Node-RED based Raspberry Pi projects using Gpio
• Join all the nodes and click Deploy. Click the button of the inject node and you
should see the following texts displayed on the LCD:
This is Line 1
This is Line 2
6 .15 Summary
In this chapter, we have learned how to use an LCD in Node-RED based Raspberry Pi pro-
jects.
In the next chapter, we will be looking at the Analog-to-Digital Converters (ADC) and see
how we can use ADCs in Node-RED based projects.
● 141
Programming with Node-RED
7 .1 Overview
Most sensors in real life have analog outputs and such outputs cannot be connected direct-
ly to computer input ports. Analog-to-digital converters (ADC) are used to convert these
analog signals to digital form so that they can be read by a computer. Unfortunately, Rasp-
berry Pi computer has no built-in ADC ports and it is not possible to interface it to analog
outputs unless an external ADC circuit is used.
There are many types of ADCs that can be used in projects. Some important ADC parame-
ters that one should take into account before using one are as follows:
Word length: Most ADCs used to be 8 bits wide, having only 256 quantization levels. Such
ADCs are not accurate since only 256 levels are used to represent the input voltage. The
general-purpose ADCs nowadays are usually 10 or 12-bits. A 10-bit ADC has 1024 quan-
tization levels, and a 12-bit ADC has 4096 quantization levels. Considering an 8-bit ADC,
with a reference voltage of +3.3V, each bit corresponds to 12.89mV. This means that input
voltages less than 12.89mV cannot be differentiated. With a 10-bit ADC, each bit repre-
sents 3.22mV, and with a 12-bit converter, each bit represents 0.80mV.
In this chapter, we will be using an external ADC on our Raspberry Pi to read data from
sensors using Node-RED.
• 10-bit resolution
• 2 input channels
• Successive approximation converter
• On-chip sample and hold circuit
• SPI interface to host computer
• +2.7 to +5.5V operation
• 200ksps sampling rate (at +5V)
• 5nA standby current
MCP3002 incorporates on-chip sample and hold circuitry which is required while converting
fast analog input signals. The pin functions are:
● 142
Chapter 7 • Using ADC in Raspberry Pi Node-RED projects
Installing the MCP3002 node: Before using the MCP 3002 in a Node-RED application, we
have to install the MCP3002 node in the Node Palette (the following steps install MCP 3xxx
nodes, which includes other ADC chips in the same family). The steps are given below:
• When the installation is finished, you should see a new node called A/D con-
verter
You can also run the following command from your default Node-RED directory of ~/ .node-
red
We must also enable the SPI interface on our Raspberry Pi 4. The steps are:
Raspberry Pi has the two SPI ports with the following pins:
SPI Port SPI Function Raspberry Pi Pin Name Physical Port number
SPI0 MOSI GPIO 10 19
SPI0 MISO GPIO 9 21
SPI0 CLK GPIO 11 23
SPI0 CE0 GPIO 8 24
SPI0 CE1 GPIO 7 26
SPI1 MOSI GPIO 20 38
SPI1 MISO GPIO 19 35
SPI1 CLK GPIO 21 40
SPI1 CE0 GPIO 18 12
SPI1 CE1 GPIO 17 11
● 143
Programming with Node-RED
SPI communication requires a minimum of 3 pins: MOSI (Master Out Slave In), MISO (Mas-
ter In Slave Out), and CLK (Clock). In some applications, it may also be necessary to enable
the SPI device using one of the CE (Chip Enable) pins.
A project is given in the next section that shows how the MCP 3002 can be used in a project.
Description: This is a voltmeter project. The voltage to be measured is applied to the input
terminals. The measured value is displayed in millivolts on an LCD. In this project, please
make sure that the input voltage is not greater than 3300mV.
Aim: The aim of this project is to show how an ADC can be used in a Node-RED project
with Raspberry Pi.
Block diagram: The block diagram of the project is shown in Figure 7.2.
Circuit diagram: Figure 7.3 shows the circuit diagram of the project. The MCP 3002 ADC
is connected to Raspberry Pi as follows:
● 144
Chapter 7 • Using ADC in Raspberry Pi Node-RED projects
Node-RED flow program: Figure 7.4 shows the flow program which consists of 4 nodes:
an inject node, an A/D converter node, function node, and an LCD20x4 I2C node.
• Create an A/D converter node and configure it as shown in Figure 7.5. Here,
set the Device to mcp3002, Input pin to A0 since we are using channel CH0,
the Device ID to CE1, and SPI bus to 0, click Done
• Create a function node and name it as Calculate mV, and enter the following
statements into this node. Here, the digital value read by the port is converted
into physical millivolts by multiplying with 3300.0 / 1024.0 The floating-point
result is then formatted using function toFixed() so that only 3 digits after the
decimal point are left:
• Create an LCD20x4 I2C node as in the projects in Chapter 6. Join all the nodes
and click Deploy.
● 145
Programming with Node-RED
• Connect the CH0 input of the ADC to an external voltage between 0V and +3.3V.
The value of the voltage will be displayed on the LCD in millivolts as shown in the
example in Figure 7.6.
Description: In this project, an analog temperature sensor chip is used to measure the
ambient temperature and display it every second on the LCD.
Aim: The aim of this project is to show how an analog sensor chip can be interfaced with
Raspberry Pi through an ADC in a Node-RED project.
Background information: In this project, the popular TMP36 type analog sensor chip is
used. This is a 3-pin chip (Figure 7.7), having the following features:
The relationship between the measured temperature and the output voltage is expressed
as follows:
T = (Vo – 500) / 10
Where T is the temperature in ºC, and Vo is the sensor output voltage in millivolts. For
example, if the sensor output voltage is 800mV then the measured temperature is (800 –
500) / 10 = 30ºC and so on.
● 146
Chapter 7 • Using ADC in Raspberry Pi Node-RED projects
Circuit diagram: Figure 7.8 shows the circuit diagram of the project. The output pin of
the TMP36 sensor chip is connected to analog input CH0 if the MCP 3002. The connections
between the MCP3002 and Raspberry Pi are as in the previous project.
Node-RED flow program: The flow program is exactly same as in Figure 7.4, except that
the contents of the function node is different and it should contain the following state-
ments. Here, the temperature is calculated by subtracting 500 from the read value in milli-
volts and dividing by 10. The output is formatted to have two digits after the decimal point:
Figure 7.9 shows an example display of the ambient temperature. Notice here that the de-
gree sign is also displayed after the temperature. For convenience, Figure 7.10 shows the
LCD characters set. The degree sign has the ASCII value 0xDF.
● 147
Programming with Node-RED
Description: This is an ON/OFF temperature control project of a room. The project consists
of a temperature sensor chip, a relay, a heater, an LED, and an LCD. The project controls
the heater through the relay so that the temperature in the room is at the desired setpoint
value. If the temperature in the room is below the setpoint, then the relay is activated to
turn ON the heater. At the same time, the LD is turned ON to indicate that the heater is ON.
If on the other hand, the temperature in the room is above the setpoint, then the relay is
deactivated so that the heater is turned OFF to bring the room temperature to the required
setpoint value. At the same time, the LED is turned OFF to indicate that the heater is OFF.
The top row of the LCD shows the setpoint temperature, while the actual room temperature
is displayed in the second row of the LCD.
Aim: The aim of this project is to show how an ON/OFF type temperature control project
can be developed using Node-RED with a Raspberry Pi.
● 148
Chapter 7 • Using ADC in Raspberry Pi Node-RED projects
controlled is short and the output rate of rise time is small. If precision temperature control
is required, then it may be more appropriate to use professional PID (Proportional+Inte-
gral+Derivative) type controller algorithms with negative feedback or to use an intelligent
fuzzy-based controller. The problem with most professional controllers is that an accurate
model of the plant to be controlled is normally required before a suitable control algorithm
can be derived. ON/OFF type controller has the disadvantage that the relay used to turn the
heater ON and OFF has to operate many times and this may shorten the life of the relay.
Block diagram: Figure 7.11 shows the block diagram of the project.
Circuit diagram: The circuit diagram of the project is shown in Figure 7.12. Most parts of
the circuit are similar to Figure 7.8, but here additionally a relay, a heater, and an LED are
connected to the system. Note that some relays operate only with +5V and if you have one
of these relays, then you will need to have a +3.3V to +5V logic level converter chip to drive
the relay (see the Internet for a suitable converter). The connections between Raspberry Pi
and external components are as follows:
● 149
Programming with Node-RED
Node-RED flow program: Figure 7.13 shows the flow program which consists of 6 nodes:
an inject node, an A/D converter node to read the room temperature, a function node
as the ON/OFF controller, and a LCD20x4 I2C node to display the setpoint and the actual
temperatures, a rpi gpio out node connected to the LED, and another rpi gpio out node
connected to the relay.
• Create a function node with 2 outputs, and name it as ON/OFF Control (see
Figure 7.14). Enter the following statements into this node. In this example, the
setpoint temperature is set to 22ºC. Variable T is loaded with the actual temper-
ature every second. The setpoint temperature is displayed at the top row of the
LCD. Similarly, the actual measured temperature is displayed in the second row
of the LCD. If the actual measured temperature is less than the setpoint value,
then the LED and the relay are turned ON. If on the other hand, the actual meas-
ured temperature is equal or greater than the setpoint value, then the LED and
the relay are turned OFF. Click Done:
● 150
Chapter 7 • Using ADC in Raspberry Pi Node-RED projects
msg.payload={msgs:[
{msg: Setpoint},
{msg: Temp}
]};
• Create a rpi gpio out node and name it as LED. Set the port name to GPIO 17,
and initialize to 0
• Create another rpi gpio out node name it as RELAY. Set the port name to GPIO
27, and initialize to 0
• Connect all the nodes as in Figure 7.13 and click Deploy. The program should
now control the room temperature as required.
Figure 7.15 shows an example display on the LCD where the setpoint temperature is 22ºC
● 151
Programming with Node-RED
7 .6 Summary
In this chapter, we have learned how to use an external analog-to-digital converter chip in
a Node-RED based Raspberry Pi project. In the next chapter, we will be installing and using
the Dashboard to create live dynamic dashboards in Node-RED projects.
● 152
Chapter 8 • The dashboard palette
8 .1 Overview
In the last chapter, we have learned how to use an analog-to-digital converter in a Node-
RED based Raspberry Pi project. In this chapter, we will be installing and using the Dash-
board palette.
The Dashboard palette provides a set of nodes in Node-RED to quickly create a live data
dashboard It is an optional module and not installed by default.
• You will see many new nodes added to the Node Palette under the heading dash-
board as shown in Figure 8.2
● 153
Programming with Node-RED
We are now ready to use the Dashboard nodes. Some examples are given in the next sec-
tions.
Description: In the last chapter we have seen how to read and display the temperature
on an LCD. In this project, we will read the ambient temperature every second and display
it on a gauge node.
Aim: The aim of this project is to show how a gauge node can be used in a Node-RED
project
Circuit diagram: The circuit diagram of the project is as in Figure 7.8 where a TMP36 type
temperature sensor chip is connected to an MCP 3002 type ADC.
Node-RED flow program: Figure 8.3 shows the flow program which consists of 4 nodes:
an inject node, an A/D converter node, a function node, and a gauge node.
• Create a function node and name it as ConvTemp. Enter the following state-
ments into this node to read the temperature and convert to degrees Centigrade
• Create a gauge node and connect all the nodes together as shown in Figure 8.3.
Configure the node as follows:
● 154
Chapter 8 • The dashboard palette
• Click the Group field button to add and configure a dashboard. You should see
the dashboard group edit form. Configure it as shown in Figure 8.4. Click Update
• Configure the gauge node as shown in Figure 8.5. Here, the Label is set to
Temperature, Units to Degrees C, min value to 0 and the max value to 40. Click
Done
• Click the button of the inject node. To see the temperature on the gauge display,
go to the following site with your browser:
http://192.168.1.202:1880/ui/
where 192.168.1.202 is the IP address of your Raspberry Pi. The display in this
project is shown in Figure 8.6.
● 155
Programming with Node-RED
The default Tab option is Home, and it allows you to specify which tab of the UI page you
will see the UI element on (here our chart). The Name field is the Node-RED node name.
The Group field allows you to group UI elements.
The flow program is the same as in Figure 8.3, but the gauge node is replaced with a chart
node and a Line chart is chosen as shown in Figure 8.7.
To configure the chart node, double click on it and configure as shown in Figure 8.8
● 156
Chapter 8 • The dashboard palette
The flow program is the same as in Figure 8.3, but the gauge node is replaced with a chart
node and a Bar chart is chosen as shown in Figure 8.10.
To configure the chart node, double click on it and configure as shown in Figure 8.11
● 157
Programming with Node-RED
You have the other chart options such as Horizontal Bar chart, Pie chart, Polar chart, and
Radar chart. Figure 8.13 shows the temperature displayed using a Horizontal bar chart.
Description: In the last examples we displayed only one item using the Dashboard. In this
project, we will read the current temperature and humidity from the weather report and
then display them using two gauges.
Aim: The aim of this project is to show how two variables can be displayed using two sep-
arate gauges.
Node-RED flow program: Figure 8.14 shows the flow program which consists of 5 nodes:
an inject node, an openweathermap node that reads the weather report, a function
node with 2 outputs that formats the data, and two gauge nodes, one to display the tem-
perature and the other one to display the humidity.
● 158
Chapter 8 • The dashboard palette
• Create an openweathermap node and name it as Temp & Hum, enter your
API key and click Done
• Create a function node and enter the following statements into this node. Var-
iables T and H extract the temperature and humidity from the current weather
report:
T = msg.payload.tempc;
H = msg.payload.humidity;
var1 = {payload: T};
var2 = {payload: H};
return [var1, var2];
• Create a gauge node and set its Label to Temperature, Units to Degrees C, min
to 0 and max to 30, click Done
• Create another gauge node and set its Label to Humidity, Units to %, min to
0 and max to 100, click Done
You should see both the temperature and the humidity displayed in two separate gauges
as in Figure 8.15.
● 159
Programming with Node-RED
Description: In this project, we will read the local weather forecast and display the fol-
lowing using gauges: minimum temperature, current temperature, maximum temperature,
humidity, and atmospheric pressure.
Aim: The aim of this project is to show how multiple gauges can be used in a Node-RED
program.
Node-RED flow program: Figure 8.16 shows the flow program which consists of 8 nodes.
● 160
Chapter 8 • The dashboard palette
Tmin = msg.payload.temp_minc;
Tmax = msg.payload.temp_maxc;
T = msg.payload.tempc;
H = msg.payload.humidity;
P = msg.payload.pressure;
varTmin = {payload: Tmin};
varT = {payload: T};
varTmax = {payload: Tmax};
varH = {payload: H};
varP = {payload: P};
return [varTmin,varT,varTmax,varH,varP];
• Display the Dashboard by entering (enter the IP address of your own Raspberry
Pi):
http://192.168.1.202:1880/ui/
You should see the displays as in Figure 8.17 (note that the gauges are displayed vertically,
and they are cut and pasted horizontally in this figure)
Description: In this example, an LED is connected to one of the Raspberry Pi ports. The
brightness of the LED is changed by using a slider node to change the duty cycle of the PWM
voltage waveform sent to the LED.
Aim: The aim of this project is to show how a slider node can be used.
● 161
Programming with Node-RED
Circuit diagram: The circuit diagram of the project is the same as in Figure 5.4 where the
LED is connected to port pin GPIO 2 through a current limiting resistor.
Node-RED flow program: Figure 8.18 shows the flow program which consists of 3 nodes:
a slider node to change the duty cycle of the PWM waveform (hence the brightness of the
LED), a rpio gpio out node to control the LED, and a gauge node to display the current
value of the duty cycle.
• Create a slider node and name it as PWM Setting. Configure this node as
shown in Figure 8.19, click Done
• Create a rpio gpio out node and name it as LED. Set the pin to GPIO 2, and the
Type to PWM, click Done
• Create a gauge node with name LED Brightness and configure it as shown in
Figure 8.20, click Done
● 162
Chapter 8 • The dashboard palette
• Display the Dashboard by entering (enter the IP address of your own Raspberry
Pi):
http://192.168.1.202:1880/ui/
• Move the slider at the bottom part of the gauge (see Figure 8.21). You should see
the brightness of the LED changing as the slider is moved from 0% to 100% (it
is set to 41% in the figure).
Aim: The aim of this project is to show how the Dashboard button nodes can be used
● 163
Programming with Node-RED
Circuit diagram: The circuit diagram of the project is the same as in Figure 5.4 where the
LED is connected to port pin GPIO 2 through a current limiting resistor.
Node-RED flow program: Figure 8.22 shows the flow program which consists of 3 nodes:
a button node to turn ON the LED, a button node to turn OFF the LED, and a rpi gpio out
button connected to the LED.
• Create a button node and set its Label to ON, and the Payload to 1 so that
the output of the node becomes 1 when clicked in the Dashboard. Configure this
node as shown in Figure 8.23, click Done
• Create another button node and set its Label to OFF, and the Payload to 0 so
that the output of the node becomes 0 when clicked in the Dashboard
• Create a rpi gpio out node and set the Pin to GPIO, Type to Digital output, and
initialize to 0
• Join all the nodes and click Deploy and display the Dashboard as shown in Figure
8.24. Click ON to turn ON the LED, and OFF to turn OFF the LED
● 164
Chapter 8 • The dashboard palette
Aim: The aim of this project is to show how the Dashboard switch and text nodes can be
used in a project.
Circuit diagram: The circuit diagram of the project is the same as in Figure 5.4 where the
LED is connected to port GPIO 2 of Raspberry Pi.
Node-RED flow program: Figure 8.25 shows the flow program which consists of 3 nodes:
a switch node to turn ON/OFF the LED, a text node to display a message, and a rpi gpio
out button connected to the LED.
• Create a switch node and set the On Payload to 1, and Off Payload to 0, as
shown in Figure 8.26, click Done
● 165
Programming with Node-RED
• Create a text node and set the Label to Click switch to turn ON/OFF
• Create a rpi gpio out node and set the Pin to GPIO, Type to Digital output, and
initialize to 0
• Join all the nodes and click Deploy and display the Dashboard as shown in Figure
8.27. Click the switch to turn ON/OFF the LED
Description: This is an interesting talking weather project. In this project the local weather
report is received using the openweathermap node and the data is decoded and then
sent to the PC speakers using the Dashboard audio output node. As a result, you can
hear the weather forecast on your PC speakers. The weather forecast is repeated after 30
seconds when it stops.
Aim: The aim of this project is to show how the Dashboard audio output node can be
used in a project.
Node-RED flow program: Figure 8.28 shows the flow program which consists of 12
nodes: an inject node to start and repeat the weather forecast, an openweathermap
node to get the local weather forecast, a function node that extracts the various local
weather parameters and sends them to delay nodes, 7 delay nodes that insert delays
between the messages, a join node that joins the messages, and a Dashboard audio out
● 166
Chapter 8 • The dashboard palette
• Create an openweathermap node and name it as Weather. Enter the API key,
the local city and country names (see Figure 8.29)
• Create a function node with 7 outputs and name it as Decode (see Figure
8.30). Enter the following statements inside this node. Here, L is the location, T
is the local temperature in Degrees Centigrade, H is the local humidity in %, P is
the local atmospheric pressure in millibars, W is the local wind speed in metres
per second:
L = msg.payload.location;
T = msg.payload.tempc;
H = msg.payload.humidity;
P = msg.payload.pressure;
W = msg.payload.windspeed;
TT = {payload: "The temperature is "+T+" degrees centigrade"};
HH = {payload: "The humidity is "+H+" percent"};
PP = {payload: "The atmospheric pressure is "+P+" millibars"};
WW = {payload: "The wind speed is "+W+" metres per second"};
● 167
Programming with Node-RED
Head = {payload: "This is the weather forecast for " + L + " today"};
This is the weather forecast for London today. The temperature is 7.1 degrees centigrade.
The humidity is 53%. The atmospheric pressure is 1020 millibars. The wind speed is 3.2
meters per second. The weather is very cold and you are advised to wear a thick coat. The
next weather forecast will be in 30 seconds time.
● 168
Chapter 8 • The dashboard palette
• Click the audio out node in the Dashboard palette, drag and drop in the work-
space. Configure this node as shown in Figure 8.32
• Join all the nodes as shown in Figure 8.28 and click Deploy.
http://192.168.1.202:1880/ui/
• Click the button of the inject node. You should hear the weather forecast re-
peating on your speakers. You might have to increase the volume control of your
speakers
8 .13 Summary
In this chapter, we have learned how to use some of the Dashboard nodes in projects.
In the next chapter, we will be using some of the network nodes to control the devices
attached to our Raspberry Pi from a smart mobile phone
● 169
Programming with Node-RED
9 .1 Overview
In the last chapter, we have learned how to use the Dashboard to create some interesting
projects. In this chapter, we will be creating Wi-Fi network-based projects.
UDP (User Datagram Protocol) and TCP (Transmission Control Protocol) are two of the most
commonly used communications protocols in Wi-Fi-based applications to send and receive
data packets over a network. TCP/IP is a reliable protocol that includes handshaking and
thus guarantees the delivery of packets to the required destination. UDP, on the other hand,
is not so reliable but is a fast protocol. Table 9.1 shows a comparison of the UDP and TCP/
IP type communications.
TCP/IP UDP
Connection-oriented protocol Connectionless protocol
Slow Fast
Highly reliable data transmission Not so reliable
Packets arranged in order No ordering of packets
20-byte header size 8-byte header size
Error checking and re-transmission No error checking
Data received acknowledgment No acknowledgment
Used in HTTP, HTTPS, FTP etc Used in DNS, DHCP, TFTP etc
UDP and TCP/IP protocol based programs are server-client based where one node sends
data and the other node receives it and vice-versa. Data is transferred through ports where
the server and the clients must use the same port numbers.
Developing UDP and TCP based programs require good programming knowledge. Luckily,
Node-RED provides nodes that simplify this task considerably. In this Chapter, we will be
developing Node-RED based projects to establish communication between a Raspberry Pi
and smart mobile phone.
● 170
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
Aim: The aim of this project is to show how UDP based network communication can be
established using Node-RED.
Block diagram: Figure 9.1 shows the block diagram of the project.
Circuit diagram: The circuit diagram of the project is the same as in Figure 5.4 where an
LED is connected to port GPIO 2 of Raspberry Pi.
Node-RED flow program: Figure 9.2 shows the flow program which consists of 3 nodes:
a udp in node to receive UDP packets from the mobile phone, a function node to format
the received data to control the LED, and a rpi gpio out node that is connected to the LED.
• Create a udp in node and configure it as shown in Figure 9.3. Here, the Port
number is set to 5000, and Output is set to string, click Done
• Create a function node and name it as ON/OFF. Enter the following statements
into this function. Here, the output is set to 1 if the command is ON, and it is set
to 0 if the command is OFF. Click Done:
● 171
Programming with Node-RED
• Create a rpi gpio out node and set the pin to GPIO 2, name the node as LED,
set it to digital output, and initialize the pin to 0. Click Done
The flow program is now complete and it waits to receive UDP commands from a mobile
phone to control the LEDs. In this project, an Android-based mobile is used for testing the
project. There are many free of charge UDP apps in the Play Store that can be used to send
and receive messages. The one used in this project is called UDP RECEIVE and SEND by
Wezzi Studios (v 3.3), as shown in Figure 9.4
• Set the IP address to the address of your Raspberry Pi (in this project it is
192.168.1.202)
• Enter message ON and click SEND UDP MESSAGE as shown in Figure 9.5 and you
should see the LED to turn ON
● 172
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
Although in this project we controlled a simple LED, there is no reason why we cannot use
for example a relay so that electrical equipment (e.g. a boiler, a lamp, etc) can be controlled
remotely.
Description: In the previous project we controlled only one LED. There are applications
where we may want to control a number of devices remotely. In this project, we will be
controlling 3 LEDs from a mobile phone. Valid commands are:
Aim: The aim of this project is to show how multiple devices can be controlled remotely
using a Node-RED UDP node.
Block diagram: Figure 9.7 shows the block diagram of the project.
● 173
Programming with Node-RED
Circuit diagram: The circuit diagram of the project is shown in Figure 9.8. The LEDs are
connected to GPIO ports GPIO 2, GPIO 3 and GPIO 4.
Node-RED flow program: Figure 9.9 shows the flow program which consists of 5 nodes:
a udp in node to receive UDP packets from the mobile phone, a function node with 3 out-
puts to format the received data to control the 3 LEDs, and 3 rpi gpio out nodes that are
connected to the LEDs.
● 174
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
if(md == "ON")
{
if(no == "1")
{
var1 = {payload: 1};
}
else if(no == "2")
{
var2 = {payload: 1};
}
else if(no == "3")
{
var3 = {payload: 1};
}
}
else if(md == "OFF")
{
if(no == "1")
{
var1 = {payload: 0};
}
else if(no == "2")
{
var2 = {payload: 0};
}
else if(no == "3")
{
var3 = {payload: 0};
}
}
LED1: GPIO 2
LED2: GPIO 3
LED3: GPIO 4
● 175
Programming with Node-RED
To test the project, you can use the apps UDP RECEIVE and SEND described in the pre-
vious project. For example, enter 2=ON and LED2 should turn ON, enter 2=OFF and the
same LED should turn OFF and so on.
As suggested in the previous project, the LEDs can be replaced with relays to control elec-
trical equipment remotely.
Description: In the previous projects we sent data from the mobile phone to Raspberry Pi.
In this project, we will be doing the opposite. i.e. we will be sending data from Raspberry
Pi to the mobile phone. The program will wait to receive the command weather from the
mobile phone. When this command is received, the local weather forecast will be received
and the temperature and humidity will be sent to the mobile phone using the UDP protocol.
The operation of the program is as follows:
Raspberry Pi: Gets local weather report and sends temperature and humidity data to
mobile phone
Aim: The aim of this project is to show how data can be sent from Raspberry Pi to the
mobile phone using the UDP protocol.
Block diagram: Figure 9.10 shows the block diagram of the project.
Node-RED flow program: Figure 9.11 shows the flow program which consists of 6 nodes:
a udp in node to receive UDP packets from the mobile phone, a function node which
checks when command weather is received, a switch node which activates the open-
weathermap node to get the local weather report, a function node to extract the local
temperature and humidity data from the weather report, and a udp out node to send the
temperature and humidity data to the mobile phone.
● 176
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
• Create a udp in node as in the previous project and name it as Receive UDP
• Create a function node and name it as ON/OFF. Enter the following statement
inside this function will return 1 when command weather is received from the
UDP:
var md = msg.payload;
if(md == "weather")
msg.payload = 1;
else
msg.payload = 0;
return msg;
• Create an openweathermap node and name it as Temp and Hum, enter the
API key, set your city (London in this project), and country (the UK in this pro-
ject)
• Create a function node and name it as Get T, H, enter the following statements
inside this function. This function extracts and returns the temperature and hu-
midity from the weather report:
● 177
Programming with Node-RED
D = T + " " + H;
msg.payload = D;
return msg;
• Create a udp out node, name it as SEND UDP, and configure it as shown in
Figure 9.13. Here, the IP address of your mobile phone must be entered into the
Address field (in this project this was 192.168.1.178)
• Join all the nodes as shown in Figure 9.11 and click Deploy
You can test the program using the apps UDP RECEIVE and SEND described in the previ-
ous projects. Enter the Port number as 5000. Then, enter the command weather and click
SEND UDP MESSAGE. The local temperature and humidity data will be displayed on your
mobile phone as shown in Figure 9.14.
● 178
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
Aim: The aim of this project is to show how TCP based reliable network communication can
be established using Node-RED.
Block diagram: The block diagram of the project is the same as in Figure 9.1.
Circuit diagram: The circuit diagram of the project is the same as in Figure 5.4 where an
LED is connected to port GPIO 2 of Raspberry Pi.
Node-RED flow program: Figure 9.15 shows the flow program which consists of 3 nodes:
a tcp in node to receive TCP packets from the mobile phone, a function node to format
the received data to control the LED, and a rpi gpio out node that is connected to the LED.
• Create a tcp in node and configure it as shown in Figure 9.16. A TCP node can
be configured either as a server or as a client. When configured as a server, the
node listens for a connection on a specified port. When configured as a client,
the node connects to a specified remote IP address. In this example, the node is
configured as a server and the port number is set to 5000
• Create a function node and name it as ON/OFF as in Project 41. Enter the fol-
lowing statements into this function.
● 179
Programming with Node-RED
• Create a rpi gpio out node and set the pin to GPIO 2 as in Project 41
The flow program is now complete and it waits to connect to a TCP client. In this project,
an Android-based mobile is used for testing the project as before. There are many free of
charge TCP apps in the Play Store that can be used to send and receive TCP messages. The
one used in this project is called Simple TCP Socket Tester by Armando Jesus Gomez
Parra, as shown in Figure 9.17
• Enter message ON and click SEND as shown in Figure 9.18 and you should see
the LED to turn ON
● 180
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
• Enter message OFF and click SEND as shown in Figure 9.19 and you should see
the LED to turn OFF
Description: In this project, we will control 3 LEDs from a mobile phone as in Project 43,
but now we will be using the reliable connection-based TCP protocol.
As before, the valid commands are:
Aim: The aim of this project is to show how multiple devices can be controlled remotely
using the TCP protocol.
Block diagram: The block diagram of the project is as shown in Figure 9.7.
Circuit diagram: The circuit diagram of the project is as shown in Figure 9.8, where the
LEDs are connected to GPIO ports GPIO 2, GPIO 3 and GPIO 4.
Node-RED flow program: Figure 9.20 shows the flow program which consists of 5 nodes:
a tcp in node to receive TCP packets from the mobile phone, a function node with 3 out-
puts to format the received data to control the 3 LEDs, and 3 rpi gpio out nodes that are
connected to the LEDs.
● 181
Programming with Node-RED
The steps are the same as in Project 43, but the udp in node must be replaced with the
tcp in node. The tcp in node must be configured as in Figure 9.16, and the function node
must be configured as in Project 43.
To test the project, you can use the apps Simple TCP Socket Tester described in the pre-
vious project. For example, enter 2=ON and LED2 should turn ON, enter 2=OFF and the
same LED should turn OFF and so on.
Description: This is very similar to Project 44 . In this project, we will be sending data from
Raspberry Pi to the mobile phone. The program will wait to receive the command weather
from the mobile phone. When this command is received, the local weather forecast will be
received and the temperature and humidity will be sent to the mobile phone using the TCP
protocol.
Aim: The aim of this project is to show how data can be sent from Raspberry Pi to the
mobile phone using the TCP protocol.
Node-RED flow program: Figure 9.21 shows the flow program which consists of 6 nodes:
a tcp in node to receive TCP packets from the mobile phone, a function node which
checks when command weather is received, a switch node which activates the open-
weathermap node to get the local weather report, a function node to extract the local
temperature and humidity data from the weather report, and a tcp out node to send the
temperature and humidity data to the mobile phone.
● 182
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
The steps are the same as in Project 43, except that here the TCP node is used instead of
the UDP node. The tcp in node at the beginning of the program should be configured as
shown in Figure 9.22.
The configuration of the remaining nodes is the same as in Project 43, except the tcp out
node which is the last node in the flow program. This node should be configured as shown
in Figure 9.23, where the Type is set to Reply to TCP.
After joining all the nodes as shown in Figure 9.21, click Deploy. You can now use the apps
Simple TCP Socket Tester to test the program. The steps are:
The current local temperature and humidity values will be displayed on your mobile phone
as shown in Figure 9.24
● 183
Programming with Node-RED
Description: Chat programs are very common in almost all social media sites. Such pro-
grams enable two or more people to communicate in real-time. Chat messages are gener-
ally short to enable the participants to respond to each other quickly. Some chat programs
also offer video links where the participants can see each other while communicating by
text. Most of the chat programs are based on the UDP protocol.
In this project, we develop a simple chat program that enables a person using a mobile
phone to chat with another person using a Raspberry Pi. Node-RED Dashboard nodes are
used in this program to display the message sent between the two parties.
Aim: The aim of this project is to show how a simple chat program can be developed using
the UDP protocol on a Raspberry Pi.
Node-RED flow program: The development of a chat program using Node-RED is rela-
tively easy. What is required is a udp in node to receive the messages, a udp out node
to send out messages, and a tool to display the received and sent messages. Therefore, a
chat program is basically a two-way communication between two devices over the Internet.
Figure 9.25 shows the flow program of our chat program. The program consists of 4 nodes:
a udp in node to receive TCP messages from the mobile phone, a Dashboard text node to
display the received messages, a Dashboard text input node to receive the message to be
sent to the mobile phone, and a udp out node to send the message to the mobile phone.
● 184
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
• Create a Dashboard text input form and configure as in Figure 9.28. Notice that
the Delay parameter is set to 0 so that messages are sent out only after the En-
ter key is pressed (otherwise each key will be sent out as soon as it is pressed)
● 185
Programming with Node-RED
• Join the nodes as in Figure 9.25 and click Deploy. To test the program, use the
apps UDP RECEIVE and SEND as described earlier in this Chapter. Start the
Dashboard by entering the following at your web browser (replace the IP address
with your own Raspberry Pi IP address). Example output on the Dashboard is
shown in Figure 9.30. The corresponding display on the mobile phone is shown
in Figure 9.31:
http://192.168.1.202:1880/ui/
● 186
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
In this modified program, a 5 seconds delay node is inserted at the output of the text.
Also, a change node is inserted with no data in it (see Figure 9.33). The result is that the
message is deleted after 5 seconds of pressing the Enter key so that a new message can
be written.
Description: Ping is a network utility program used to test the reachability of a computer
on a network. Ping measures the round trip time for messages sent from a computer to
a destination computer. Basically, a message is sent out and the time for the message
to echo back is measured and displayed. Ping works if both computers are available on
a network (e.g. Internet or Wi-Fi). In this project, we will send a ping message from our
Raspberry Pi to our mobile phone and display the round trip time.
Aim: The aim of this project is to show how the ping utility can be used in a Node-RED
application.
Node-RED flow program: The network group of nodes includes a pin node that can be
used in an application. The easiest setup is to enter the IP address of the destination com-
puter in node ping and connect a debug node to the output of this node. This way, the ping
return data will be displayed in the Debug window. In this project, we will use a Dashboard
text node to display the ping return data dynamically. Figure 9.34 shows the flow program
of the project.
● 187
Programming with Node-RED
• Create a ping node by clicking, dragging and dropping it from the network pal-
ette. Double click to configure this node as shown in Figure 9.35. Here, the node
is configured to output every 5 seconds. The IP address of the author's mobile
phone is given as the Target (you should choose your own IP address). Note that
you can also enter a valid web address, e.g. www.bbc.co.uk
• Create a text node by clicking, dragging and dropping it from the Dashboard.
Configure this node as shown in Figure 9.36
• Join the two nodes and click Deploy. Start your dashboard. You should see the
round trip time as shown in Figure 9.37
● 188
Chapter 9 • Wi-Fi UDP/TCP Network-Based projects
9 .10 Summary
In this chapter, we have learned how to use UDP and TCP nodes in Node-RED based appli-
cations to communicate with a mobile phone.
In the next chapter, we will be looking at storage nodes and learn how we can store data
in a file.
● 189
Programming with Node-RED
10 .1 Overview
In the last chapter, we have learned how to use Node-RED nodes for UDP and TCP based
network communication. In this chapter, we will be looking at the important topic of how to
store data in files on a Raspberry Pi SD card, using Node-RED nodes.
Data on Raspberry Pi is normally stored on the SD card which is also loaded with the oper-
ating system. The default user folder is /home/pi. In this chapter, we will be creating files
in the default directory and then store data in these files.
Description: In this project, we will be reading the local weather report every minute us-
ing the openweathermap node and then extract the temperature and the humidity data.
This data will then be stored in a file called temphum .txt on the Raspberry Pi SD card
together with the time that the data was extracted.
Node-RED flow program: Figure 10.1 shows the flow program which consists of 5 nodes:
an inject node which repeats every minute, an openweathermap node which gets the
local weather report, a function node which formats the data, a change node which spec-
ifies the name of the file, and a file node which stores (appends) the data into the specified
file.
• Create an inject node, name it as Click, and set it to repeat every minute
• Create an openweathermap node and name it as Weather. Enter the API key
• Create a function node, name it as Format, and enter the following statements
inside this node. Variable first is initialized to 0 as a context variable. This is
done so that we can insert a heading to the data the first time the function is
run. Thereon, the first is non-zero and the actual data is stored in the file. The
local time is extracted and stored in a variable called Tim which is stored in the
file with every data item.
● 190
Chapter 10 • Storage Nodes
• Create a change node and set msg .filename to the name of the file where we
want the data to be stored, i.e. /home/pi/temphum.txt. Note that we could have
set the filename in the node file as well. If msg.filename is used then the file will
be closed after every write. Configure this node as shown in Figure 10.2
• Create a file node and configure it as shown in Figure 10.3. Notice that the Ac-
tion is set to Append to file, and a new line is to be added after each record
• Join all the nodes as shown in Figure 10.1, and click Deploy.
• Click the button of the inject node. A new file called temphum.txt will be created
in folder /home/pi and the local temperature and humidity data will be stored in
the file every minute.
● 191
Programming with Node-RED
Figure 10.4 shows the files (using command ls) in the default user folder /home/pi. Notice
that file temphum.txt is in this folder. The contents of file temphum.txt (command cat
temphum .txt) are shown in Figure 10.5.
Description: In the previous project we have seen how to store data in a file. In this pro-
ject, we will read the contents of the file that we created in the previous project.
Node-RED flow program: Node file in is used to read the contents of a file either as a
string or as a binary buffer. Figure 10.6 shows the flow program which consists of 3 nodes:
an inject node, a file in node to read the contents of the file, and a debug node that dis-
plays the contents of the file.
• Create a file in node and configure it as shown in Figure 10.7. The Filename is
set to /home/pi/temphum.txt, and the Output is set to a string
● 192
Chapter 10 • Storage Nodes
• Create a debug node and set its Output to debug window. Join the nodes and
click Deploy
• Click the button of the inject node. You should see the contents of the file dis-
played in the Debug window as shown in Figure 10.8. Notice here that all the
contents of the file are displayed and the text is not aligned properly.
• Now, double click on the debug node and change the Output to the system
console. Click the button of the inject node. The system console is the Raspberry
Pi command mode display and you should see that the contents of the file are
displayed correctly as shown in Figure 10.9
● 193
Programming with Node-RED
• The file can be read in different formats. Double click on node file in and change
the Output to a msg per line. Also, change the debug node to output to the
Debug window. Now, click the button of the inject node and you should see the
contents of the file displayed on the Debug window as shown in Figure 10.10
Figure 10.10 Displaying the file contents in msg per line mode
• The file can also be displayed in binary format by setting the Output of node file
into a single Buffer object. In this mode, the output is shown in Figure 10.11.
This display may not seem to have much meaning. Click on the numbers and you
should see the contents of the file displayed correctly as shown in Figure 10.12.
Figure 10.11 Displaying the file contents in single Buffer object mode
● 194
Chapter 10 • Storage Nodes
utf-8 string: the entire file is converted into a string and read and presented as a
text string, and the file cannot be processed before it is completed. Here, the data
must contain text data.
one msg per line: the data is read and presented as lines of text, and the file can
be processed while reading it
a single Buffer object: the data is read as sequence of raw bytes and the com-
plete data is read, it cannot be processed before it is completed
a stream of buffers: the data is read and presented as a sequence of raw bytes,
and it can be processed while reading it
We can easily convert the binary data into string format using function toString(). For ex-
ample, in the following function code, we can set the file in format to a stream of buffers
and convert the data into string format:
Description: In the previous project we have seen how to read the contents of a file us-
ing the file in node. The problem was that the entire contents of the file were read and
therefore it was not possible to process the file while it was being read. In this project, we
will read the file created in Project 50 and extract and display the temperature field only.
Node-RED flow program: Node file in is used to read the contents of the file as in the
● 195
Programming with Node-RED
previous project. Figure 10.13 shows the flow program which consists of 5 nodes: an inject
node, a file in node to read the contents of the file, a delay node to output one message
per second, a function node to extract the temperature field of the data, and a debug
node that displays the extracted data in the Debug window.
• Create a file in node and set the Filename to /home/pi/temphum.txt, and the
Output to a msg per line
• Create a delay node set its Action to Rate limit with 1 msg per second. Config-
ure this node as shown in Figure 10.14
• Create a function node named Temp Field and enter the following statements
inside this node. This node will extract and output the temperature field of the
data:
T = msg.payload.substr(12,4);
msg.payload = T;
return msg;
• Join the nodes and click Deploy. Click the button of the inject node. You should
see the temperature displayed in the Debug window as shown in Figure 10.15
● 196
Chapter 10 • Storage Nodes
10 .5 Summary
Files in Raspberry Pi are normally stored on the SD card that also stores the operating
system. In this chapter, we have learned how to use file nodes to write to and also read
from files.
In the next chapter, we will be looking at the nodes that are used for serial communication,
and develop projects that use serial communication.
● 197
Programming with Node-RED
11 .1 Overview
In the last chapter, we have learned how to write and read from files using Node-RED, and
we have developed several projects on this topic. This chapter is about serial communica-
tion where we will learn how two devices can communicate using serial communication.
Serial communication has been one of the earliest methods of establishing communication
between two devices. Nowadays, this type of communication is not used much, especially
after the invention of USB.
In its simplest form, serial communication between two devices requires only 3 wires: TX
(or TXD, transmit), RX (or RXD, receive), and GND (ground). Figure 11.1 shows the sim-
plest form of serial communication between two devices where the TX and RX lines are
crossed between the devices.
In serial communication, data bytes are broken down into bits and these bits are sent and
received with the correct timings. Data is sent or received as frames where a frame consists
of the following bits:
• Start bit
• 7 or 8 data bits
• Optional parity bit
• Stop bit
The parity bit is used for one-bit error checking and this bit is not used very often. Data is
normally sent with 8 bits. Therefore, a data frame consists of 10 bits, where a device that
wishes to communicate with another device sends out a start bit, followed by 8 data bits,
and a stop bit.
The bit timing, also known as the Baud rate, is very important in serial communication and
both sides must have exactly the same Baud rates. Typical Baud rates are 9600, 19200,
38400, and so on. The Baud rate effectively determines the number of bytes that can be
sent in a second. For example, at 9600 Baud we can send or receive 960 bytes (or charac-
ters) per second.
Older serial communications devices used ±12V as the signal levels, where -12 was known
as Mark and +12 as Space. These signal levels were specified by the standard RS232 pro-
tocol. Two types of connectors were used in RS232 applications: 25-way D-type connector
(you can see these connectors on very old computers), and 9-way D-type connector (usu-
ally found on old laptops). Nowadays, most microcontrollers operate with either +5V or
● 198
Chapter 11 • Serial communication
+3.3V. Therefore, serial communication signal levels have changed to be compatible with
the present-day microcontroller inputs. Sometimes the new levels are also called to be TTL
compatible. It is important to be careful and not to connect an RS232 based line to a mi-
crocontroller input as the high voltage will damage the microcontroller circuitry.
In this chapter, we will be using the serial in and serial out nodes provided by Node-RED to
communicate with the external world over the Raspberry Pi serial port.
Description: In this project, we use an Arduino Uno and a Raspberry Pi. An analog tem-
perature sensor is connected to one of the analog inputs of the Arduino. The Arduino reads
the ambient temperature every 5 seconds and sends it to the Raspberry Pi over the serial
line. The Raspberry Pi reads the temperature from the serial line and displays it in the De-
bug window.
Aim: The aim of this project is to show how the serial communication can be established
using the Node-RED serial in node.
Background information: The Arduino computer can be programmed to use either its
dedicated hardware serial communication port (GPIO port pins 0 and 1) or any of its port
pins can be used in what is known as software serial communication. In software serial
communication, all the timing is done in software. The only disadvantage of using software
instead of hardware in serial communication is that the maximum Baud rate is rather lim-
ited. In this application, we shall be using 9600 as the Baud rate, and there are no timing
problems at this low Baud rate.
Raspberry Pi computers have two built-in hardware UARTs: a PL011 and a mini UART. These
are implemented using different hardware blocks, so they have slightly different charac-
teristics. Since both are 3.3V devices, extra care must be taken when connecting to other
serial communication lines. On Raspberry Pis which are equipped with Wireless/Bluetooth
modules (e.g. Raspberry Pi 3, Zero W, 4, etc), the PL011 UART is by default connected to
the Bluetooth module, while the mini UART is the primary UART with the Linux console on
it. In all other models, the PL011 is used as the primary UART. By default, /dev/ttyS0 refers
to the mini UART and /dev/ttAMA0 refers to the PL011. The Linux console uses the primary
UART which depends on the Raspberry Pi model used. Also, if enabled, /dev/serial0 refers
to the primary UART (if enabled), and if enabled, /dev/serial1 refers to the secondary UART
By default, the primary UART (serial0) is assigned to the Linux console. Using the serial port
for other purposes requires this default configuration to be changed. On startup, systemd
checks the Linux kernel command line for any console entries and will use the console de-
fined therein. To stop this behaviour, the serial console setting needs to be removed from
the command line. This is easily done by using the raspi-config utility by selecting option
5 (Interfacing Options) and then P6 (Serial) and select No. Exit raspi-config and re-start
your Raspberry Pi. You should now be able to access the serial port (Don't forget to re-en-
able the console setting after you finish).
● 199
Programming with Node-RED
In Raspberry Pi 3 and 4, the serial port (/dev/ttyS0) is routed to two pins GPIO 14 (TXD)
and GPIO 15 (RXD) on the header. Models earlier than model 3 uses this port for Bluetooth.
Instead, a serial port is created in software (/dev/ttyS0).
We can easily search for the available serial ports by entering the following console com-
mand:
dmesg | grep tty
The last line in the output below indicates that the console is enabled on serial port ttyS0.
console [ttyS0] enabled
In this book, we are using Raspberry Pi 4. The serial port is: /dev/ttyS0. If you are using
earlier than model 3, use the serial port named: /dev/ttyAMA0
Block diagram: Figure 11.2 shows the block diagram of the project, where the tempera-
ture sensor is connected to the Arduino Uno.
Circuit diagram: The circuit diagram of the project is shown in Figure 11.3. In this project,
an LM35DZ type analog temperature chip is used and its output pin is connected to analog
input A0 of the Arduino Uno. This is a 3-pin device operating with +5V, and its pin configu-
ration is shown in Figure 11.3. The output voltage of LM35DZ is directly proportional to the
temperature and is given by the relationship:
T = Vo / 10
Where, T is the measured temperature in degrees Centigrade, and Vo is the output voltage
of the sensor in millivolts. For example, if the output voltage is 200mV, then the measured
voltage is 20ºC and so on.
● 200
Chapter 11 • Serial communication
The serial connection between the Arduino Uno and Raspberry Pi are as follows. Notice here
that GPIO pins 2 and 3 of the Arduino Uno are used for serial communication (pin 2 for RX
and pin 3 for TX):
Raspberry Pi TXD output is not used in this project. The digital output high voltage of the
Arduino Uno is +5V and as a result, we cannot connect the TX output of Arduino Uno di-
rectly to the Raspberry Pi RXD input. A resistive potential divider circuit is used to lower the
voltage from +5V to +3.3V as shown in Figure 11.3.
Arduino Uno Program: The Arduino program (File: ArduinoTemp) listing is shown in
Figure 11.5. At the beginning of the program, port pins 2 (not used) and 3 are defined as
the software serial communication port lines. Inside the setup routine, the Baud rate is set
to 9600. The remainder of the program runs in the main program loop. Here, analog data
is received from port A0, is stored in variable sensor as a digital value. This value is then
converted into physical voltage in millivolts and stored in floating-point variable mV. The
temperature is then calculated by dividing this number by 10 and storing in floating-point
variable T. Built-in function dtostrf() is used to convert the floating-point value to a string
so that it can be displayed by the Raspberry Pi. This function has the following parameters:
dtostrf(floating variable, min string width, number of vars after dec point,
character buffer)
After converting the temperature value into a string, it is sent through the serial line TX to
the Raspberry Pi every 5 seconds. The data is sent in the following format:
T=nn.mmC
● 201
Programming with Node-RED
/*---------------------------------------------------------
* This program received the ambient temperature from a
* LM35DZ tye analog temperature sensor connected to pin
* A0 of the Arduino Uno. The temperature is sent to
* port 3 in serial form at 9600 Baud
*
* File: ArduinoTemp
*---------------------------------------------------------*/
#include <SoftwareSerial.h>
SoftwareSerial MySerial(2, 3); // RX, TX
float mV, T;
char Temp[10];
void setup()
{
MySerial.begin(9600);
}
void loop()
{
int sensor = analogRead(A0); // Read temperature
mV = sensor * 5000.0 / 1024.0; // in mV
T = mV / 10.0; // in Centigrade
dtostrf(T, 4,2,Temp); // Convert to string
MySerial.print("T="); // Display T=
MySerial.print(Temp); // Display Value
MySerial.println("C"); // Display C
delay(5000); // Wait 5 secs
}
Figure 11.5 Arduino Uno program
We can use the Arduino IDE Serial Monitor to confirm that the program is working as ex-
pected, and the temperature is converted into Degrees Centigrade correctly.
Node-RED flow program: Remove the serial console setting as described earlier in this
Chapter. Figure 11.6 shows the flow program which consists of just 2 nodes: a serial in
node which receives serial data, and a debug node that is used to display the received
data.
● 202
Chapter 11 • Serial communication
• Create a serial in node and configure as shown in Figure 11.7 (Click the pen
after Serial Port), click Update and Done. The Serial Port is set to /dev/ttyS0,
Baud rate is set to 9600, 8 data bits, no parity, and 1 stop bit (these settings
must be same as the settings of the transmitting side)
• Create a debug node, join the nodes and click Deploy. You should see the tem-
perature received from the Arduino Uno displayed in the Debug window as shown
in Figure 11.8
● 203
Programming with Node-RED
Set the Label field of your text node to string Temperature: You should start your Dash-
board. Figure 11.10 shows the temperature displayed with the text node.
• Create a function node and enter the following statements inside this function.
If for example, the temperature is 20.00ºC, then this function will send the text
The temperature now is twenty point zero degrees centigrade to node
audio out so that it can be heard on the PC speakers
• Create an audio out node and tick box: Play audio when window not in focus
• Join the nodes, click Deploy and start your Dashboard. You should hear the cur-
rent temperature spoken through your PC speakers
Description: In this project, a GPS receiver module is connected to the serial input of the
Raspberry Pi. The serial in node is used to receive and display the GPS sentences in the
Debug window.
Aim: The aim of this project is to show how serial data can be received using node serial
in.
● 204
Chapter 11 • Serial communication
Background information: GPS receivers receive geographical data from the GPS satel-
lites and they provide accurate information about the position of the user on Earth. These
satellites circle the Earth at an altitude of about 20,000 km and complete two full orbits
every day. In order for a receiver to determine its position, it is necessary for the receiver
to communicate with at least 3 satellites. Therefore, if the receiver does not have a clear
view of the sky then it may not be possible to determine its position on Earth. In some
applications, external antennas are used so that even weak signals can be received from
the GPS satellites.
The data sent out from a GPS receiver is in text format and is known as the NMEA Sentenc-
es. Each NMEA sentence starts with a $ character and the values in a sentence are separat-
ed by commas. Some of the NMEA sentences returned by a GPS receiver are given below:
$GPGLL: This sentence returns the local geographical latitude and longitude
$GPRMC: This sentence returns the local geographical latitude and longitude,
speed, track angle, date, time, and magnetic variation.
$GPVTG: This sentence true track, magnetic track, and the ground speed.
$GGGA: This sentence returns the local geographical latitude and longitude, time,
fix quality, number of satellites being tracked, horizontal dilution of position, alti-
tude, the height of geoid, and DGPS data
$GPGSV: There are 4 sentences with this heading. These sentences return the
number of satellites in view, satellite number, elevation, azimuth, and SNR.
In this project, the GPS Click board (www.mikroe.com) is used. This is a small GPS receiver
(see Figure 11.12) which is based on the LEA-6S type GPS. This board operates with +3.3V
and provides two types of outputs: I2C or serial output. In this project, the default serial
output is used which operates at 9600 Baud rate. An external dynamic antenna can be at-
tached to the board in order to improve its reception for indoor use or in for use in places
where there may not be a clear view of the sky.
● 205
Programming with Node-RED
Figure 11.13 shows the complete list of the NMEA sentences output from the GPS Click
board every second.
Figure 11.13 NMEA sentences output from the GPS Click board
GPS Click board is a 2x8 pin dual-in-line module and it has the following pin configuration
(pin 1 is the top left pin of the module):
● 206
Chapter 11 • Serial communication
In serial operation, only the following pins are required: +3.3V, GND, TX. In this project,
an external dynamic antenna is attached to the GPS Click board as it was used indoors.
Circuit diagram: Figure 11.14 shows the circuit diagram of the project. The TX serial out-
put pin of the GPS Click board is connected to RXD input of the Raspberry Pi. Since both TX
and RXD pins operate with +3.3V, there is no need to lower the voltage for the Raspberry
Pi input.
Node-RED flow program: Remove the serial console setting as described earlier in this
Chapter. Figure 11.15 shows the flow program which consists of just 2 nodes: a serial in
node which receives serial GPS data, and a debug node that is used to display the received
data.
Configure the serial in node and the debug node exactly as in the previous project. You
should see the NMEA sentences displayed in the Debug window as shown in Figure 11.16.
Notice that only some of the NMEA sentences are shown in this Figure.
● 207
Programming with Node-RED
$GPGLL is one of the commonly used NMEA sentences. This sentence is displayed in Figure
11.16 as follows:
$GPGLL,5127.37032,N,00003.12782,E,221918.00,A,A*61
Notice that the fields are separated by commas. The validity of the data is shown by letters
A or V in the data, where A shows that the data is valid, and V indicates that the data is
not valid.
Description: This project is similar to the previous project, but here the latitude, its direc-
tion, longitude, and its direction are extracted and displayed in the Debug window.
Aim: The aim of this project is to show how the latitude and longitude values can be
extracted from an NMEA sentence. The $GPGLLsentence is used in this example which
includes both the latitude and longitude information.
● 208
Chapter 11 • Serial communication
Circuit diagram: The circuit diagram of the project is the same as in Figure 11.14.
Node-RED flow program: Remove the serial console setting as described earlier in this
Chapter. Figure 11.17 shows the flow program which consists of 4 nodes: a serial in node
which receives serial GPS data, a switch node to extract only the $GPGLL sentence from
the NMEA sentences, a function node to extract the latitude and longitude from the $GP-
GLL, and a debug node which is used to display the data in the Debug window.
• Create a switch node and configure it a shown in Figure 11.18. This node ex-
tracts only the $GPGLL sentences
• Creata a function node and name it as Lat/Lon. Enter the following statements
inside this node. This node extracts the latitude and longitude information and
their directions:
var nmea=msg.payload.split(",");
var lat=nmea[1];
var latdir = nmea[2];
var lon = nmea[3];
var londir = nmea[4];
T = "Lat="+lat+latdir+" Lon="+lon+londir;
msg.payload=T;
return msg;
• Create a debug node to display the result in the Debug window. Click Deploy.
You should see the latitude, longitude, and directions displayed as shown in Fig-
ure 11.19.
● 209
Programming with Node-RED
Modified program
The flow program given in Figure 11.17 displays the latitude and longitude as degrees
and minutes. For example, Lat = 5127.3610N means that the latitude is 51 degrees and
27.3610 minutes and it is in the Northern Hemisphere. Similarly, Lon = 00003.12748E
means that the longitude is 0 degrees 03.12748 minutes east of Greenwich (where the zero
degrees longitude is). In most applications, the latitude and longitude are represented as
decimal degrees and if the point is in the Southern Hemisphere (i.e. direction is S), then a
negative sign is added to the value. Similarly, if the point is on the west side of Greenwich
(i.e. direction is W), then a negative sign is added to the value.
In this section, we will modify the displayed values so that they are displayed as degrees
with the correct signs.
The process is as follows. Consider the example where the Lat = 5127.3610S:
• Take the integer part of the value and divide by 100 to give 51
• Take away 51x100 from the original value to find the minutes value, 5127.3610
– 51x100 = 27.361
Node-RED flow program: The flow program is the same as in Figure 11.17, where only
the contents of the function node changes. The flow program is repeated in Figure 11.20
below so that the exported flow program can be loaded from Figure 11.20.
● 210
Chapter 11 • Serial communication
var nmea=msg.payload.split(",");
var lat=nmea[1];
var latdir = nmea[2];
var lon = nmea[3];
var londir = nmea[4];
//
// Process Latitude
//
var Lat = Number(lat);
var Latint = parseInt((parseInt(Lat)) / 100);
var mins = Lat - 100*Latint;
var degrees = mins / 60;
var LatValue = (Latint + degrees).toFixed(5, 2);
if(latdir == "S")
LatValue = -LatValue;
//
// Process Longitude
//
var Lon = Number(lon);
var Lonint = parseInt((parseInt(Lon)) / 100);
mins = Lon - 100*Lonint;
degrees = mins / 60;
var LonValue = (Lonint + degrees).toFixed(5, 3);
if(londir == "W")
LonValue = -LonValue;
msg.payload="Lat="+LatValue+" Lon="+LonValue;
return msg;
● 211
Programming with Node-RED
Description: In this project we receive and decode the GPS coordinates as in Project 55
with the latitude and longitude converted into degrees. We then plot our location on a map
using the Dashboard node called worldmap.
Aim: The aim of this project is to show how our location can be plotted on a map using a
node called worldmap.
Circuit diagram: The circuit diagram of the project is the same as in Figure 11.14, where
a GPC Click board receives our position data and passes it to the Raspberry Pi.
Node-RED flow program: In this project, we use a Dashboard node called worldmap.
You must install this node in your Node-RED before it can be used. The steps are:
• When the installation is complete, you should see the node worldmap in your
Node Palette.
The flow program of this project is shown in Figure 11.22. It consists of 4 nodes: a serial in
node to receive the GPS data in real-time, a switch node to extract the $GPGLL sentences,
a function node to extract the latitude and longitude in degrees format, and a worldmap
node to show our position on a map.
• Create a function node, name it as Lat/Lon and enter teh following statements
inside this node. Notice how the latitude and longitude should be specified by
variable msg .payload:
var nmea=msg.payload.split(",");
var lat=nmea[1];
var latdir = nmea[2];
● 212
Chapter 11 • Serial communication
• Create a worldmap node and configure it as shown in Figure 11.23. Make the
following settings (assuming you are in the UK):
● 213
Programming with Node-RED
http://192.168.1.202:1880/ui/
• You should see your position marked on the map as shown in figure 11.24. Notice
that here the map is zoomed to show the street level.
● 214
Chapter 11 • Serial communication
You can change the zoom level easily. Figure 11.25 shows the map after zooming out.
You can also change the Base map easily by double-clicking on the worldmap node. Figure
11.26 shows our position with the Base map set to terrain.
Node worldmap includes many features that are not covered in this project as this topic
is beyond the scope of this book. Interested readers can look at the following web site for
very detailed information:
● 215
Programming with Node-RED
https://flows.nodered.org/node/node-red-contrib-web-worldmap
Description: In this project, we will receive the weather report using node openweath-
ermap and then send the temperature and humidity readings to the Arduino Uno every 5
seconds on a serial line. The Arduino will display the temperature at the top row and the
humidity at the bottom row of an LCD.
Aim: The aim of this project is to show how serial data can be outputted from Raspberry
Pi using the serial out node.
Block diagram: The block diagram of the project is shown in Figure 11.27.
Circuit diagram: Figure 11.28 shows the circuit diagram of the project. The serial output
pin of the Raspberry Pi is connected to pin 3 of the Arduino Uno, where this pin is configured
as serial input. A standard HD44780 compatible parallel LCD is connected to the Arduino
Uno as shown in the figure. The output HIGH voltage of a Raspberry Pi pin is maximum
+3.3V and this is not enough to drive the input of the Arduino Uno. A logic level converter
module (Figure 11.29) is used to increase the output voltage level of Raspberry Pi to +5V.
As shown in Figure 11.30, the one used in this project is a 2-channel module. A MOSFET
transistor is used to convert +3.3V to +5V, and a resistive potential divider circuit is used
to convert from +5V to +3.3V.
● 216
Chapter 11 • Serial communication
Arduino Uno program: Figure 11.31 shows the Arduino Uno program (program: ar-
duinolcd). At the beginning of the program, the software library and the LCD libraries are
included in the program. The interface between the LCD and the Arduino Uno is defined.
Here, the pins should be defined as follows: RS, E, D4, D5, D6, D7. The software library
pins are defined such that pin 2 is input and pin 3 is output (not used in this project). In-
side the setup routine, the serial line Baud rate is set to 9600, the LCD is initialized to 16
characters by 2 lines. The text Arduino is then displayed on the LCD.
The remainder of the program runs inside the main program loop. Here, the program
checks if there is data at the serial port, and if so, function readStringUntil() is used to read
a string of data until the terminating character '#' is detected (this character is sent by
Raspberry Pi to indicate the end of its data) and the received data is stored in string varia-
ble s1 in the form: nn .n,mm#. Then functions indexOf() and substring() is used to extract
the temperature and humidity from string s1. The temperature is displayed at the top row
as T=nn.nC and the humidity is displayed at the bottom row as H=mm%.
/*---------------------------------------------------------
* This program receives the temperature and humidity data
* from the Raspberry Pi over teh serial line at 9600 Baud.
* The temperature and humidity are displayed on an LCD
*
* File: Arduinolcd
*---------------------------------------------------------*/
#include <SoftwareSerial.h> // Serial library
#include <LiquidCrystal.h> // LCD library
LiquidCrystal lcd(8,9,4,5,6,7); // LCD connections
SoftwareSerial MySerial(2, 3); // RX, TX
● 217
Programming with Node-RED
void setup()
{
MySerial.begin(9600); // Start serial
lcd.begin(16,2); // Init LCD
lcd.print("Arduino"); // Display Arduino
delay(1000); // Wait 1 second
}
void loop()
{
if(MySerial.available() > 0) // Data available?
{
lcd.clear(); // Clear LCD
String s1 = MySerial.readStringUntil('#');
int comma = s1.indexOf(','); // Position of comma
String Temperature = s1.substring(0, comma);
String Humidity = s1.substring(comma+1);
lcd.setCursor(0,0); // Cursor at 0,0
lcd.print("T="); // Display T=
lcd.print(Temperature); // Display Temp
lcd.print("C"); // Display C
lcd.setCursor(0,1); // Cursor at 0,1
lcd.print("H="); // Display H=
lcd.print(Humidity); // Display humidity
lcd.print("%"); // Display %
}
}
Figure 11.31 Arduino Uno program
Node-RED flow program: Figure 11.32 shows the flow program of this project. In this
project there are 4 nodes: an inject node to start the flow, an openweathermap node
to get the local weather report, a function node to extract the temperature and humidity
from this report, and a serial out node to send data to the Arduino Uno over the serial line.
● 218
Chapter 11 • Serial communication
• Create a function node named T and H, and enter the following statements in-
side this node. This node extracts the temperature and humidity, separates them
with a comma and inserts the terminator character '#', click Done:
var T=msg.payload.tempc;
var H = msg.payload.humidity;
All = T + ","+H + "#";
msg.payload = All;
return msg;
• Create a serial out node and configure it as shown in Figure 11.33, click Update
and then Done
• Build your circuit as shown in Figure 11.28, turn ON the Arduino Uno. You should
see the temperature and humidity displayed on the LCD as shown in Figure 11.34
Don't forget, after you finish working with your serial port, you may want to give this port
back to the console. This is easily done by using the raspi-config utility by selecting option
5 (Interfacing Options) and then P6 (Serial) and select Yes. Exit raspi-config and restart
your Raspberry Pi.
● 219
Programming with Node-RED
Description: In the previous project we had to connect the serial output port of our Rasp-
berry Pi to the serial input of Arduino Uno. In this project, we just connect the USB port of
the Arduino to one of the USB ports of the Raspberry Pi. As in the previous project we get
and display the local temperature and humidity on the Android Uno.
Aim: The aim of this project is to show how serial communication can be established using
one of the USB ports of Raspberry Pi.
Block diagram: The block diagram of the project is shown in Figure 11.35. The Arduino
is connected to the Raspberry Pi using a USB cable. There is no other connection between
the two computers.
Raspberry Pi USB port device name: Before using the Raspberry Pi USB ports, we have
to know their device names. Perhaps the easiest way is to display the serial device list with-
out the Arduino, and then connect Arduino to Raspberry Pi and display the device list again.
This way, the device name of the Raspberry Pi can be found very easily. The command to
display the serial devices is:
pi@raspberrypi:~ $ ls /dev/tty*
Figure 11.36 shows the serial devices on the author's Raspberry Pi before Arduino Uno was
connected.
The device list after connecting the Arduino Uno to the Raspberry Pi with a USB cable is
shown in Figure 11.37.
● 220
Chapter 11 • Serial communication
Comparing the two figures, it is obvious that the USB port device name is: /dev/ttyACM0 .
Now that we know the device name, we can modify our Arduino and Node-RED flow pro-
grams accordingly.
Arduino Uno program: The Arduino Uno USB port is connected to hardware serial port
pins 0 (RX) and 1 (TX) and is named just Serial. Therefore, the only changes required in
Figure 11.31 is to remove the software serial ports and replace MySerial with Serial. The
modified program (program: arduinousb) listing is shown in Figure 11.38.
/*---------------------------------------------------------
* This program receives the temperature and humidity data
* from the Raspberry Pi over a USB link at 9600 Baud.
* The temperature and humidity are displayed on an LCD
*
* File: Arduinousb
*---------------------------------------------------------*/
#include <LiquidCrystal.h> // LCD library
LiquidCrystal lcd(8,9,4,5,6,7); // LCD connections
void setup()
{
Serial.begin(9600); // Start serial
lcd.begin(16,2); // Init LCD
lcd.print("Arduino"); // Display Arduino
delay(1000); // Wait 1 second
}
void loop()
{
if(Serial.available() > 0) // Data available?
{
lcd.clear(); // Clear LCD
String s1 = Serial.readStringUntil('#');
int comma = s1.indexOf(','); // Position of comma
String Temperature = s1.substring(0, comma);
String Humidity = s1.substring(comma+1);
lcd.setCursor(0,0); // Cursor at 0,0
● 221
Programming with Node-RED
lcd.print("T="); // Display T=
lcd.print(Temperature); // Display Temp
lcd.print("C"); // Display C
lcd.setCursor(0,1); // Cursor at 0,1
lcd.print("H="); // Display H=
lcd.print(Humidity); // Display humidity
lcd.print("%"); // Display %
}
}
Figure 11.38 Modified Arduino Uno program
Node-RED Flow program: The only change required in the flow program in Figure 11.32
is to change the serial port name from /dev/ttyS0 to /dev/ttyACM0 in node serial out,
everything else remains the same. That's all. Click Deploy and you should see the temper-
ature and humidity displayed on the LCD as in Figure 11.34.
Description: In the previous projects we sent data from the Raspberry Pi using a direct
connection to the Arduino, either by connecting the Raspberry Pi transmit pin to Arduino
receive pin, or by connecting the two devices together using a USB cable.
In this project, we use a pair of RF radio modules to send serial data from the Raspberry Pi
to the Arduino Uno. As in the previous project, the temperature and humidity data are sent
to the Arduino Uno which displays them on the LCD.
Aim: The aim of this project is to show how RF radio modules can be used to send (or re-
ceive) serial data from a Raspberry Pi.
● 222
Chapter 11 • Serial communication
tRF is a 2x8 pin module with the following pin names (pin 1 is at the top left corner, NC =
No Connection):
Normally, only the following pins are used in most applications: +3.3V, GND, TXD, RXD
Block diagram: The block diagram of the project is shown in Figure 11.40. Two tRF Click
modules are used to establish the RF radio communication between the devices.
● 223
Programming with Node-RED
Circuit diagram: The circuit diagram of the project is shown in Figure 11.41. On the Rasp-
berry Pi side, the serial output pin TXD (GPIO 14) is connected to the RXD input of the tRF
module.
On the Arduino side, the TXD pin of tRF module is connected to serial input 2 of the Arduino
through a logic level converter (see Figure 11.29) since the output HIGH level of tRF is only
+3.3V (you may find that there may not be a need for a logic level converter here).
Arduino Uno program: The Arduino Uno program is exactly the same as the one given
in Figure 11.31 (program: arduinolcd), except that the Baud rate must be set to 19200
which is the default Baud rate of the tRF module.
Node-RED flow program: The Node-RED flow program for Raspberry Pi is exactly the
same as the one given in Figure 11.32, where /dev/ttyS0 is used as the serial port pin of
the Raspberry Pi, and the Baud rate must be set to 19200.
Build the Arduino and Raspberry Pi circuits as shown in Figure 11.41. You should see the
temperature and the humidity displayed on the LCD as shown in Figure 11.34.
11 .9 Summary
In this chapter, we have learned how to use Node-RED serial in and serial out nodes with
several projects.
In the next chapter, we will be learning how to use Raspberry Pi Sense HAT in projects with
Node-RED.
● 224
Chapter 12 • Using Sense HAT
12 .1 Overview
Sense HAT is an add-on board for Raspberry Pi containing a number of useful sensors and
an LED array. HAT is an acronym for Hardware Attached on Top. Sense HAT was an im-
portant component of the Astro Pi project, which was an educational Raspberry Pi sent to
the International Space Station with the British astronaut Tim Peake to run code developed
by children. The actual Astro Pi had some modifications and had metal casing to make it
suitable for use in space.
In this chapter, we will be designing various projects using the Node-RED Sense HAT node
with the Sense HAT board. Before that, it is worthwhile to look at the features of the Sense
HAT board. Detailed information on Sense HAT can be obtained from the link: magpi.
cc/AstroPiGuide. Also from the Essentials_SenseHAT_v1 (MagPi Essentials series), and
from many other Internet sources.
● 225
Programming with Node-RED
The LED matrix is very useful as it enables you to display text and also data from various
sensors, to play games, etc. We will in later sections of this Chapter how to use display
various items on the LED matrix.
A Node-RED simulator is available that can be downloaded from the Internet free of charge.
The simulator allows you to create flows and interact with a virtual Sense HAT, without
having the actual hardware. The simulator is useful to first try a project on the simulator
before purchasing the hardware.
The motion events are the readings from the accelerometer, gyroscope, magnetometer,
and compass heading, which are sent approximately 10 per second. The payload is the
values of the sensors, and the topic is the motion. The sensor values are returned with the
following units:
● 226
Chapter 12 • Using Sense HAT
• Accelerometer (x,y,x) in Gs
• Gyroscope (x.y.z) in radians/s
• Orientation (roll, pitch, yaw) in degrees
• Compass heading in direction of North in degrees
The environmental events are readings from the following sensors: temperature,
humidity, and pressure. The payload is the value returned by a sensor and the topic is the
environment. The values are returned with the following units:
The joystick events are sent when the joystick is moved. The payload is the value returned
and the topic is the joystick. The following values are returned:
For example, to get temperature, humidity, and pressure, we can create a function with 3
outputs, and enter the following statement inside the function:
Example projects are given in the following sections to show how Sense HAT nodes can be
used in Raspberry Pi projects. Make sure that the Sense HAT board is plugged on top of
your Raspberry Pi board before using the projects.
Description: In this project, we will get temperature, humidity, and pressure from the
Sense HAT board and display them in the form of gauges and charts.
Aim: The aim of this project is to show how the Environmental Events can be read and
displayed.
● 227
Programming with Node-RED
Node-RED flow program: Figure 12.3 shows the flow program which consists just 8
nodes: a Sense HAT node to get the environmental variables, a function node to extract
the temperature, humidity, and pressure, and 3 gauge nodes to display the temperature,
humidity, and pressure, and 3 chart nodes to display the same variables.
• Create function node, name it as Format and enter the following statements
inside this node:
• Create 3 gauge nodes and 3 chart nodes with the following configurations:
Join all nodes and click Deploy. You should see the temperature, humidity, and pressure
displayed in the Dashboard. Notice that by default the gauges and charts are displayed
vertically. We can, however, group the gauges and charts so that they are displayed hori-
zontally, with the gauges and their corresponding charts displayed vertically together as
shown in Figure 12.4. Grouping of the gauges and charts is shown in Figure 12.5.
● 228
Chapter 12 • Using Sense HAT
Notice that temperature is not displayed correctly. This is because the temperature sensor
on the Sense HAT board is very close to the Raspberry Pi CPU and as a result of this the
reading is not the correct ambient temperature reading. A correct reading can be obtained
if the Sense HAT board is connected to Raspberry Pi using a ribbon cable so that the sensor
is not close to the CPU.
Aim: The aim of this project is to show how the compass heading can be displayed.
● 229
Programming with Node-RED
Node-RED flow program: Figure 12.6 shows the flow program which consists of just
3 nodes: a Sense HAT node to get the motion variables, a function node to extract the
compass heading, and a Dashboard text node to display the heading dynamically.
• Create a function node, name it as Format and enter the following statements
inside this node:
• Join the groups, click Deploy, and start your Dashboard. You should see the
compass heading from North displayed dynamically as shown in Figure 12.7
Aim: The aim of this project is to show how acceleration can be displayed.
Node-RED flow program: Figure 12.8 shows the flow program which consists of 5 nodes:
a Sense HAT node to get the motion variables, a function node with 3 outputs to extract
the acceleration in 3 dimensions, and 3 Dashboard text nodes to display the acceleration
in each direction.
● 230
Chapter 12 • Using Sense HAT
• Create a function node with 3 outputs, name it as Format and enter the fol-
lowing statements inside this node. This function returns the acceleration in 3
dimensions:
• Join the nodes and click Deploy. You should see the acceleration displayed in
your Dashboard as shown in Figure 12.9
Description: In this project, we will display pitch, roll, and yaw dynamically.
Aim: The aim of this project is to show how the orientation can be displayed dynamically.
● 231
Programming with Node-RED
In Figure 12.11, the terms pitch, roll, and yaw as applied to Sense HAT are shown.
Node-RED flow program: The flow program is exactly the same as Figure 12.8, but the
contents of function node and the 3 text nodes are modified. Figure 12.12 shows the flow
program.
● 232
Chapter 12 • Using Sense HAT
• Change the Labels of the text nodes as shown in Figure 12.12. Figure 12.13
shows the pitch, roll, and yaw displayed in the Dashboard.
Perhaps the easiest way to understand the operation of the joystick is to set the Outputs
of the Sense HAT node to Joystick events and connect a debug node to it (Figure 12.14).
By moving or pressing the joystick the Debug window will show the action performed.
For example, moving the joystick left and holding it down generates the message shown
in Figure 12.15.
● 233
Programming with Node-RED
Most of the LED matrix control statements are based on the LED coordinates (x, y) on the
Sense HAT board. Figure 12.16 shows the LED co-ordinates in relation to the board.
Perhaps the easiest way to understand how the LED matrix operates is to create an LED
matric test flow program by connecting an inject node and a function node to the Sense
HAT output node as shown in Figure 12.17, and then examining the LED matrix by writing
statements inside function node.
● 234
Chapter 12 • Using Sense HAT
LED colours
The colour of an individual LED can be set using the statement:
"x,y,colour"
Where x and y must either be from 0 to 7 or a * to indicate the entire row or column. The
colour can be one of the following:
Example 1
Set the LED at co-ordinate 0,0 (i.e. at the top left corner when the USB sockets of Raspber-
ry PI are facing the right-hand side) to red and turn ON the LED as shown in Figure 12.18.
Solution 1
Enter the following statement into the function:
msg.payload = "0,0,red";
return msg;
Example 2
Set all LEDs to a blue colour.
Solution 2
Enter the following statement into the function:
msg.payload = "*,*,blue";
return msg;
● 235
Programming with Node-RED
Example 3
Set LEDs at four corners to blue, red, green, and yellow as shown in Figure 12.19
Solution 3
Enter the following statement into the function:
msg.payload = "0,0,blue,0,7,red,7,0,green,7,7,yellow"
return msg;
Example 4
Set LEDs in a 4-pixel wide column to blue as shown in Figure 12.20.
msg.payload = "0-3,*,blue";
return msg;
Example 5
Set all LEDs in the second row to blue as shown in Figure 12.21.
● 236
Chapter 12 • Using Sense HAT
Solution 5
Enter the following statement into the function:
msg.payload = "*,1,blue";
return msg;
Example 6
Set the diagonal LEDs to red as shown in Figure 12.22.
Solution 6
Enter the following statement into the function:
msg.payload = "0,0,red,1,1,red,2,2,red,3,3,red,4,4,red,5,5,red,6,6,red,7,7,
red";
return msg
We could have also written the following function to set the diagonal LEDs to red:
● 237
Programming with Node-RED
var L="";
for(i=0; i <= 7; i++)
{
if(i != 7)
L = L + String(i)+","+String(i)+",red,";
else
L = L + String(i)+","+String(i)+",red";
}
msg.payload = String(L);
return msg;
Description: In this project, we will flash LEDs on the LED matrix randomly. The colours
are also random.
Aim: The aim of this project is to show how random numbers can be used to flash LEDs
randomly, having random colours.
Node-RED flow program: The flow program is shown in Figure 12.23, and it consists of
11 nodes: an inject node that repeats every second, 5 random number nodes. Two of
these nodes generate numbers between 0 and 7 that correspond to the LED co-ordinates,
the other 3 nodes generate numbers from 0 to 255 to correspond to the RGB colours, a join
node that joins all the random numbers and passes them to a function node. The function
node outputs strings to flash the LEDs randomly having random colours. A delay node is
also used to turn OFF all the LEDs every second so that only one LED is ON at any time.
• Create two random nodes named X and Y and configure them to generate ran-
dom numbers between 0 and 7.
• Create three more random numbers named COLOUR1, COLOUR2 and COL-
OUR3 and configure them to generate random numbers between 0 and 255
● 238
Chapter 12 • Using Sense HAT
• Create a function node named ON and enter the following statements inside
this node:
var x = msg.payload[0];
var y = msg.payload[1];
var c1 = msg.payload[2]
var c2 = msg.payload[3];
var c3 = msg.payload[4];
msg.payload = x + "," + y + "," + c1 + "," + c2 + "," + c3;
return msg;
• Create another function node names OFF and enter the following statements:
msg.payload = "*,*,off";
return msg;
• Create a Sense HAT output node and join all the nodes. You should see LEDs
turning ON and OFF randomly in different colours.
Description: We have seen earlier in this Chapter how to control LEDs on the LED matrix.
In this project, we will be displaying the temperature in real-time by turning the correct
number of LEDs ON.
There are 64 LEDs in the LED matrix. For simplicity, we will assign each LED to 0.5ºC so
that the temperature can be displayed from 0ºC (corresponding to no LEDs ON) to up to
32ºC (corresponding to all the 64 LEDs ON). Therefore, by counting the number of LEDs
that are ON and dividing the number by 2 we find the temperature.
Aim: The aim of this project is to show how the Sense HAT board can be used to read the
ambient temperature and to display the temperature by turning ON the correct number of
LEDs.
● 239
Programming with Node-RED
Node-RED flow program: The flow program is shown in Figure 12.25, and it consist of
4 nodes: a Sense HAT input node to read the ambient temperature, a function node
with two outputs to format the readings and also to turn OFF the screen so that it can be
updated, a delay node to limit the messages, and a Sense HAT output node to turn the
appropriate number of LEDs ON.
• Create a function node named Format with two outputs, and enter the fol-
lowing statements inside this node. Variable T extracts the temperature from
Sense HAT. Variable OnCount calculates the number of LEDs that must be ON.
For example, if the temperature is 22ºC then 44 LEDs must be turned ON. The
remainder of the code is executed if the temperature is below or equal to 32ºC.
Variable rows is the number of rows of LEDs that must be ON. For example, if
the temperature is 22ºC, then rows is equal to 5 so rows: 0, 1, 2, 3, 4 should be
ON. cols is the remaining LEDs that should be ON. For example, if the tempera-
ture is 22ºC then cols is equal to 4. i.e. 4 more LEDs must be turned ON. Three
for loops are used in the function. The outer loop iterates from 0 to rows, the
inner loop iterates 8 times so that all the LEDs in a given row are turned ON. The
last loop turns ON the remaining LEDs. Variable L stores the pattern that will be
output from the node.
The second output of the function sends text off to the display to clear the screen
so that the display can be updated. When a new LED is turned ON or OFF, the
ones already ON remain ON. For example, if the temperature is 22ºC, then we
have 44 LEDs ON. If the temperature goes down to 20ºC, then the ON count
does not go down to 40. Although a command is sent to turn ON only 40 LEDs,
the ones already ON do not go OFF. Therefore, we clear the screen by turning all
LEDs OFF and then update with the new data.
● 240
Chapter 12 • Using Sense HAT
If the temperature is greater than 32ºC, then the middle LED (at co-ordinate 4,
4) is turned red to indicate that the temperature is outside the limit:
var L="";
var T = msg.payload.temperature;
var OnCount = parseInt(2*T);
if(T <= 32)
{
var rows = parseInt(OnCount / 8);
var cols = OnCount-rows*8;
var l = L.length;
msg.payload=L.substr(0,l-1);
}
else
msg.payload = "4,4,red";
var f = {payload: "*,*,off"};
return [msg, f];
• Create a delay node with the Action set to Rate limit and configure it to send 1
message every 30 seconds. This node is connected to the second output of node
function so that the screen is cleared by sending the text off.
• Create a Sense HAT output node and join all the node, click Deploy. You should
see that the temperature displayed on the LED matrix with the number of LEDs
turned ON. In the example shown in Figure 12.26, 51 LEDs are turned ON.
Therefore, the temperature is 51 / 2 = 25.5ºC. Note that, as described earlier,
the temperature reading of Sense HAT is not accurate since the sensor is close
to the Raspberry Pi CPU.
● 241
Programming with Node-RED
msg.payload = "Hello";
return msg;
We can specify the background colour, text colour, and scroll speed by specifying: back-
ground, color, and speed respectively. Speed can take values 1 to 5, where 1 is slow and
5 is fast (default is 3). An example is shown below which specifies the background colour
as yellow, text colour as red, and the speed as 2:
If the text is a single character, it will be displayed without scrolling. To scroll a single char-
acter, append a blank space after it, e.g. "X ".
Description: In this project, we will scroll the pressure readings on the LED matrix. The
background colour will be set to white, text colour to red, and the speed to 1.
Aim: The aim of this project is to show how the data can be scrolled on the LED matrix.
Node-RED flow program: The flow program is shown in Figure 12.27, and it consists of 3
nodes: a Sense HAT input node to read the ambient pressure, a function node to format
the readings, a delay node to limit the rate of the messages to 1 every 5 seconds, and a
Sense HAT output node to display the data on the LED matrix.
● 242
Chapter 12 • Using Sense HAT
• Create a delay node and set the Action to Rate limit to limit 1 message every
5 seconds. This node is required to slow down the messages coming from Sense
HAT.
• Create a Sense HAT output node as before. Join all the nodes and click Deploy.
You should see the ambient pressure displayed and scrolled on the LED matrix.
Rotate screen
To rotate the screen, enter command R followed by the angle. The angle must be 0, 90, 80,
or 270. In the following example the screen is rotated 180 degrees:
var T = "Hello";
msg.payload = "R90\n" + T;
return msg;
● 243
Programming with Node-RED
12 .14 Summary
In this chapter, we have learned how to use Sense HAT input and output nodes in various
projects.
In the next chapter, we will be learning how to use Node-RED with the Arduino and develop
several projects with the Arduino.
● 244
Chapter 13 • Node-RED with Arduino Uno
13 .1 Overview
Arduino Uno is one of the most commonly used microcontroller development boards cur-
rently. There are hundreds of projects available on the Internet using the Arduino Uno with
sensors, actuators, and display devices.
This Chapter is about using Node-RED with the Arduino Uno. The hardware details of the
Arduino Uno are not given in this chapter as it is assumed that the readers are familiar with
the Arduino Uno and have developed programs using this development board. Interested
readers can find many tutorials, application notes, datasheets, and projects for the Arduino
Uno on the Internet. The chapter describes how to install and use Node-RED for the Arduino
Uno. Several projects are described in the chapter using Node-RED.
• Install node .js (64-bit or 32-bit according to your computer) from the following
site:
https://nodejs.org/en/download
C:\Windows\system32> node-red
● 245
Programming with Node-RED
• You should see messages displayed similar to the ones shown in Figure 13.2. If
you can see these messages, it means that Node-RED is installed correctly on
your PC
• Now start your web browser and enter the following address to start your Node-
RED in your browser (do not close your command window):
http://127.0.0.1:1880
• You should now see the Node-RED startup screen as shown in Figure 13.3 (only
part of the screen is shown here).
• Install the Arduino node. Click Menu -> Manage palette and click Install
• You should see two nods added to the Node Palette: arduino in and arduino
out
The Arduino must be connected to the host computer via USB serial connection. We cannot
use both the Arduino IDE and Arduino nodes at the same time as they will conflict. We will
have to exit from the Arduino IDE in order to use Node-RED. Alternatively, we must stop
Node-RED if we wish to program the Arduino using the IDE.
● 246
Chapter 13 • Node-RED with Arduino Uno
The Firmata protocol is used for communicating between an Arduino and the host com-
puter, providing direct access to the GPIO pins. Before developing our programs, we have
to load the Firmata into our Arduino Uno. The steps are as follows:
• Stop Node-RED
• Click Sketch -> Verify/Compile and then click Sketch -> Upload
You should now start Node-RED on your Windows, and then start the dashboard on your
web browser:
C:\Windows\system32> node-red
http://127.0.0.1:1880
We are now ready to develop Arduino programs using Node-RED. A simple example pro-
gram is given in the next section to show how Node-RED can be used with the Arduino Uno.
Description: This is a very simple program where the LED on the Arduino Uno board at
port 13 is flashed every second.
Aim: The aim of this project is to show how the on-board LED at port pin 13 can be flashed
every second.
Node-RED flow program: Figure 13.4 shows the flow program which consists of just 3
nodes: an inject node that repeats every second, a function node that toggles its output,
and an Arduino out node.
● 247
Programming with Node-RED
• Create a function node, name it as Toggle LED and insert the following state-
ments inside this node. In this node, a context variable is toggled so that its value
changes between 0 and 1. Remember that context variables keep their values
inside the node:
context.led = !context.led || 0;
msg.payload = context.led;
return msg;
• Create an arduino out node and configure it as shown in Figure 13.5. Notice
that the serial port number found earlier (COM5) is used in this node.
• Join all the nodes as shown in Figure 13.4 and click Deploy.
Description: In this project, the ambient temperature is measured using an analog tem-
perature sensor chip.
Aim: The aim of this project is to show how arduino in node can be used to read analog
input data.
Circuit diagram: An LM35DZ type analog temperature sensor chip is used in this project.
The sensor is connected to +5V and its output is connected directly to analog input A0 of
the Arduino Uno. Figure 13.6 shows the circuit diagram of the project.
● 248
Chapter 13 • Node-RED with Arduino Uno
Node-RED flow program: Figure 13.7 shows the flow program which consists of just 3
nodes: an arduino in node to receive the temperature readings, a function node to for-
mat the data, and a debug node to display the data in the Debug window.
• The temperature will be displayed in the Debug window as shown in Figure 13.9
● 249
Programming with Node-RED
Description: In this project, the ambient temperature is measured as in the previous pro-
ject and is displayed in node text of the Dashboard.
Aim: The aim of this project is to show how Dashboard nodes can be used in Arduino pro-
jects.
Node-RED flow program: Figure 13.10 shows the flow program which consists of just 3
nodes: an arduino in node to receive the temperature readings, a function node to for-
mat the data, and a Dashboard text node.
Before using a Dashboard node, we have to install the Dashboard Palettes. The steps are:
• You should see the Dashboard nodes added to your Node Palette
● 250
Chapter 13 • Node-RED with Arduino Uno
• Join all nodes and click Deploy. Start the Dashboard by entering the following
into your web browser. You should see the ambient temperature displayed as
shown in Figure 13.12 (notice that the Style is set to Dark in this display):
127.0.0.1:1880/ui/
Description: In this project, the ambient temperature is measured as in the previous pro-
ject and is displayed in the form of a gauge and chart.
Aim: The aim of this project is to show how the Dashboard gauge and chart can be used
in Arduino projects.
Node-RED flow program: Figure 13.13 shows the flow program which consists of 4
nodes: an Arduino in node to read the temperature, a function node to format the temper-
ature, a gauge and a chart nodes to display the temperature.
● 251
Programming with Node-RED
• Click Deploy and you should see the temperature displayed in the Dashboard
using a gauge and a chart as shown in Figure 13.16
● 252
Chapter 13 • Node-RED with Arduino Uno
We can connect the Arduino to one of the USB ports of Raspberry Pi and then write code
using the Arduino IDE. The output can then be sent to Raspberry Pi via the serial port. The
Raspberry Pi can receive the data using the serial node and process it as we have seen in
earlier chapters of this book. This approach, of course, requires code to be developed for
the Arduino.
Description: In this project, a DHT11 temperature and humidity sensor are used and
the ambient temperature and humidity data are displayed in the form of a gauge every 5
seconds.
Aim: The aim of this project is to show how the serial node can be used to receive data
from the Arduino Uno.
Circuit diagram: The circuit diagram of the project is shown in Figure 13.17. The DHT11
is connected to digital port pin 3 of the Arduino Uno. The Arduino Uno is connected to one
of the USB ports of Raspberry Pi using a USB cable. The temperature and humidity data
are sent through this cable.
● 253
Programming with Node-RED
Arduino Uno program: Before using the DHT11 with the Arduino Uno, we have to include
the DHT11 library in our Arduino library. The steps are as follows:
• Enter DHT11
The Arduino program (program: dht11arduino) is shown in Figure 13.18. At the begin-
ning of the program, pin 3 is assigned to DHT11 and DHT11 is defined as the sensor type
(not DHT22). Inside the setup routine, the serial port is initialized to 9600 Baud and the
DHT11 is initialized. The remainder of the program is executed inside the main program
loop. Here, the humidity and temperature are read from the sensor and are then sent to
the serial port. This process is repeated after 5 seconds.
#include <DHT.h>
#define DHTPin 3 // DHT11 pin
#define DHTType DHT11 // DHT11 type
DHT dht(DHTPin, DHTType); // Initialize
void setup()
{
Serial.begin(9600); // Start serial
dht.begin(); // Initialzie DHT11
● 254
Chapter 13 • Node-RED with Arduino Uno
void loop()
{
Hum = dht.readHumidity(); // Get humidity
Temp= dht.readTemperature(); // Get temperature
Humidity = String(Hum); // To string
Temperature = String(Temp); // To string
Serial.print(Humidity); // Send to serial port
Serial.print(","); // Insert comma
Serial.println(Temperature); // Send to serial port
delay(5000); //5 seconds delay
}
Figure 13.18 Arduino Uno program
Node-RED flow program: Re-start your Raspberry Pi, and then start Node-RED running
on your Raspberry Pi. Start the Dashboard by entering (enter the IP address of your own
Raspberry Pi) on your PC:
192.168.1.202:1880
Figure 13.19 shows the flow program which consists of 4 nodes: a serial in node to read the
temperature and humidity data from the Arduino, a function node to format the received
data, two gauges to display the temperature and the humidity.
• Create a serial in node with the configuration shown in Figure 13.20. Notice
that the Serial Port name is set to /dev/ttyACM0, which is device name of the
Raspberry Pi USB port.
● 255
Programming with Node-RED
• Create a function node with two outputs and enter the following statements (or,
use the split(",") function to extract the humidity and the temperature:
• Create two gauge nodes. For the humidity, node set the Label to Humidity, min
and max values to 0 and 100, and the Units to % respectively. For the temper-
ature, node set the Label to Temperature, min and max values to 0 and 30,
and Units to C
• Join all the nodes, click Deploy, and start the Dashboard by entering your own
IP address:
192.168.1.202:1880/ui/
• You should see the humidity and temperature displayed as shown in Figure 13.21
13 .8 Summary
In this chapter, we have learned how to use Node-RED with Arduino Uno, and several pro-
jects are given on this topic.
In the next chapter, we will look at how to use Node-RED with ESP32 processors.
● 256
Chapter 14 • Using the ESP32 DevkitC with Node-RED
14 .1 Overview
ESP32 is one of the popular microcontrollers used currently by students, practicing elec-
tronics engineers, hobbyists, and many other people interested in microcontroller-based
embedded system design. In this chapter, we will be learning how to use Node-RED with
ESP32 microcontrollers. In this chapter, we will use the ESP32 DevKitC development board.
It is assumed that the readers are familiar with the ESP32 processor and the ESP32 DevKitC
development board and have used it in at least one project. In the project in this chapter,
the ESP32 processor is programmed using the Arduino IDE. It is assumed that the Arduino
IDE is loaded with the ESP32 Dev Module software. If this is not the case, then you should
load this software to your Arduino IDE. The steps on installing the ESP32 support to the
Arduino IDE on a Windows PC are given in this section. If you have already installed ESP32
on Arduino IDE then you must delete the Espressif folder from your Arduino directory
before re-installing it.
• Download and install the latest version of Arduino IDE from the following web
site:
https://www.arduino.cc/en/Main/Software
• Open your Arduino IDE and click File -> Preferences to open the Preferences
window. Locate text box Additional Board Manager URLs at the bottom of
the window and enter the following text as shown in Figure 14.1. If the text box
contains another URL, add the new URL after separating it with a comma:
https://dl.espressif.com/dl/package_esp32_index.json
• Click OK
● 257
Programming with Node-RED
• Click Tools -> Board -> Board Managers window and search for ESP32 as
shown in Figure 14.2
• Click the Install button. You should see the Installed message as shown in Fig-
ure 14.3. Close the window.
• If the software is installed correctly, then you should see the ESP32 Dev Module
which is the board we will be using with our ESP32 DevKitC. Select Tools ->
Board ->ESP32 Dev Module as shown in Figure 14.4.
As a reminder, Figure 14.5 shows the pin configuration of the ESP32 DevKitC development
board. Interested readers can get a large amount of data on the ESP32 processor from the
Internet:
● 258
Chapter 14 • Using the ESP32 DevkitC with Node-RED
Description: This is a very simple project. In this project, an LED is connected to one of
the I/O ports of the ESP32 DevKitC through a current limiting resistor. The LED is turned
ON or OFF by clicking inject buttons in Node-RED.
Aim: The aim of this project is to show how the ESP32 DevKitC input/output ports can be
controlled from a Raspberry Pi which is programmed using Node-RED.
Block diagram: The block diagram of the project is shown in Figure 14.7.
● 259
Programming with Node-RED
Circuit diagram: Figure 14.8 shows the circuit diagram of the project. The LED is con-
nected to GPIO 21 of the ESP32 DevKitC. Serial port output TXD (GPIO 14, physical pin 8)
of the Raspberry Pi is connected to GPIO 23 of the ESP32 DevKitC. The ESP32 DevKitC has
3 UART pins as follows:
#include "HardwareSerial.h"
#define RXD 23
#define TXD 22
HardwareSerial Ser(1);
String buffer;
#define LED 21
● 260
Chapter 14 • Using the ESP32 DevkitC with Node-RED
void setup()
{
pinMode(LED, OUTPUT);
Ser.begin(9600, SERIAL_8N1, RXD, TXD);
}
void loop()
{
while(Ser.available() > 0)
{
buffer = Ser.readStringUntil('#');
if(buffer[0] == 'O' && buffer[1] == 'N')
digitalWrite(LED, HIGH);
else if(buffer[0] == 'O' && buffer[1] == 'F' && buffer[2] == 'F')
digitalWrite(LED, LOW);
}
}
Figure 14.9 ESP32 DevKitC program listing
Click Sketch -> Compiler/Verify to compile the program. After a successful compilation,
you must press the Boot button on ESP32 DevKitC (the button at the bottom right-hand
side) and keep it pressed and click Sketch -> Upload. When the uploading is complete,
release the Boot button and press the EN button to reset and start the program running
on your ESP32 DevKitC.
Node-RED flow program: Figure 14.10 shows the flow program which consists of just
3 nodes: two inject nodes to send the ON# or OFF# commands to the serial port, and a
serial out port to send the commands to the ESP32 DevKitC. You should disable the console
serial port (/dev/ttyS0) as described in Chapter 11 so that you can use the Raspberry Pi
serial port.
• Create two inject nodes, set the Payload to ON# in one of them, and to OFF#
in the other one.
● 261
Programming with Node-RED
• Build the circuit as shown in Figure 14.8. Click the button of the inject node
ON#, the LED should turn ON. Click the button of the inject node OFF#, the LED
should turn OFF.
14 .4 Summary
In this chapter, we have learned how to connect the ESP32 DevKitC to Raspberry Pi using
the serial link at 9600 Baud. Node-RED was started on Raspberry Pi. By sending commands
from Raspberry Pi to the ESP32 DevKitC we can easily control the LED. Interested readers
can develop more complex ESP32 processor-based projects using the technique described
in this chapter.
In the next chapter, we will be learning how to use Amazon Alexa in Node-RED based pro-
jects.
● 262
Chapter 15 • Using Amazon Alexa in Node-RED projects
15 .1 Overview
Alexa is a sound-based virtual assistant device developed by Amazon in 2014 and first
used in Amazon Echo and Amazon Echo Dot. Alexa interacts with the user through sound
and it can obey the commands given by a speaker. For example, Alexa can play a piece of
required music, it can provide weather reports, ask questions, give traffic reports, give the
current news, give recipes, translate words to other languages, and many more. Alexa can
also be used to control a device through sound commands and therefore it can be used in
home automation. The device is activated by giving the wake-word Alexa. The user can
then communicate with Alexa. Alexa is connected to the local Wi-Fi router of the user and
it gets the answers to the user questions from the Amazon cloud. The latest model of Alexa
at the time of writing this book was the 3rd generation devices. Figure 15.1 shows the 3rd
Gen Alexa Dot device.
In this chapter, we will be using Node-RED with Alexa and Raspberry Pi and learn how we
can control the GPIO ports of Raspberry Pi by giving spoken commands to Alexa.
Description: In this project, an LED is connected to one of the Raspberry Pi GPIO ports.
The LED is turned ON and OFF by giving spoken commands to Alexa.
Aim: The aim of this project is to show how Alexa can be used with Node-RED in a Rasp-
berry Pi project to control a device remotely.
Block diagram: The block diagram of the project is shown in Figure 15.2.
● 263
Programming with Node-RED
Circuit diagram: In this project, a small LED is connected to port pin GPIO 2 of the
Raspberry Pi through a 470 Ohm current limiting resistor.
Node-RED flow program: Before developing our flow program, we have to install the
Alexa node to our Node Palette. Because the Alexa nodes listen on port 80, it is important
that you start your Node-RED on the Raspberry Pi with a super user command. i,e,
• You should see two new nodes called amazon echo hub and amazon echo
device added to your Node Palette
If you find that your Raspberry Pi GPIO nodes are not listed in the Nodes Palette, you can
re-install them using the following steps:
Figure 15.3 shows the flow program which consists of just 4 nodes: an amazon echo hub
node, an amazon echo device node, a function node, and a rpi gpio out node.
• Create an amazon echo hub node and make sure that the Port is set to 80 and
Process Input is set to No.
• Create an amazon echo device node and set the Name to Bedroom Lights (this
is the name that Alexa will know the LED. You should choose your own name
here).
● 264
Chapter 15 • Using Amazon Alexa in Node-RED projects
• Create a function node and name it as ON/OFF. Enter the following statements
inside this node. This node outputs 1 if the message coming from Alexa is on, or
it outputs 0 is the message coming from Alexa is off:
if(msg.payload == "on")
out = 1;
else
if(msg.payload == "off")
out = 0;
msg.payload = out;
return msg;
• Create an rpi gpio out node and name it as LED. Set the Pin to GPIO 2, Type
digital output, and Initialize the pin state to logic 0.
To test the project, ask Alexa "Alexa, discover devices". After a minute or so Alexa will
confirm that it has detected your device (Bedroom Lights in this project).
To turn the LED ON, ask Alexa "Alexa, turn on bedroom lights"
To turn the LED OFF, ask Alexa "Alexa, turn off bedroom lights"
The nodes can be used to turn on/off a device or to dim a light and it is supported by the
1st, 2nd and 3rd generation Alexa devices. Notice that we can add as many amazon echo
devices as we wish to our design for the control of various equipment. An example project
is given below where we have added a buzzer to our design.
Description: In this project, an LED and a buzzer are connected to the Raspberry Pi GPIO
ports. The LED and the buzzer are turned ON and OFF by giving spoken commands to Alexa.
Aim: The aim of this project is to show how multiple devices can be controlled by Alexa.
Block diagram: The block diagram of the project is shown in Figure 15.4.
● 265
Programming with Node-RED
Circuit diagram: The circuit diagram of the project is shown in Figure 15.5, where the LED
is connected to GPIO 2 and the buzzer is connected to GPIO 3.
Node-RED flow program: Figure 15.6 shows the flow program. Notice that we have
added another amazon echo device node to our program and named it as Buzzer. This
second node drives another function node which has exactly the same content as the one
in Figure 15.3. The second rpi gpio out node is used to drive the buzzer where its Pin is
set to GPIO 3 and its Type is digital output as before. Because the new amazon echo device
is not known to Alexa, we have to ask Alexa to discover nodes again: "Alexa, discover
devices". After this, we can control the LED and the buzzer by asking the Alexa:
To turn the LED ON, ask Alexa "Alexa, turn on bedroom lights"
To turn the LED OFF, ask Alexa "Alexa, turn off bedroom lights"
To turn the Buzzer OFF, ask Alexa "Alexa, turn off buzzer"
● 266
Chapter 15 • Using Amazon Alexa in Node-RED projects
Notice that we could have used another Alexa node called node-red-contrib-alexa-
home-skill for more sophisticated Alexa based control tasks. This node, called the Alexa
Home node, requires the user to be registered and have an account before using it. Alexa
Home node supports the following commands (Interested readers can get much more in-
formation from the web link: https://alexa-node-red.bm.hardill.me.uk/docs):
• TurnOnRequest
• TurnOffRequest
• SetPercentageRequest
• IncrementPercentageRequest
• DecrementPercentageRequest
• SetTargetTemperatureRequest
• IncrementTargetTemperatureRequest
• DecrementTargetTemperatureRequest
• GetTemperatureReadingRequest
• GetTargetTemperatureRequest
• SetLockState
• GetLockState
• SetColorRequest
• SetColorTemperatureRequest
Modified program
In the previous project, the LED is turned ON and OFF by sending spoken commands to
Alexa. In some applications we may want to turn the LED ON by sensing a command, then
we may want the LED to turn OFF automatically after some time. For example, before en-
tering a room we may ask Alexa to turn the light ON and after 20 seconds we may want
the light to turn OFF automatically. This can be done easily by adding a trigger node to
Figure 15.3. In the example flow program shown in Figure 15.7, the LED is turned OFF after
15 seconds. The trigger node is configured to send 1 for 15 seconds and then it sends 0.
Figure 15.8 shows the trigger node contents. Notice that the output of the trigger node
is reset if msg.payload is equal to 0 (i.e. if Alexa is asked to turn the Bedroom Lights OFF).
● 267
Programming with Node-RED
15 .4 Summary
In this chapter, we have learned how to use Amazon Alexa with Node-RED to control
equipment connected to a Raspberry Pi. Although the projects in this chapter use the Rasp-
berry Pi, there are no reasons why Arduino or the ESP32 DevKitC cannot be used in Alexa
based projects. As described in the earlier chapters, we can connect Arduino or the ESP32
DevKitC to Raspberry Pi and then control their GPIO ports via the Raspberry Pi by sending
commands via Alexa.
In the next chapter, we will be learning how to access Node-RED on Raspberry Pi from
anywhere on earth.
● 268
Chapter 16 • Accessing Raspberry Pi Node-RED from anywhere
16 .1 Overview
In all of the previous projects, we have been accessing Raspberry Pi Node-RED over a Wi-Fi
link through our Wi-Fi router. There are many cases where we may want to access Node-
RED from anywhere on earth, so that for example appliances in our house can be controlled
and monitored remotely from anywhere on earth. In this chapter, we will learn how this
can be done.
16 .2 The ngrok
We will be using a free service called ngrok in order to create a tunnel to our Raspberry
Pi so that we can access it from anywhere in the world. First of all, we have to change our
default port number from 80 to something else, e.g. 1880 since for some reason ngrok
does not work with port number 80.
• Click Auth link at the left-hand side to get your unique Tunnel token as shown in
Figure 16.2. In this example author's tunnel token is (this is modified for security
reasons): gqudoMhDuJeXnLqVGHqv7jyUTtbYpnQzTk3Eb
● 269
Programming with Node-RED
• Copy the software to a folder on your Raspberry Pi (e.g. /home/pi). You can if
you wish, download the software to your PC and then use the WinSCP utility to
copy it to your Raspberry Pi. At the time of writing this book, the software was
named: ngrok-stable-linux-arm .zip
• Unzip the software on your Raspberry Pi and save the token in file ngrok .yml by
entering the command shown in Figure 16.3
• You will be presented with a screen similar to the one shown in Figure 16.4. Here
we want the part that starts with Forwarding and https, as this is the address
we will be entering into our web browser, i.e.
https://2353edf8.ngrok.io
• Start Node-RED on your Raspberry Pi manually (or automatically during the re-
boot time. This is shown in the next section of this Chapter)
● 270
Chapter 16 • Accessing Raspberry Pi Node-RED from anywhere
• You can now access Node-RED remotely by entering the following address into
your web browser. Note that you must not close the ngrok screen (Figure 16.4)
while accessing Node-RED remotely:
https://2353edf8.ngrok.io
16 .4 Summary
In this chapter, we have learned how to access Node-RED from anywhere on Earth.
In the next chapter, we will be looking at how Bluetooth communication can be used with
Node-RED based projects on Raspberry Pi.
● 271
Programming with Node-RED
17 .1 Overview
Bluetooth is a wireless communications technology used over short distances. Although it
was originally developed as a wireless alternative to RS232 based serial communication, it
is widely used nowadays to transfer data between two Bluetooth compatible devices. Most
smart mobile phones have built-in Bluetooth hardware and they can be used to transfer data,
e.g. pictures to other PCs and to other compatible mobile phones. Bluetooth operates in the
2.4 to 2.485 GHz frequency range and is managed by the Bluetooth Special Interest Group.
In this chapter, we will learn how to use Bluetooth with Node-RED on a Raspberry Pi. Before
using Bluetooth with Node-RED we have to install it in the Node Palette. The steps are:
• Start Node-RED
• You should see two new nodes named bt serial in and bt serial out added to
your Node Palette
An example project is given in the next section to show how the Bluetooth node can be
used.
Description: In this project, an LED and a buzzer are connected to the Raspberry Pi GPIO
ports. The LED and the buzzer are turned ON and OFF by sending commands from a smart
mobile phone via the Bluetooth interface.
Aim: The aim of this project is to show how Bluetooth can be used with Node-RED on a
Raspberry Pi.
Block diagram: The block diagram of the project is shown in Figure 17.1.
● 272
Chapter 17 • Using Bluetooth with Node-RED
Circuit diagram: The circuit diagram of the project is as shown in Figure 15.5, where the
LED is connected to GPIO 2 and the buzzer is connected to GPIO 3 of Raspberry Pi.
Node-RED flow program: Figure 17.2 shows the flow program of the project which con-
sists of 4 nodes: a bt serial in to receive data from the Bluetooth device, a function node
to format the data for the GPIO ports, and two rpi gpio out nodes to control the LED and
the buzzer.
• Click Settings
• Click System
• Click Status
• Scroll down until you see the Bluetooth address of your Android mobile phone
(see Figure 17.4). The MAC address of the mobile phone in this project was
B4:CD:27:15:68:7B
● 273
Programming with Node-RED
• Create a function node named ON/OFF and enter the following data into this
node. The data returned by the bt serial in node is in binary and it is converted
into string and stored in variable T. If the command is LON then output 1 is set
to 1, if the command is LOFF then output 1 is set to 0. Similarly, output 2 is set
to 1 and 0 if the commands are BON and BOFF respectively:
if(T == "BON")
out2 = {payload: 1};
else if(T == "BOFF")
● 274
Chapter 17 • Using Bluetooth with Node-RED
• Create two rpi gpio out nodes named LED and Buzzer. Set the Pin to GPIO
2 for the LED and to GPIO 3 for the Buzzer. Set the Type to digital output, and
Initialize the pin to 0 for both nodes.
We can send data to our Raspberry Pi using a Bluetooth app on our Android mobile phone.
There are many Bluetooth apps in the Play Store. The one used in this project is called
Bluetooth Terminal by Qwerty as shown in Figure 17.5. Install this app on your mobile
phone.
In order to be able to access the Raspberry Pi from a mobile phone app, make the following
changes to your Raspberry Pi from the command line:
• Add –C at the end of the ExecStart= line. Also add another line after the Exec-
Start line. The final two lines should look like:
ExecStart=/usr/lib/bluetooth/bluetoothd -C
ExecStartPost=/usr/bin/sdptool add SP
Before sending a command to our Raspberry Pi we need to know the Bluetooth MAC ad-
dress of our Raspberry Pi. This is found by entering the following in the command mode
(your device name will probably be different):
● 275
Programming with Node-RED
pi@raspberrypi:~ $ bluetoothctl
[MyDevice]# show
You will find the Bluetooth MAC address listed at the top of the list. Enter the following
commands to make the Bluetooth discoverable on your Raspberry Pi:
[MyDevice]# agent on
[MyDevice]# discoverable on
[MyDevice]# exit
Now, make sure that Node-RED is running. Start the Bluetooth apps on your mobile phone.
And click the 3 dots at the top right-hand side. Click Make discoverable, then click Con-
nect a device – Insecure, select the Raspberry Pi, and wait until the message connect-
ed: raspberrypi is displayed. You will also see that the message connected is displayed
under node bt serial in your flow program. You are now ready to send commands from
your mobile phone to the Raspberry Pi over the Bluetooth link. Send the following com-
mands (see Figure 17.6):
In this project, we have received commands from the mobile phone over a Bluetooth link.
You may like to try and use the bt serial out node to send commands from the Raspberry
Pi back to the mobile phone using the Bluetooth link.
17 .3 Summary
In this chapter, we have learned how to communicate using Bluetooth Node-RED nodes.
We have developed a project where an LED connected to Raspberry Pi can be controlled
by sending commands from a mobile phone using the Bluetooth link. It is possible to use
an Arduino development board or an ESP32 DevKitC together with a Raspberry Pi in order
● 276
Chapter 17 • Using Bluetooth with Node-RED
to control devices connected to Arduino or the ESP32 DevKitC using Bluetooth connectivity
with Node-RED.
● 277
Programming with Node-RED
18 .1 Overview
MQTT stands for Message Queuing Telemetry Transport. It is a message protocol that was
created for machine-to-machine (M2M) communication, and is based on publishing and
subscribing. MQTT is particularly very useful when it comes to sending data and controlling
information with low bandwidth and high response times. This protocol is especially worth
considering when it is required to send data to actuators and retrieve data from sensors.
MQTT was first developed by IBM in 1999 mainly for satellite communication, and since
then has become the standard communications protocol for the Internet of Things (IoT)
applications. MQTT uses your existing home network to send messages to your IoT devices
and receive a response from them. The official website of MQTT is: http://mqtt.org
MQTT works on top of the TCP/IP protocol and it is faster than sending HTTP requests since
a message can be as small as 2 bytes and there are no headers which is the case with
the HTTP. Additionally, in MQTT messages are distributed automatically to the interested
clients.
In Figure 18.1, the temperature sensor publishes (or sends) its measured value to the bro-
ker, who accepts and saves the data. The broker then sends this measured value to other
devices that have subscribed to receive this data.
• Publisher
• Subscriber
• Messages
• Topics
• Broker
● 278
Chapter 18 • Node-RED and MQTT
Publisher: The publisher is the node that sends data or the message on a topic. For exam-
ple, a publisher can be a sensor node that sends ambient temperature values.
Messages: Messages are the information exchanged in the MQTT network. A message
can be data or a command. For example, a message can be the temperature value, or a
command to turn ON a switch.
Topics: Topics are important concepts of MQTT. These are the ways we register interest
for incoming messages, or how we specify where we want to publish the message. i.e. the
message exchange takes place via the topics. Topics in MQTT are represented with char-
acter strings, separated by a forward slash. Each forward slash indicates a topic level. An
example is shown below which creates a topic for an LED in your kitchen:
home/kitchen/led
In the above example, home, kitchen, and led are the topic levels and they are separated
by the topic level separators. The topics are case sensitive and for example, Home/kitchen/
led is not the same as above.
Single level wildcards: We can use wildcards in topics so that several sensors can be
queried at the same time. A "+" sign is used to identify a single level wildcard. Example is
given below:
Multi-level wildcards: We can also use a multi-level wildcard, represented by the sign
"#". This must always be used at the end of a topic. An example is given below:
Broker: the broker receives all messages, filters them and decides who are interested in
them, and then sends the message to all subscribed clients
Figure 18.2 illustrates the operation of MQTT, which can be summarised as follows:
● 279
Programming with Node-RED
• The processor (and sensor) publishes ON and OFF messages on-topic home/
kitchen/led
To test the Mosquitto installation, enter the command mosquitto –v as shown in Figure
18.3. This command displays the version of the Mosquitto running on your system (Don't
worry about the Error: Address already in use).
Subscribe to the topic "TestTopic" by entering the following command. Mosquitto_sub tells
that we want to subscribe to a topic, and the name following –t is the topic name. Now,
every time we publish (i.e. send message) to TestTopic, the message will appear in the
window:
● 280
Chapter 18 • Node-RED and MQTT
Now, because the terminal is listening for messages from our broker, we have to open an-
other window so that we can publish messages. After opening another window, enter the
following command to publish to TestTopic:
Here, the topic name is after –t, and the message is after –m. After hitting the Enter we will
see the message appear on our subscriber terminal as shown in Figure 18.4.
• A Raspberry Pi
• Node-RED and MQTT
• An Arduino, ESP32, ESP8266, or any other compatible microcontroller
Figure 18.5 shows the basic MQTT system setup. The sensors, actuators, relays, switches,
lamps, LEDs, etc are connected to the system via an Arduino, ESP32, ESP8266, or any
other compatible processor.
Node-RED offers two MQTT nodes (mqtt in and mqtt out) which can be found in the net-
work palette as shown in Figure 18.6.
● 281
Programming with Node-RED
We can send a message to the MQTT broker using an inject node as shown in Figure 18.7.
Notice that the small green box under the mqtt out node indicates that the connection
from the mqtt out node to the broker has been established. In Figure 18.7 the topic is
set to TestTopic, and the inject node Payload is set to message Hello From Me!!. This
message is displayed on the MQTT subscriber as shown in the figure. In this flow program,
the mqtt out node Server was set to localhost and the Port number was set to 1883
(network ports 1883 and 8883 are reserved by default):
Notice that, by using different topics we can send (publish) different messages and these
messages will be received by the subscribers having the same topics.
A very simple example is given below which illustrates how an LED can be controlled using
MQTT.
Description: In this project, we will learn how an LED can be controlled using MQTT.
Aim: The aim of this project is to show how MQTT can be used in a very simple project.
Circuit diagram: In this project, an LED is connected to Raspberry Pi port pin GPIO 2
through a current limiting resistor.
Node-RED flow program: Figure 18.8 shows the flow program of the project. Basically,
two inject nodes are used with the Payloads set to 1 and 0 respectively. When for example
the button of the upper inject node is clicked then a 1 is sent to the broker via the mqtt
out node. The mqtt in node in the lower flow is given the same topic name as the mqtt
out node, and this node drives the rpi gpio out node which controls the LED accordingly.
The Raspberry Pi console displays the data received by the GPIO port since it is subscribed
to the same topic as shown in Figure 18.9.
● 282
Chapter 18 • Node-RED and MQTT
In more complex and real projects instead of using inject nodes, we usually have proces-
sors with sensors connected to their inputs. The data from these sensors are sent to the
broker via the mqtt out node. The mqtt nodes then receive and process this data (e.g.
display or activate an actuator).
In the next sections, we will learn how to use the ESP8266 NodeMCU development board
as the client in an MQTT application.
There are many versions of the ESP8266 chip, available as modules on small boards with
different functionalities and different input/output capacities. The basic specifications of the
ESP8266 chip are summarized below:
● 283
Programming with Node-RED
NodeMCU (LoLin) is a small microcontroller development board based on the ESP8266 pro-
cessor. It was first manufactured in 2014 and currently, it is one of the most popular Wi-Fi
development kits based on the ESP8266 chip and it incorporates an on-board USB-to-TTL
adapter, micro USB socket, a large number of GPIOs, PWM, I2C, ADC, +3.3V voltage regu-
lator, UART and so on. Figure 18.10 shows the pin configuration of the NodeMCU.
NodeMCU can be programmed using the Arduino IDE. The steps to install the necessary
software on the Arduino IDE are given below:
• Click File -> Preferences and enter the following at the bottom of the screen
as shown in Figure 18.11. If you already have another URL there, separate them
with a comma, and click OK
http://arduino.esp8266.com/stable/package_esp8266com_index.json
● 284
Chapter 18 • Node-RED and MQTT
• Enter esp8266 and press the install button for ESP8266 by ESP8266 Com-
munity (see Figure 18.12)
• After a successful installation, you should see the Installed message as in Figure
18.13. Close the screen.
Detailed programming of the ESP8266 processor is beyond the scope of this book. A simple
project is given in the next section just to remind the users of how the ESP8266 can be
programmed using the Arduino IDE. It is assumed that the readers are familiar with using
the Arduino IDE.
Description: This is a very simple project where an LED is connected to one of the GPIO
ports of the NodeMCU and the LED is flashed every second.
Aim: The aim of this project is to remind the users of how the NodeMCU can be pro-
grammed using the Arduino IDE.
Circuit diagram: Figure 18.14 shows the circuit diagram of the project. The LED is con-
nected to GPIO port 16 of the NodeMCU.
● 285
Programming with Node-RED
Program Listing: The program listing (program: esp8266led) is shown in Figure 18.15.
The steps to start programming are as follows:
Build the circuit and connect the NodeMCU to your PC through a mini USB cable
• Select the COM port and click Tools -> Port n where n is the port number
void loop()
{
digitalWrite(LED, HIGH); // LED ON
delay(1000); // Wait one second
digitalWrite(LED, LOW); // LED OFF
delay(1000); // Wait one second
}
• Click Sketch -> Verify/Compiler and make sure there are no compilation errors
• Click Sketch -> Upload and wait until you see the message Done uploading.
● 286
Chapter 18 • Node-RED and MQTT
https://github.com/knolleary/pubsubclient/archive/master.zip
• Download the above .zip file (Click Clone or Download and select Download
ZIP). The file is named: pubsubclient-master .zip
• Select File -> Examples -> PubSubClient and you should see a number of
mqtt based example files listed
You should make Mosquitto auto-start on boot by entering the following command:
A simple project is given below to illustrate how MQTT can be used with the ESP8266 No-
deMCU.
● 287
Programming with Node-RED
Description: This is a very simple project where an LED is connected to one of the GPIO
ports of the Raspberry Pi. Additionally, a push-button switch is connected to the ESP8266
NodeMCU. The LED is toggled when the button is pressed.
Aim: The aim of this project is to show how MQTT can be used with the ESP8266 NodeMCU.
Here, the NodeMCU is the client (publisher) and the Raspberry Pi is the subscriber which
receives the messages.
Block diagram: Figure 18.17 shows the block diagram of the project.
Circuit diagram: The circuit diagram of the project is shown in Figure 18.18. The button
is connected to port pin GPIO 2 of the ESP8266 NodeMCU. Similarly, the LED is connected
to port pin GPIO 2 of the Raspberry Pi.
ESP8266 NodeMCU program listing: Figure 18.19 shows the program listing (program:
mqttesp8266). NodeMCU uses the Wi-Fi link to communicate with the Raspberry Pi in
MQTT based applications. Therefore, we need to know the SSID name and the password
of our Wi-Fi router, and the IP address of our Raspberry Pi. In this example we have the
following settings (you will have to enter your own settings):
● 288
Chapter 18 • Node-RED and MQTT
SSID: BTHomeSpot-XNH
Password: 49350baeb
Raspberry Pi IP address: 192.168.1.202
We have to enter these values into our program. Notice that the button is connected to
port pin GPIO 2:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
WiFiClient wclient;
PubSubClient client(wclient);
Inside the setup routine, we will initialize the Arduino IDE Serial Monitor at 115200 Baud so
that we can see trace the execution of the code easily. We will also have to configure port
pin GPIO 2 where the switch is connected to as input and enable the pull-up resistor, and
enable the Wi-Fi on our ESP8266 NodeMCU:
//
// The setup routine
//
void setup()
{
Serial.begin(115200);
pinMode(Button, INPUT);
digitalWrite(Button, HIGH);
delay(100);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
The Wi-Fi is setup inside the setup routine as follows (readers who used the ESP8266 be-
fore should be familiar with the following code):
● 289
Programming with Node-RED
//
// Connect to local Wi-Fi router
//
void setup_wifi()
{
The main program loop attempts to reconnect to the client by calling function reconnect if
the connection is lost, and reads the status of the button to check if it is pressed.
//
// Reconnect to client if the connection is lost
//
void reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
if (client.connect(ID))
{
Serial.println("Connected");
Serial.print("Publishing to: ");
Serial.println(Topic);
Serial.println('\n');
}
else
{
Serial.println(" Trying to connect again in 5 seconds");
delay(5000);
}
}
● 290
Chapter 18 • Node-RED and MQTT
void loop()
{
if (!client.connected()) reconnect();
client.loop();
Node-RED flow program: Figure 18.20 shows the flow program for the Raspberry Pi
which consists of just 3 nodes: an mqtt in node, a function node, and a rpi gpio out
node.
• Create an mqtt in node and set its Server to localhost, Port to 1883, and the
Topic to kitchen/light/
● 291
Programming with Node-RED
• Create a function node names ON/OFF and enter the following statements in-
side this function:
if(msg.payload == "on")
msg.payload = 1;
else if(msg.payload == "off")
msg.payload = 0;
return msg;
• Create a rpi gpio out node and set the Pin to GPIO 2, Type to digital output,
and Initialize to 0.
Testing
The project can be tested as follows:
• Power on the ESP8266 NodeMCU and open the Serial Monitor and set its Baud
rate to 115200.
• You should see messages on the Serial Monitor saying that the NodeMCU is con-
nected to your Wi-Fi (see Figure 18.21) and that it can publish to MQTT with the
topic kitchen/light/
• Press the button. You should see the following message displayed on the Serial
Monitor (see Figure 18.22). At the same time the LED will turn ON:
kitchen/light/ is ON
• Release the button and press again. You should see the following message dis-
played on the Serial Monitor. At the same time the LED will turn OFF:
kitchen/light/ is OFF
● 292
Chapter 18 • Node-RED and MQTT
• If you subscribe your Raspberry Pi console to topic kitchen/light/ then you should
see the messages displayed there as well (see Figure 18.23)
Description: This project is similar to the previous one but here the LED is connected to
the NodeMCU and the button is connected to the Raspberry Pi. As before, the LED is toggled
when the button is pressed.
Aim: The aim of this project is to show how the client (NodeMCU in this project) can be
configured as a subscriber so that it can receive messages using MQTT. Raspberry Pi is a
publisher in this project.
Block diagram: Figure 18.24 shows the block diagram of the project.
● 293
Programming with Node-RED
Circuit diagram: The circuit diagram of the project is shown in Figure 18.25. The button
is connected to port pin GPIO 2 of the Raspberry Pi. Similarly, the LED is connected to port
pin GPIO 2 of the NodeMCU through a current limiting resistor.
ESP8266 NodeMCU program listing: Figure 18.26 shows the program listing (program:
esp8266mqtt). The program is very similar to the one given in Figure 18.19 except the
following changes:
The statement client.subscribe(Topic) is added to the setup routine so that the NodeMCU is
configured as an MQTT subscriber.
The main program loop has been modified so that the loop only re-connects if the connec-
tion is lost.
A new function called callback is added to the program. This function is called every time a
message is received by the NodeMCU. At the beginning of the function, the message New
message arrived is displayed together with the MQTT topic name. The function then dis-
plays the received message. Character array payload[0] stores the first character of the
received message which is either '1' or '0' in this project. If '1' is received then the LED is
turned ON, otherwise, the LED is turned OFF. The contents of this function are as follows.:
● 294
Chapter 18 • Node-RED and MQTT
}
}
/******************************************************************
* ESP8266 NodeMCU MQTT PROGRAM
* ============================
* In this program a push-button switch is conencted to port
* GPIO 2 of the Raspberry Pi. Similarly, an LED is connected
* to port GPIO 2 of the NodeMCU. Pressing the button toggles
* the LED.
*
* Author: Dogan Ibrahim
* File : esp8266mqtt
* Date : December 2020
*
******************************************************************/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
WiFiClient wclient;
PubSubClient client(wclient);
//
// Connect to local Wi-Fi router. This function connects the
// NodeMCU to the local WiFi router. Because the Serial Monitor
// is enabled, we can see the progress in the monitor
//
void setup_wifi()
{
Serial.print("\nESP32 NodeMCU connecting to: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
● 295
Programming with Node-RED
//
// This is the setup routine. Here the Serial Monitor is enabled,
// Button is configured as digital input, and the WiFi is setup.
// Notice that the MQTT server (Raspberry Pi) operate on port 1883
// The callback routine is called callback
//
void setup()
{
Serial.begin(115200); // Enable Serial Monitor
pinMode(LED, OUTPUT); // Button is input
delay(100); // Small delay
setup_wifi(); // Setup WiFi
client.setServer(mqtt_server, 1883); // Define client
client.setCallback(callback);
}
//
// Reconnect to client if the connection is lost
//
void reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
if (client.connect(ID))
{
Serial.println("connected");
Serial.print("Publishing to: ");
Serial.println(Topic);
Serial.println('\n');
client.subscribe(Topic);
}
else
{
Serial.println(" Trying to connect again in 5 seconds");
delay(5000);
}
}
}
//
// This is the callback routine. The program jumps here when a message
● 296
Chapter 18 • Node-RED and MQTT
//
// Main program loop. If client gets disconnected, re-connect
//
void loop()
{
if (!client.connected()) reconnect();
client.loop();
}
Figure 18.26 esp8266mqtt program listing
Node-RED flow program: Figure 18.27 shows the flow program for the Raspberry Pi
which consists of just 3 nodes: a rpi gpio in node to read the button status, a function
node, and an mqtt out
● 297
Programming with Node-RED
• Create a rpi gpio in node to read the button status and set the Pin to GPIO 2
and Resistor to pullup
• Create a function node named ON/OFF and enter the following statements in-
side this function. The function returns "1" if the button is pressed (msg.payload
= "0"), and "0" if the button is not pressed:
if(msg.payload == "0")
msg.payload = "1";
else
msg.payload = "0";
return msg;
• Create an mqtt out node and set its Server to localhost, Port to 1883, and the
Topic to kitchen/light/
Testing
The project can be tested as follows:
• Power on the ESP8266 NodeMCU and open the Serial Monitor and set its Baud
rate to 115200.
• You should see messages on the Serial Monitor saying that the NodeMCU is con-
nected to your Wi-Fi and that it can publish to MQTT with the topic kitchen/light/
• Press the button. You should see the following message displayed on the Serial
Monitor (see Figure 18.28). At the same time the LED will turn ON:
• Release the button. Now, you should see the following message displayed on the
Serial Monitor. At the same time the LED will turn OFF:
● 298
Chapter 18 • Node-RED and MQTT
If you publish from Raspberry Pi console to topic kitchen/light/ then you should see the LED
turning ON or OFF and the messages displayed on the Serial Monitor (see Figure 18.29)
18 .11 Summary
In this chapter, we have learned how to install and use MQTT with Node-RED. The projects
given in this Chapter are based on the ESP8266 NodeMCU development board. There are
no reasons why other development boards such as the ESP32 DevKitC cannot be used in
MQTT based applications. This is left as an exercise for the readers.
In the next chapter, we will be learning how to use Node-RED HTTP nodes in projects.
● 299
Programming with Node-RED
19 .1 Overview
The node-red palette includes nodes for HTTP request, HTTP response, and HTTP in. The
http request node is a core node that can be used for making http requests. Using this node
we can retrieve web pages from a website, send and receive JSON data to a website, make
API requests and so on. The following configuration is supported by the node:
HTTP is a text-based request and response protocol which uses the client-server model of
communication. A request consists of a command, some optional headers, and optional
body content. Similarly, a response consists of a status code, optional headers, and op-
tional body content. A web browser may be the client that submits an HTTP request to the
server.
Whenever we enter a URL in the address box of a browser, this URL is translated into a re-
quest message. For example, the URL http://www.test.com/doc/index.html may be trans-
lated into a request of the following format:
Here, GET is the method and /doc/index .html is the path and HTTP/1 .1 is the protocol
version.
The response status code can have several values. Code 200 is the code for success.
In this section, we will learn how to use the http request node in Node-RED based projects.
http://example.com/hi/there?hand=wave
● 300
Chapter 19 • Using HTTP in Node-RED projects
this flow program, we have an inject node, an http request node with the Method is
set to GET and the URL is set as above. A debug node is used to display the output in the
Debug window. Figure 19.2 shows the output displayed.
Figure 19.2 Output in the Debug window (only part of the output is shown)
We can insert a html node inbetween the http request node and the debug node and set
its Selector to div to extract the div types, and its Output to display only the text content
of the elements, as a single message containing an array. The output is then shown in Fig-
ure 19.3 together with the flow program.
19 .3 Web server
A web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve web pag-
es to users in response to their requests. These requests are forwarded by HTTP clients.
● 301
Programming with Node-RED
By using the HTTP server/client pair we can control any device connected to a web server
processor over the web.
Figure 19.4 shows the structure of a web server/client setup. In this figure, Raspberry Pi is
the webserver processor and the PC (or a laptop, tablet or smart mobile phone) is the web
client. The device to be controlled is connected to the webserver processor. The operation
of the system is as follows:
• The web server is in the listen mode, listening for requests from the web client
• The web client makes a request to the web server by sending an HTTP request
• In response, the webserver sends an HTTP code to the web client which is acti-
vated by the web browser by the user on the web client and is shown as a form
on the web client screen.
• The user sends commands (e.g. ticks buttons on a web client form) and this
sends code to the webserver so that the webserver can carry out the required
operations.
A project is given in the next section to illustrate how a Node-RED based web server can
be used to control relays.
Aim: The aim of this project is to show how a web server application can be designed using
Node-RED on a Raspberry Pi.
● 302
Chapter 19 • Using HTTP in Node-RED projects
Background information: In this project, a 4-channel relay board (see Figure 19.5) from
Elegoo (www.elegoo.com) is used. This is an opto-coupled relay board having 4 inputs, one
for each channel. The relay inputs are at the bottom right-hand side of the board while the
relay outputs are located at the top side of the board. The middle position of each relay
is the common point, the connection to its left is the normally closed (NC) contact, while
the connection to the right is the normally open (NO) contact. The relay contacts support
AC250V at 10A and DC30V 10A. IN1, IN2, IN3, and IN4 are the active LOW inputs, which
means that a relay is activated when a logic LOW signal is applied to its input pin. Relay
contacts are normally closed (NC). Activating the relay changes the active contacts such
that the common pin and NC pin become the two relay contacts and at the same time the
LED at the input circuit of the relay board corresponding to the activated relay is turned
ON. The VCC can be connected to either +3.3V or to +5V. Jumper JD is used to select
the voltage for the relay. Because the current drawn by a relay can be in excess of
80mA, you must remove this jumper and connect an external power supply (e .g .
+5V) to pin JD-VCC.
Block diagram: Figure 19.6 shows the block diagram of the project.
● 303
Programming with Node-RED
Node-RED flow program: Figure 19.8 shows the flow program of the project which con-
sists of 8 nodes: a http in node to get the HTTP request, a template node to store the
HTML code, a http out node, a function node to format the data for the output, and 4 rpi
gpio out nodes to control the 4 relay inputs.
● 304
Chapter 19 • Using HTTP in Node-RED projects
• Create a http in node and configure as shown in Figure 19.9. Here, the URL is
named as /relay . The operation of the project is as follows: When the user en-
ters the URL 192 .168 .1 .202:1880/relay from a web browser, a GET request is
sent to the Raspberry Pi node http in. This node then activates node template
which displays a form on the user screen. This form contains buttons that the
user can click to activate/de-activate a chosen relay. When a button is clicked, a
command is received by node http in. This command is passed to node function
which extracts the appropriate part of the command and outputs code to activate
the correct rpio gpio out node, which in turn controls the relay connected to
that node.
• Create a template node and enter the HTML code shown in Figure 19.20 into this
node. At the beginning, the heading Node-RED RELAY CONTROL is displayed.
The next line displays the sub-heading Web Server Example With 4 Relays.
The remainder of the HTML code displays a form with the names of the relays as
RELAY1 ON and RELAY1 OFF to RELAY4 ON and RELAY4 OFF where the ON
states are displayed in green colour and the OFF states in red colour. The form
elements are buttons that can be clicked. One line of the code is shown below. In
this code, the button is named RELAY1 ON and it is green colour. Similar code is
repeated for all the relays.
When the GET request is received by node http in (i.e. when the user enters:
192.168.1.202:1880/relay), the form shown in Figure 19.21 is displayed on the
user screen.
● 305
Programming with Node-RED
• Create a function node named CONTROL having 4 outputs, and enter the fol-
lowing statements inside this node:
var var1 = null;
var var2 = null;
var var3 = null;
var var4 = null;
var T = msg.req.url;
switch (T)
{
case "/relay?RELAY1=ON":
var1 = {payload: 0};
break;
case "/relay?RELAY1=OFF":
var1 = {payload: 1};
break;
case "/relay?RELAY2=ON":
var2 = {payload: 0};
break;
case "/relay?RELAY2=OFF":
var2 = {payload: 1};
break;
case "/relay?RELAY3=ON":
var3 = {payload: 0};
break;
case "/relay?RELAY3=OFF":
var3 = {payload: 1};
break;
case "/relay?RELAY4=ON":
var4 = {payload: 0};
break;
case "/relay?RELAY4=OFF":
var4 = {payload: 1};
break;
}
return[var1, var2, var3, var4];
● 306
Chapter 19 • Using HTTP in Node-RED projects
When a button is clicked on the form, a command is sent to the web server in
addition to some other data. Here, we are only interested in the actual command
sent. Variable msg.req.url is loaded with the command received by node http in
when a button is clicked. The following are the commands received:
The function uses a switch statement to check the message received. For exam-
ple, if button RELAY 1 ON is clicked then msg .req .url will be loaded with the
data /relay?RELAY1=ON. Variable var1 is then loaded with 0 (remember that
a relay is activated if its input is at logic 0) to activate Relay 1, connected to GPIO
2. Similarly, if RELAY 1 OFF is clicked then msg .req .url will be loaded with the
data /relay?RELAY1=OFF. Variable var1 is then loaded with 1 to de-activate
Relay 1.
• Create 4 rpio gpio out nodes. Set the Pins of these nodes to GPIO 2, GPIO 3,
GPIO 4, and GPIO 17, corresponding to relay inputs IN1, IN2, IN3, and IN4 re-
spectively. Set the Types to digital output and Initialize pin states to High (1) so
that all the outputs are at logic 1 when the program starts. This ensures that all
the relays are de-activated at the beginning of the program.
Testing
• You should see the form shown in Figure 19.21 displayed on your PC screen
• Click button RELAY1 ON. You should hear relay 1 activated, and the LED corre-
sponding to this relay will turn ON on the relay module. Try turning ON/OFF other
relays to make sure that they all work. Figure 19.22 shows the URL when relay
1 is activated.
● 307
Programming with Node-RED
• You can also control the relays from your smartphone. Enter the URL:
192 .168 .1 .202:1880/relay as shown in Figure 19.23 and you will be present-
ed with the form to control the relays
19 .5 Summary
In this chapter, we have learned how to use the HTTP request node to request a web page.
Also, an example project is given to show how a web server can be designed to control 4
relays from a web browser.
● 308
Appendix A • The function node
A .1 Overview
The function node is one of the most useful nodes in Node-RED and it is based on JavaScript
(JS). In this Appendix, we will look at how to write statements inside functions, and also
learn the very important topics of string manipulations, built-in string, and mathematical
functions, conditional statements, repetition, etc that can be used in function nodes.
A .2 Variables
The nice thing about JS is that it does not care about the data types. Variables are declared
using the var keyword. Every statement must be terminated with a semicolon. Some ex-
ample variables are:
An integer number has no decimal point such as x = 25. A floating point number has deci-
mal point such as x = 25.322. Numbers can be written in scientific format as shown below:
x = 345e2 // x = 34500
or
x = 345e-2 // x = 3.45
All variables are destroyed except the 3 types of variables: global, context, and flow.
global variables: these variables retain their values across all flows. An example is given
below where integer 10 is stored in variable XYZ, and then variable abc is assigned the
value of XYZ:
global.set('XYZ', 10);
var abc = global.get('XYZ');
context variables: these variables retain their values in function nodes where they are
declared only. An example is given below where variable cnt is initialized to 0 if it does not
already exist. Then, it is incremented by one and stored back in cnt. Therefore, each time
the function is run the value of cnt will be incremented by one:
● 309
Programming with Node-RED
flow variables: these variables retain their values in the same flow. An example is given
below where again integer 10 is stored in XYZ, and then variable abc is assigned the value
of XYZ.
flow.set('XYZ', 10);
var abc = flow.get('XYZ');
Note the difference between the == and the === comparison operators. == is used to
compare two variables where the type of the variable (e.g string or number) is not consid-
ered. On the other hand, === is used to compare two variables including their types. For
example, if a = 10, then a == 10 is true and a == 5 is false. Also, a === 10 is true, but
a === "10" is false.
A .3 Multiple outputs
It is sometimes necessary for a function to have more than one output. This can be done
as shown in the following example:
A .4 String manipulation
String manipulation is one of the most important operations in JS. Examples of commonly
used string manipulation operations are given in this section.
Number
Converts a string to a number.
● 310
Appendix A • The function node
String
Converts a number to a string
Assuming that:
Then:
var pos = x.indexOf("name", 12); // look for name, starting from position
// 12. pos = -1
var pos = x.search("name"); // search for name and return its position
// (pos = 3)
var str = x.slice(-8, -6); // count from the end. Extract from
// position 6 to 8. str = ea
● 311
Programming with Node-RED
● 312
Appendix A • The function node
A .5 Mathematical functions
The following mathematical functions are commonly used. All of these functions must be
preceded by the keyword Math . For example, Math .abs(x):
To convert degrees to radians, multiply by Pi and divide by 180. For example, to calculate
sin 30 degrees:
● 313
Programming with Node-RED
Hyperbolic functions such as sinh, cosh, tanh, asinh, acosh, and atanh are also supported.
● 314
Appendix A • The function node
A .7 Date
Date functions are useful when we want to include the date and/or time in our function
nodes. Some of the commonly used date functions are given in this section. Data objects
are created with new Date(). Some commonly used functions are:
var dt = new Date(); // get date. e.g. Thu Dec 26 2019 10:52:02
// GMT+0000 (Greenwich Mean Time)
Additionally, the date and time can be set using functions: setHours(), setMinutes(), set-
Seconds() etc.
A .8 Arrays
Arrays are very useful in all programming languages as it enables related items to be col-
lected and accessed under a name. In JS arrays are indexed starting from 0.
We can use the following functions (only the commonly used functions are given here):
● 315
Programming with Node-RED
A .9 Conditional statements
Conditional statements are used when a choice is to be made in a program. JS supports the
following conditional statements:
if . .else . .elseif
This is one of the commonly used conditional statements. An example is given below. If
multiple statements are used inside a condition they must be enclosed in a curly bracket:
● 316
Appendix A • The function node
b = 1;
}
else
c = 0;
switch
The switch statement is used to select one of many conditions. An example is given below:
switch(n)
{
case 1:
text = "you selected 1";
break;
case 2:
text = "you selected 2";
break;
case 3:
text = "you selected 3";
break;
default:
text = "you selected something else";
}
do . .while
an example is given below where the loop is repeated 5 times. At the end of the loop, k = 5
var k = 0;
do
{
k++;
}while(k < 5);
for
repeat the loop a number of times. In the following example the loop is repeated 5 times
and the value of j = 5 at the end of the loop:
var k;
var j = 0;
for(k = 0; k < 5; k++)
{
j++;
}
● 317
Programming with Node-RED
while
Loop through while a condition is true. In the following example, the loop is repeated while
k < 5. At the end of the loop, k = 5
var k = 0;
while (k < 5)
{
k++;
}
for . .of
Loop through the values of an array. An example is given below. At the end of the loop,
variable y = "LondonParisAnkara":
for (k of cities)
{
y = y + k;
}
break
Used to exit from a loop when a condition becomes true. In the following example, the loop
terminates when k = 3. At the end of the loop j = 4
var k;
var j = 0;
for(k = 0; k < 10; k++)
{
j++;
if(k == 3)
break;
}
continue
Skip the loop when a condition becomes true. In the following example, the sum of num-
bers from 0 to 10 are calculated. When k = 5, the loop continues but misses this value. At
the end of the loop, j = 50 and not 55
var k;
var j = 0;
for(k = 0; k <= 10; k++)
{
if(k == 5)continue;
● 318
Appendix A • The function node
j = j + k;
}
A .11 Functions
Functions are useful when a certain operation is to be repeated several times in a program.
Functions are also used to breakdown a complex program into smaller more manageable
sections. In JS a function is declared with the keyword function, followed by the name of the
function. A function can have optional parameters inside brackets. The body of a function
must be enclosed inside curly brackets.
In the following example, a function called Add is created which has 2 arguments. The func-
tion adds these arguments and returns the result to the calling program:
function Add(a, b)
{
return a + b;
}
y = Add(3, 4)
A .12 Examples
Some examples are given below to show how some of the built-in functions can be used in
function nodes.
Example
Figure A.1 shows a flow diagram with a function node and a debug node. Assuming the
input to the function node is:
Write a function with 3 outputs to extract 15, 50, and 75. Display the results in the Debug
window.
● 319
Programming with Node-RED
Solution
The function should have the following statements. split() function is used to extract the
elements:
var F = msg.payload.split(",");
var1 = {payload: F[0]};
var2 = {payload: F[1]};
var3 = {payload: F[2]};
return [var1, var2, var3];
● 320
Appendix B • Flow programs used in the book
A .1 Overview
The web site of the book includes all the flow programs used in this book. The programs are
stored as word documents and are given the name of the Project that they belong to, e.g.
Project 29. Some flow programs do not belong to a project and for these, the name of the
figure they belong to is given. e.g. Figure 12.14
• You should see the flow program added to the Node-RED workspace
• Click Deploy
● 321
Programming with Node-RED
Processors:
Raspberry Pi 4, ESP32 DevKitC, ESP8266 NodeMCU, Arduino Uno
Components:
• 4 x Red LED
• 4 x 470 Ohm resistor
• 1 x Green LED
• 1 x Orange LED
• 1 x 10K pot
• 1 x 220 Ohm resistor
• 2 x 1K resistors
• 2 x 2K resistors
• 1 x Buzzer
• 1 x Button
• 1 x I2C LCD
• 1 x Parallel LCD
• 1 x DHT11
• 2 x Ultrasonic sensors
• 1 x MCP3002 ADC
• 1 x TMP36DZ sensor
• 1 x GPS Click board
• 2 x tRF Click Board
• 2 x Antenna for tRF
• 1 x Sense HAT
• 1 x 4 Relay module (Elegco)
● 322
Index
B F
Bar chart, 157 File operation, 33
Baud rate, 198 File permission, 28
Bluetooth, 272 Firmata, 247
Break, 318 Flashing LED, 85
Broker, 279 Flow variables, 309
Button, 106 Functions, 319
Button node, 163 Function nodes, 57, 309
Buzzer, 92, 135
G
C Gauge, 154, 251
Cat, 34 GET, 300
Chart, 156 GPIO connector, 80
Chat, 184 GPIO pins, 81
Comment node, 106 GPS, 204
Context variable, 87, 309 GPS click, 206
Compass heading, 229 Gyroscope, 227
Conditional statements, 316
Continue, 318 H
Copying node, 55 Halt, 40
Core nodes, 55 HC-SR04, 129
CSI port, 16 HD44780, 137
HDMI, 16
D Horizontal bar chart, 158
Dashboard, 153 HTTP, 300
Dashboard nodes, 153 HTTP request, 57
Date and time, 47 Humidity, 120
DELETE, 300
DevKitC, 257 I
DHT11, 124, 253 Ifconfig, 42
DHT22, 124 Importing, 54
● 323
Programming with Node-RED
Input nodes, 55 P
ISM, 222 Parallel LCD, 137
Ping, 187
J Pitch, 232
Jason, 72 PoE port, 16
Joystick, 233 Pressure, 242
Ps, 39
L POST, 300
Latitude, 208 Publisher, 279
LCD, 113 Push button, 106
LCD character set, 148 PUT, 300
LED colours, 235 Putty, 23
LED matrix, 234 PWM, 110
Line chart, 156
LM35DZ, 201 R
Logic level converter, 217 Random node, 121
Longitude, 208 Random number, 60
Raspberry Pi nodes, 58
M Raspbian Buster, 18
Map, 212 Remote access, 22
Mark, 110 Repetition, 317
Mathematical functions, 313 RF radio, 222
MCP3002, 142 Roll, 232
Mean, 67 Rotate screen, 243
Micro SD card, 17
MOSFET, 216 S
Mosquitto, 280 SCL, 113
Motion events, 229 Scrolling data, 242
MQTT, 278 SDA, 113
MQTT in, 281 Send UDP, 178
MQTT out, 281 Sense Hat, 225
Multiple GPIO, 98 Sense Hat nodes, 226
Multiple gauge, 160 Serial communication, 198
Multiple inputs, 62 Shutdown, 40
Multiple LED, 173 Slider node, 161
Multiple outputs, 65 Smooth node, 67
Social nodes, 58
N Space, 110
Ngrok, 269 SPI, 143
NodeMCU, 285 SSH, 23
Node-RED configuration, 78 Storage nodes, 58, 190
String manipulation, 310
O Subscriber, 279
Openweathermap, 71, 91 Switch node, 109
Orientation, 231 Super user, 37
Output nodes, 56 Switch, 317
● 324
Index
T
Talking weather forecast, 166
TCP, 170
Temperature conversion, 52
Text node, 165
TightVNC, 26
Timestamp, 190
TMP36, 146
Topics, 279
Traffic lights, 102
Trf click, 223
Trigger node, 86. 104
Twitter, 76
Twitter in, 76
Twitter out, 76
U
UDP, 170
UDP receive, 176
Ultrasonic, 129
Unit conversion, 62
URL, 301
USB keyboard, 17
USB port, 220
Utf-8, 195
V
Variables, 309
VNC, 25
VNC server, 25
Voltmeter, 144
W
Weather, 70
Web server, 301
Websocket, 56
While, 318
Whoami, 36
WiFi, 170
Wildcard, 33
Y
Yaw, 232
● 325
Programming with Node-RED
Dogan Ibrahim
Programming with Node-RED
lektor
● 326