Build Your Own IoT Gateway With Python
Build Your Own IoT Gateway With Python
Le Trong Nhan
Page 2 Faculty of Computer Science and Engineering
Contents
Basing on IoTs, applications are no longer staying at the smart concept but take one step
further, which is called autonomous. For instance, some supervising and self-adapting
projects about indoor services, parking lots, or monitor systems in agriculture and aqua-
culture. According to Timothy Chou - a famous speaker, his architecture about smart app
base on internet of things was divided into a 5-layer model. The figure below will describe
this model.
• Connect: Data collection from sensor nodes. Because existing connection stan-
dards are based on utilization, so this layer must support many connection types.
Those types include Zigbee and Wifi in smart homes with short-range communica-
tion or long-range communication as LoRa or 3G/4G.
• Collect: After the data is collected, a central server will receive and store data. Then,
a large amount of data will be pushed back to smaller servers, creating a big chal-
lenge for them which processing by Big Data technology.
• Do: The system will create some adaptive rules to fit the environment and suggest
decisions based on specific info. With each decision, the performance is evaluated
automatically by the system. Then, The system carries out deviation of action from
the optimal goal for the next time. In this way, the system automatically accumu-
lates “experience” over a long period, to become more and more intelligent and
perfect.
This tutorial will focus on layer Connect, with the function namely Gateway IoTs. A de-
vice will play a role of Gateway. It collects info and send them to the server as well as
receive control signal from server at Collect layer. We will create a Gateway in Python
programming language. The main content of this tutorial include:
The key factor in this architecture is the Gateway IoT, which will be built by combining
a computer and a Microbit. The reason for this combination is because the function of
Gateway will be implemented in Python programming language. Our computer is a pow-
erful and handy device for this requirement. In addition, when implementing the system,
the Python program can be easily used on embedded computers, such as Raspberry PI for
example. The Microbit circuit was added because of hte need to expand the connection
Many Microbit can act as sensor node and send data back to the central Microbit, where it
sent data to computer. In the computer, the program written in Python will send this data
to the Adafruit IO server. From there, remote monitoring devices such as mobile phones
or even another computer can monitor the system’s data. In case you want to control a
device, the data flow will go backward from the terminal to the sensor node, to execute
the control command.
In this first tutorial, we will start creating an account on the Adafruit IO server, before we
can use it to store sensor data and circulate control signals.
Step 1: Access the main website at https://io.adafruit.com/. This interface will appear.
Choose Sign In to login if you already have an account. However, this interactive button
will also lead us to creating new account page in the next step.
Step 2: Because we don’t have an account yet, so at this step, we choose Sign Up to
register an account.
Step 3: Provide personal information (FIRST NAME and LAST NAME), Email, username
and password. Except for USERNAME, you can not use special characters. Finally, we
choose CREATE ACCOUNT to create an account, as the instruction below.
Although, after successfully created an account, the system will login automatically, in the
next working session, user can login with Sign In function.
To be able to store data on server, we must classify it. Normally, We call it a feed. Usually,
each of the object in the system will have its own data channel. For example, too record
the state of a LED, we need a channel which name is BBC_LED. After successfully logging
in to the system, we begin to create the first data channel, with the instructions below.
Step 1: Open the list of data channels by clicking on Feeds, as showed in the picture
below:
Next, we chose View all to list all available data channels in your account, as shown in the
following figure:
In image above, our account does not have a data channel yet, because it has just been
registered for the first time. A data channel will be created by clicking the New Feed but-
ton.
Step 2: Fill in the information for the data channel, as shown in the figure below.
The most important is the Name of the data channel. Readers should name it with a prefix,
to easily distinguish which data channel is for which project. In this tutorial, we illustrate
data from a led display on Microbit, and name the channel BBC_LED. The Description
is optional, readers can add additional comment information. Finally click the Create
button. A new channel will be created and our interface will now look like this:
In case you want to delete an existing data channel, you can chose it and click Delete
Feed, as the picture below:
To do this, we need to access the feed directly, by clicking directly on the feed name, here
BBC_LED. There are many ways for readers to find your own channel. According to the
current process, readers can directly tap BBC_LED at Figure 1.10. In case you just login
to your account, just select Feeds, this data channel will appear, as shown in the image
below:
Let’s notice the Privacy section in the right pane, it’s currently in private mode. We click
on the settings icon, to go to the following interface:
In the above interface, we select Public in the Visibility section and finally, click the Save
button to complete the channel adjustment in shared mode.
Now, the information in the Privacy section has changed, with the additional instructions
Anyone can see it at this link. You can share your data channel with others by sending this
link. However, this step is only necessary in checking whether the data channel can com-
municate instantaneously. Also, it’s not really a useful feature in the applications we’re
going to implement. Usually, you will have the need to mask your channel to protect your
system’s data. Our purpose when setting the channel to Public is just to simplify future
programming.
4. Devices like sensors, pumps, power circuits belong to which layers in the IoT model?
A. Things
B. Connect
C. Collect
D. Learn
Solution
1. D 2. C 3. D 4. A 5. C 6. D 7. D
With different uses, the Feed data channel which introduced in previous lesson, often
used by the manager in order to check raw data of the system. Meanwhile, Dashboard
is a eye-catching and user-friendly interface. These two objects are usually called Back
End for Feed and Front End for Dashboard. Obviously, these two objects will have closed
association: If data is sent to Feed, Dashboard interface will be updated correlatively and
vice versa.
In this lesson, readers will be guided to create a simple Dashboard on Adafruit IO. This
Dashboard is used to connect to Feed that we have created in the previous lesson and
have a button which users can turn on/off the LED on Microbit. Dashboard Interface
looks like this:
Step 1: After signing in Adafruit IO account, you choose Dashboard, and click View all,
as instruction below:
Step 2: Press +New Dashboard to create a new project on Adafruit, as shown in the fol-
lowing figure:
After that, one window will appear to fill in the name and description for Dashboard. At-
tention! Name is required information, meanwhile, Description is optional. When nam-
ing the Dashboard, you should also add prefixes for future management, as shown in the
image below:
In case you wan to delete the Dashboard, you need to choose it in the above list, and press
Delete Dashboard button, as shown in the following image:
After successfully creating a Dashboard in previous steps, you can access into it(click di-
rectly Dashboard button you want to choose), an interface will be initialized and appear
like this:
Before designing objects on Dashboard interface (in this chapter, the object is a button),
we need to configure Dashboard to be Public, so we can share on many different devices,
such as mobile phone or tablet, in order to remote control and monitor system.By clicking
on the settings icon on the right side of Dashboard, we click on Dashboard Privacy icon,
as the following instructions:
A new default Dashboard interface doesn’t have any elements, we will put a button on the
interface by clicking on the Settings icon, and choose Create New Block, as follows:
The Dashboard support interface objects are plentiful. However, in this section, we choose
the first object. This object is called Toggle Button, and it is totally appropriate for appli-
cation which turn on/off a device in the future lesson. After that, this interface will appear.
This is the most important step in designing interface for Dashboard. Up to this lesson,
• Block Title: This part is optional, not required. Here we can give the button a name.
• Button On Text: In this part, we will have text on button if it on. At default settings,
if the state of the button is on, button will show the word "ON".
• Button On Value: This path allows us to customize data sent when this button is
clicked to be on state. For simplicity, we will specify the data for it as 1.
• Button Off Text:In this part, we will have text on button if it off. At default settings,
if the state of the button is off, button will show the word "OFF"..
• Button Off Value: This path allows us to customize data sent when this button is
clicked to be off state. For simplicity, we will specify the data for it as 0.
Besides, readers can check the change of the interface of the button, every time data is
sent to Feed, by typing 0 or 1 on Test Value box. This function simulate button in real-
ity. Finally,we click Create block icon and new button will appear in your Dashboard, as
follows.
4 Edit button
In some cases, we will need to reset the button object, for example, we can make it bigger,
change the value of on/off state, or delete this button object. it is able to make a few
adjustments by click on the Dashboard settings icon, and select Edit Layout, as instructed
below:
Interface objects on Dashboard will have their own settings icons. When we click this
icon, and click Edit Block, an old interface introduced at Figure 2.11 will appear for us to
change object configuration. The delete function will also appear in the list when we click
this icon.
In case you want to change the size of the object, you simply drag and drop its 4 corners
to change. Finally, press Save Layout button.
This is the final configuration check on Adafruit IO, before coding and sending data from
Gateway to Feed. The testing process will be in the following order:
Step 1: From Dashboard interface, you should try pressing the button on the interface,
remembering the times you press, corresponding to the ON and OFF states of the button.
Step 2: if you reopen the Feed interface,you will see raw data, which is 0 and 1, send to
Feed, as shown in the following figure.
Although a graph is plotted over the data channel, the reader should note its raw data,
listed in a table below. Every time we press the button, its state will be saved, along with
the time parameter. This raw information, will be sent down to the Gateway in the future..
Step 3: On the Feed, you press + Add Data button. This interface will appear:
You enter valid values, in this case you can choose 0 or 1, then click the Create button.
Obviously, A new data line will be added to the Feed. But at the same time, the interface
of the Dashboard has also been changed accordingly.
Step 4: Checking system latency. This will be something new that Adafruit IO server have.
You should try to share your Dashboard link with others, so that both parties can check
remotely. We will see that the data communication between Feed and Dashboard has very
low latency.
With Gateway IoT will be implemented in the next post, every time you interact on the
Dashboard, the data will be sent to the Feed. Then, the Feed will automatically send down
4. When configuring a button on the Dashboard, what is the value for the 2 states of the
button?
A. 0 and 1
B. 1 and 2
C. ON and OFF
D. different from each others
5. The latency of data communication between the Feed and the Dashboard is:
A. Fast
B. Slow
C. Average
D. indeterminable
6. The latency of data communication between the Feed and the IoT Gateway is:
A. Fast
B. Slow
C. Average
D. indeterminable
7. The latency of data communication between Dashboard and IoT Gateway is:
A. Fast
B. Slow
C. Average
D. indeterminable
Solution
1. C 2. B 3. C 4. D 5. A 6. A 7. A
The architecture with 4 level in Internet of things is like the diagram above. The Feed
on Ádafruit server become intermediary for transmitting data between Gateway IoT and
Dashboard. In this chapter, we focus on create a program on computer which received
data when user interact with Dashboard. This is new feature that you need for remote-
controlled applications. This feature on common server like ThingSpeak wiill have signif-
icant delay. In other word, user must take at least 30 second waiting to turn on a light bulb
after press its button by using ThingSpeak. However, this will done under 1 seconde witt
server Adafruit IO.
The main purposes of this chapter are as follows:
2 Adafruit Information
Gateway need information from adafruit to connect with Feed to transmit data to feed.
From task bar on Adafruit IO, after you log in into the systems, this information will be on
c My Key, like the picture below:
The information will be shown only you click on My Key, so that we need to save User-
name and Active Key.
Next, you need to check the Feed’s name of the data accessed by type Active Key. This
name will be create automatically by system and different with the name for Feed in the
previous chapter. You choose Feeds on the task bar and Feed info to access this informa-
tion, for instance: with feed BBC_LED, the below display will be shown:
After click on Feed Info, another display will be shown. Here, we have the feed channel
for the program, as like an example below:
3 Project on PyCharm
Now, we use PyCharm IDE to create functionality program for Gateway IoT on PC. Py-
Charm is one of the most application for Python developer because of its compatibility
with many different operating systems Windows, Linux or MacOS. This IDE provide us a
virtual environment to easily install extend library for some advanced features. We use
python with version 3.8 in this example.
Installation instructions for the PyCharm software as well as the Python compiler pro-
gram can be found in the Basic Python curriculum, shared at the following link:
https://drive.google.com/file/d/1dJLE3CdRJvU2QUOfjqMcX6azHMBYBl_q/view
After starting PyCharm, we choose File/New Project, as shown in the picture below:
A message window may appear after you click Create then choose to create a new project
in the current window of PyCharm so as not to have to open multiple windows at the same
time, by clicking This Window, as shown below:
Once the project is created, you can delete the default program content in main.py, to
start implementing the program for the IoT Gateway.
4 Install library
One of the indispensable first steps for advanced features with the Python language is to
install the library. The extension library we need to integrate is adafruit-io. There are
2 ways for us to install this library: Online installation using the pip install tool and in-
stalling from our self-developed GIT source code. The first method will be more familiar
with practician. However, for those who are just starting out or method 1 is not success-
ful, you can try method 2. Git server, which we maintain regularly and provide the most
suitable library for you to read. . The details for the 2 methods of installing the library are
presented as follows:
Up to this step, we are ready to implement the program. If the installation of the library
fails, you can try the second method, in the next section.
https://github.com/npnlab-vn/python_libs
Then the interface as shown below will appear, with a lot of libraries built by us for each
course.
Step 1: You need to select the correct folder before downloading the library to your com-
puter, by clicking the option at position 1. Then, navigate to the IoT_CoBan_64bit-v3.8
folder. For machines with different configurations, or other Python versions, you can
choose the appropriate library for their computer.
Step 2: Once we have selected the correct folder, we can download the library, by clicking
the Code button and selecting the ZIP file download mode in Download ZIP. You need to
choose the path to save the downloaded file.
Step 3: Extract the downloaded ZIP fil by right-clicking and selecting Extract Here. With
the newly extracted folder, continue to press right to copy (or press the hotkey Ctrl+C), as
shown below:
Step 4: Copy the extracted folder, and paste it into the project folder created in the previ-
ous section. In this directory, you will see the file main.py, like the following result:
After this step, when we return to the PyCharm programming environment, we will see
the libraries and attachments appear in the project window.
Step 5: Right click on the file setup.py and select Run, to install the library, as shown in
the image below:
In case the installation fails, you need to check their Python version. When creating the
project, this information will be located in the Base Interpreter section to reload the li-
brary accordingly.
5 Implement program
Now, we move to work in the file main.py to implement the program’s functionality. The
actual steps in this file are detailed as below.
You can execute the program in the file main.py, by right-clicking on this file and select-
ing Run. From the second, you can select the Run button on the PyCharm toolbar.
When connecting successfully with the server, the Gateway will subscribe to a data chan-
nel to receive data from it. When there is data from any source sent to the Feed, this data
will be automatically sent to the IoT Gateway, and the message function will automatically
run without processing much.
9 while True :
10 pass
Code 3.3: Configuration for the MQTT Client object
At the end of the program, we need an endless loop so that the program does not ter-
minate. Thus, it listens to the information sent back from the Adafruit server and au-
tomatically calls the message function for us. Since in this endless loop, we don’t need
to perform any function yet, so the pass command is added to correct the syntax in the
Python language.
https://github.com/npnlab-vn/code-manager/blob/IoT_Lab3/IoT_Lab.py
5.4 Demo
Now, we will execute the file main.py to test its functionality. Once launched, the Gateway
will connect to the Adafruit IO server and then subscribe to the Feed BBC_LED channel.
The following information will be printed to the screen if these two tasks are successful:
Now, you can reopen their Dashboard and interact on the push button to illustrate send-
ing the On/Off command. Almost immediately, this command will be passed down to the
IoT Gateway, as shown in the image below:
Obviously, all of this data is saved on the Data Feed, which you can check easily.
4. When configuring a button on the Dashboard, to which object is the value sent?
A. Gateway IoT
B. Data Feed
C. Dashboard
D. All objects above
6. What is the central mechanism of the connection between the IoT Gateway and the
Feed?
A. request/response
B. ask/wait
C. publish/subscribe
D. Unable to determine
Solution
1. D 2. A 3. B 4. B 5. C 6. A 6. C 7. C
With MQTT protocol, every time the IoT Gateway sends data, you will see this data imme-
diately update to the graph. This is very different from traditional sever such as ThingS-
peak. Normally, ThingSpeak has high latency, about more than 5 seconds for data to be
updated on graph. However, since we are using a free account from Adafruit IO, there is
also a limit on the number of times we can send data to the server. Currently, we can only
send no more than a packet per second. So, for monitoring applications, which does not
necessarily send data continuously, you can send data with 30 seconds or even 60 sec-
onds. We will reserve network resources for push buttons to control the device below the
IoT Gateway.
The main purposes of this chapter are as follows:
After creating new Feed, the result will be shown in the image above. However, you need
to access directly to Feed in order to change the privacy mode to Public. This operation
was described in the previous post and will not be detailed here.
From the settings icon in the right corner, Readers add new interface objects by clicking +
Create New Block. With the interface objects supported on Adafruit IO, we will select the
graph object, as shown below:
After that, an interface will appear, so that we can link the graph to the Data Feed. Here,
we will select Feed BBC_TEMPERATURE, as shown in the figure below:
Figure 4.5: Select the Data Feed associated with the graph
Press Next step button to configure the display of the graph. The interface is shown below:
There are many information that you can change. However, the configuration informa-
tion is in default mode without changing anythings. Here, we simply add information to
Block Title, and press Create block button at the end of this interface settings. As a result,
a graph will be added to the Dashboard as follows:
This is the required step, before starting to program the Gateway. We need to make sure
that the interaction between Feed and Dashboard is stable. This work can be done by
adding data manually to Feed BBC_TEMP, as introduced below:
Once some test data has been added, readers can reopen the Dashboard. If the installa-
tion on the Dashboard is successful, a graph will be drawn according to the values added
manually on the Feed, as follows:
5 Implement Gateway
After completing all tasks on Adafruit sever, which include Feed and completed Dash-
board, We can start programming for Gateway to send data periodically to sever. As shown
in the introduction, we will send a random value (simulated for temperature) every 30 sec-
onds. You need to review the information of the Feed to use it for programming. In this
case, this feed is called "bbc-temp".
When we send data to server, We don’t have to access to Feed channels. The commands
in AdafruitIO library allow us to send data(publish) by specifying the name of the Feed
directly.
The first step of programming, we need two available libraries in the system to set time
and get random numbers. You can add two commands at the begin of the program:
1 import random
2 import time
Code 4.1: Add libraries to system
Next, we will change the program in the infinite loop at the end of the program, like this:
1 while True :
2 value = random . randint (0 , 100)
3 print ( " Cap nhat : " , value )
4 client . publish ( " bbc - temp " , value )
5 time . sleep (30)
Code 4.2: Add libraries to system
At the moment, you can check on Feed or Dashboard. Every 30 seconds, a random data
will be sent. Meanwhile, every time pressing the button on Dashboard, data is immedi-
ately sent to Gateway. The complete program is shared at the following link:
https://github.com/npnlab-vn/code-manager/blob/IoT_Lab4/IoT_Lab.py
32 while True :
33 value = random . randint (0 , 100)
34 print ( " Cap nhat : " , value )
35 client . publish ( " bbc - temp " , value )
36 time . sleep (30)
Code 4.3: Gateway’s two-way communication program with Server
4. Which of the following commands has the effect of waiting 5 seconds in Python?
A. time.sleep(5)
B. time.sleep(5000)
C. delay(5000)
D. pause(5000)
5. Which of the following commands is correct to send data to a Feed on Adafruit IO?
A. client.publish("bbc-temp", 30)
B. client.publish("BBC-TEMP", 30)
C. client.publish("BBC-TEMP", "30")
D. All of them are correct
Solution
1. C 2. B 3. A 4. A 5. A 6. A 7. A
• The Gateway are running on a computer. In the future, this process will be brought
to a embeded computer. The general feature of every computer is common but not
specialized. Connecting with a specialized system must be through USB connec-
tion.
• Connecting with a dedicated system will provides almost limitless scalability for
computer system. In this occation, we want the capability of wireless communi-
tion of Microbit for Gateway IoT on computer.
• With wireless connection of Microbit,every sensor nodes using Microbit can easily
send data wirelessly to Gateway.
Although Microbit board connects with the computer via the USB connection, this method
has another name, called virtual COM serial communication. This is the most common
protocol for every microcontrollers (like Microbit) and embedded computer. The serial
connection also fully supports many programming languages, from drag and drop to
Python..
For the convenience of readers, small Python programs are introduced in each section.
However, at the end of this tutorial, we will cover the entire program. In the process of
reading and understanding the document, readers can refer to the program at the end so
that they can find the appropriate location to integrate the functional program.
For the time being, for the central Microbit board, we do not need any instructions in the
on start block or the forever block. However, readers should keep it for further develop-
ment in the future.
An important note, the data received from the serial communication is string data. There-
fore, when you want to process an instruction, the string comparison operator needs to
be used for precision (there is a character "" for string data). This program is shared at the
following link:
https://makecode.microbit.org/_5Rj8TeeM1RFb
After download programm to Microbit, we can start program the Gateway IoT, with the
detail steps are presented in the next section.
3 Implement Gateway
After successfully installing the library, readers can add the library import statement be-
low at the beginning of the program.
1 import serial . tools . list_ports
Code 5.1: Add Pyserial library
However, this COM port can completely be changed every time we restart the computer,
or when we change the USB port. Therefore, we provide you with a function to automati-
cally find this COM port, as instructed below :
Besides, this program can work correctly when only one Microbit connect with the sys-
tem. Thank to USB driver of this board, the program can automatically recognize it. In
case the function do not work, readers need to check in Device Manager to see if the de-
vice’s name has the keyword "USB Serial Device" or not.
The code for opening the Serial port to the Microbit board, using the function presented
above will be as follows:
1 ser = serial . Serial ( port = getPort () , baudrate =115200)
Code 5.3: Open connection with Microbit
In the above code, we specify the COM port name by calling the auxiliary function get-
Port() and the communication speed, configured to the default Microbit speed of 115200
bits/s
Once the connection can be successfully opened, sending data to the Microbit is very
simple. Readers can refer to the program in the next section: When receiving data from
the server, this data will be sent to the Microbit.
https://github.com/npnlab-vn/code-manager/blob/IoT_Lab5/IoT_Lab.py
26 def getPort () :
27 ports = serial . tools . list_ports . comports ()
28 N = len ( ports )
29 commPort = " None "
30 for i in range (0 , N ) :
31 port = ports [ i ]
32 strPort = str ( port )
33 if " USB Serial Device " in strPort :
34 splitPort = strPort . split ( " " )
35 commPort = ( splitPort [0])
36 return commPort
37
48 while True :
49 value = random . randint (0 , 100)
50 print ( " Cap nhat : " , value )
51 client . publish ( " bbc - temp " , value )
52 time . sleep (30)
Code 5.4: Open connection to Microbit
4. What character can be use as the end character for the command sending from Gate-
way to central Microbit?
A. #
B. :
C. $
D. All of the above
7. The request to send data from Gateway to central Microbit is implemented at what
function?
A. connected
B. subscribe
C. message
D. getPort
Solution
1. A 2. C 3. C 4. D 5. C 6. C 7. C
The limitation presented above is a general limitation of systems using operating systems,
such as computers in general and embedded computers in particular. These systems,
which have advantages such as stable network connection, support many new services
on the Internet. However, some tasks, such as receiving data from the serial port, are the
world of Microcontrollers like Microbit circuits.
Even so, we also have classical models to deal with for this. By encapsulating data in a
predefined format, as shown in the figure below:
Periodic sending is implemented in the forever block. The statement serial write string is
taken from the group Advance/Serial. The above program is shared at the following link:
https://makecode.microbit.org/_AXYRzvURMJVY
In this function, we need a global variable, named mess to accumulate the data received
from Microbit. You should notice how to specify a variable to be globally accessible with
the command at line 5, global mess.
https://github.com/npnlab-vn/code-manager/blob/IoT_Lab6/IoT_Lab.py
The source code for the program up to this step is presented as follows:
1 import serial . tools . list_ports
2 import random
34 def getPort () :
35 ports = serial . tools . list_ports . comports ()
36 N = len ( ports )
37 commPort = " None "
38 for i in range (0 , N ) :
39 port = ports [ i ]
40 strPort = str ( port )
41 if " USB Serial Device " in strPort :
42 splitPort = strPort . split ( " " )
43 commPort = ( splitPort [0])
44 return commPort
45
72 while True :
73 readSerial ()
74 time . sleep (1)
Code 6.3: Integrate the program into the IoT Gateway
2. What is the processing technique for receiving Serial data at the Gateway?
A. Declare a global variable to accumulate data
B. Process information based on the beginning and ending characters of the infor-
mation
C. Cut information based on special characters
D. All of the above techniques
3. With the format "!ID:KEY:VALUE#", which of the following character strings is valid?
A. !1TEMP30#
B. !1:TEMP:30#
C. !2:HUMI:60#
D. There are 2 valid strings
4. What effect does increasing the wait time in the while True loop have on the process-
ing of receiving data from Serial?
A. Lose data
B. Increases the delay when sending sensor data to the server
C. Doesn’t matter
D. It’s all wrong
5. To distinguish from which node of the sensor network the data is sent, which of the
following information should be considered?
A. ID
B. KEY
C. VALUE
D. All the above information
7. To access the sensor’s value, which of the following information will be used?
A. ID
B. KEY
C. VALUE
D. All the above information
Solution
1. A 2. D 3. D 4. B 5. A 6. B 7. C
Button on Dashboard
1 Introduction
Until now, we have built a system that has enough features at Gateway with the combi-
nation of the Python program running on computer and the connection of Microbit. Our
system can receive the signal from a button when users have action on Dashboard and
the data will be sent to the center Microbit which is connecting to the Python program
running on our computer.
In this chapter, we will expand our Dashboard by adding a new button. It is important to
note that in order to receive the data from Adafruit server, our Gateway need to subscribe
to the feed, which is similar to the thing that we subscribe to some Youtube channels to
get notification when they have new videos. In previous chapters, we have subscribed to
the feed that is related to turning on and off the led. In this lecture, we will create a new
feed to do something new such as turning on and off a water pump.
We also re-implement the center Microbit in order that it can have the correct execution:
Whenever the center Microbit receive a command from the Gateway, it will use the Radio
feature to forward the command to the sensor nodes. In the other hand, when this center
Microbit receive some data from sensor nodes (through Radio), it also send this data the
Gateway to process. Using Microbit in the previous chapters is just for checking the com-
munication feature of the Gateway.
Program in the forever block will not exist anymore. Reading and packaging the data
from the sensors will be left for the sensor nodes and will be presented in the next chap-
ter. Meanwhile, when receiving a command from the Gateway, the center Microbit will
change the data into numeric type before sending it to the sensor nodes with the radio
send number statement. The group of Microbit circuits in one system will be defined in
block on start with the radio set group statement.
When we use the center Microbit as a wireless communication bridge, we form a special-
ized wireless network which can meet the requirements of many applications. With this
approach, if we want to change to other wireless communications, for instance Lora or
ZigBee, it is feasible. Indeed, we just need to connect Lora device to all Microbit circuits
of the system. The program for the center Microbit will be shared in teh link below:
https://makecode.microbit.org/_7dFKhAecaf4A
This is the first step, before you create a new button on Dashboard. The steps to create
a new feed is the same as we introduce in the previous chapter, so it is not presented in
details again. Besides, you need to note that you must change the access of the feed to
Public for the new feed. Here, we create a new feed the name BBC_PUMP using for stor-
ing the data to control the water pump.
You need to pay attention the key of the new feed to use it for programming, in our case
here is bbc-pump.
In order to create a new button on Dashboard, you do the same steps in previous chap-
ter: Click on the setting icon, choose Create New Block and then select the button icon.
However, this time you will link your new button with the new feed which you just have
created before. The result will look like the below figure:
Finally, you configure two different value for the button. With two values 0 and 1 for the
button of the LED, we will choose 2 and 3 for this button. This will make the programming
in the future much easier.
After creating a new button, you need to check again the communication between Dash-
board and Feeds. If the communication between Dashboard and Feeds fails, you can
try to Refresh the Dashboard one or two times. After creating a new component on the
Dashboard, it can behave incorrectly with its functionality in the first time.
To generalize the way we approach and program with many buttons (corresponding with
many feeds) in the future, we provide a general code frame with some important notices:
Define an array of feeds that we need to subscribe: AIO_FEED_ID will be modified into
an array to store Feeds that we need to subscribe, like the figure below:
1 AIO \ _FEED \ _ID = [ " bbc - led " , " bbc - pump " ]
Code 7.1: Define AIO_FEED_ID as an array
In case that there are more feeds, you just need to list them in this AIO_FEED_ID variable.
Modify the connected function: Instead of just subscribing one feed like we did before,
one for loop will be used to subscribe all feeds listed in AIO_FEED_ID array.
1 AIO_FEED_ID = [ " bbc - led " , " bbc - pump " ]
2 def connected ( client ) :
Depending on how many feeds that you subscribe, there will be as many lines of notifica-
tions printed to the screen. Now, when we press two buttons on Dashboard respectively,
we will receive 4 different values. The result will look like the figure below:
https://github.com/npnlab-vn/code-manager/blob/IoT_Lab7/IoT_Lab.py
In order to avoid unexpected error, conditional statements are added in case that the
Gateway cannot connect to the center Microbit circuit. The source code of the whole
program is attached below:
1 import serial . tools . list_ports
2 import random
3 import time
4 import sys
5 from Adafruit_IO import MQTTClient
6
38 def getPort () :
39 ports = serial . tools . list_ports . comports ()
40 N = len ( ports )
41 commPort = " None "
42 for i in range (0 , N ) :
43 port = ports [ i ]
44 strPort = str ( port )
45 if " USB Serial Device " in strPort :
46 splitPort = strPort . split ( " " )
47 commPort = ( splitPort [0])
48 return commPort
49
50 isMicrobitConnected = False
51 if getPort () != " None " :
52 ser = serial . Serial ( port = getPort () , baudrate =115200)
53 isMicrobitConnected = True
54
55
79 while True :
80 if isMicrobitConnected :
81 readSerial ()
82
4. In which cases, we can distinguish data from buttons just using the payload field?
A. When these buttons return 4 different values
B. When they have 2 different feeds
C. When they are on the same Dashboard
D. All answers are correct
Working with node sensors means that we are dealing with the hardest part of the entire
system. Although sensor node actualization technology is not new, it’s problems comes
from having many, even overwhelmingly many sensor nodes. They will take care of gath-
ering 1 kind of information individually or as a group. Furthermore, some nodes can be
responsible for controlling either 1 or some sort of devices. Therefore, the world of sen-
sors is no doubt diverse.
A crucial thing for sensor chips is to identify the data that it will be forwarding to the Gate-
way so as to categorize the source of the data and what information is contained in that
data (temperature or humidity for example). The problem has been introduced in the
previous chapter will be further clarified on this chapter where multiple sensor nodes can
be seen interacting with the Gateway.
In this chapter, we will recreate a sensor node receiving orders from a central Gateway. In
particular, 4 simple commands will be sent to 1 sensor node to turn ON/OFF a light bulb
and a pump. The main requirements of this chapter are as follows:
• Connects electrical devices: electrical relay, pump and LED.
Therefore, in the above connection, we have left out the power cords (anodes) from the
battery while the cathodes of the battery is connected to a pole of the device (the pump’s
engine unidirectional). It wouldn’t affect the system functionalities at all if we were to
connect the pump with the cathodes left opened. If you don’t have access to a separate
battery, you can utilize the 2 power ports on the Chipi Base Shield. These 2 ports are
able to provide voltage to the pump with the external adapter’s voltage.
Finally, for the 4 ports controlling the Relay, we connect them to the control ports VCC-
GND-P0-P1 on the expansion board on the ChiPi Base Shield. The LED will be connected
to the adjacent ports which are VCC-GND-P1-P2. The entire system’s connections should
be as follows:
As such, in order to control the motor, we will program on the port P0 and the LED at port
P1 and P2.
Programming the ON/OFF effect of a device on Microbit is extremely simple. We just need
If you have 2 Microbit where the first is connected to the LED and the second is con-
nected to the Relay + pump, we only need to reduce the amount of conditions for the if
statement. An important node is that you are not allowed to use the else structure when
implementing receiving and executing features from the Gateway. It will cause unnec-
essary confusions when the system has multiple nodes. You should just implement the
correct condition statements.
https://makecode.microbit.org/_0zoE2PhgUigm
In this lesson, we will temporarily not actualizing the functionality in the forever loop.
In the later lessons, the process of sending the collected data will be implemented in the
forever loop.
2. Normally when a pump is not working, which 2 ports of the Relay are connected?
A. COM and NO
B. COM and NC
C. NO and NC
D. All are correct
4. Which of these commands are correct to receive orders from the Gateway Microbit?
A. seriel on data received
B. on radio received receivedNumber
C. on radio recevied receivedString
D. All are possible
6. Which of these sources are relevant for powering the engine of a pump?
A. 3.3V source from the Microbit
B. 5V source from the USB port of a computer
C. A 5V source from an external adapter
D. All of them can be used
7. How many pins of the Microbit can be used to control the ChiPi LED?
A. 1
B. 2
C. 3
D. 4
Solution
1. B 2. B 3. C 4. A 5. C 6. A 7. C 1. C 2. A 3. A 3. C 4. B 5. D 6. C 7. B
In this section, we will discuss about the integrated temperature and humidity sensor -
DHT11 as shown in the above figure. This sensor is able to simultaneously provide 2 kinds
of data from the environment, hence the word "integrated". DHT11 is a simple sensor
for beginners, however its advanced versions like DHT22 or AM2305 are more generally
used in practice. Nonetheless, these sensors are highly compatible in terms of software,
allowing us to switch for better devices with accuracy and durability at ease.
The main purposes of this chapter are as follows:
In this instruction, we will use a standardized DHT11 for connection compatibility with
the ChiPi Base Shield extension board. We simply connect a 4-pin wire with the extension
board. On connection, you should notice which pin of the Microbit board is connected
with the signal pin of DHT11. This information will be used in the next programming
phase. Following the previous sections, we will connect the sensor to pin P3 as in the be-
low figure:
Despite being one of the simplest integrated sensor, it is rather complicated when in
comes to data retrieval from DHT11. In order to initiate the communication protocol,
a query signal from Microbit board to the sensor is a low signal, which lasts 18ms. After-
wards, Microbit board will raise the signal to high level, waiting for response from DHT11.
After about 40µs, the sensor will acknowledge by sending back an 80-µs low signal, fol-
lowed by an 80-µs high signal. Finally, data of 40 bits will be sent back to the Microbit,
with bit 0 being comprised of a 50-µs low signal followed by a 25-µs high singal, while bit
1 being comprised of a 50-µs low signal followed by a 70-µs high signal. Readers should
pay attention to the unit of time, illustrated in figure 9.4.
After the decoding of the 40-bit data, Microbit board will continue processing to extract
the necessary information for the application, with the first 16 bits representing the air
humidity, followed by 16 bits for the temperature and ending with an 8-bit error detection
signal (40 = 16 + 16 + 8).
Due to the complication characteristic, mainly from the processing of the signal, most ap-
plication written for Microbit will use supporting programming libraries. Thanks to these
libraries, the programming will be a lot more simple and convenient for the readers to fo-
cus more on building the application itself, rather than the deep interaction to the system
regarding tasks for signal processing.
https://github.com/npnlab-vn/IoTBitKit
Finally, press the search button. The result will be displayed as below:
Many groups of commands for IoTBitKit library will be included into the system. For this
instruction, all the necessary commands for DHT11 programming belong to the com-
mand group NPNBitKit, as shown below:
Reusing the developed program in previous sections, we will add a feature to read the data
from the sensor every 30 seconds in the forever loop. This is the suggested program:
The sensory data will be sent to the central node in the predefined format. Two pieces of
information are sent a small time apart, reducing the probability of data collision. Fur-
thermore, in order to simplify the programming, we add a 30-second wait command at
the end of the forever loop. Readers may use their initiative by getting rid of this com-
mand, using only the wait command pause(100). For the second implementation, the
system will work a lot better.
Readers should notice that due to the connection to pin P3, we must add a command led
enable false in the on start block. With this command, all 25 LEDs of the Microbit will be
disabled in return for the usage of extra pins, such as P3. The program is shared in this
link:
https://makecode.microbit.org/_Y9ufwoAFAiKp
5 Improve Gateway
With the said 2-piece information, readers may add another feed and plot the humidity
data. Improvements for the Gateway program can be made by adding code to the pro-
cessData function, as shown below:
1 def processData ( data ) :
2 data = data . replace ( " ! " , " " )
3 data = data . replace ( " # " , " " )
4 splitData = data . split ( " : " )
5 print ( splitData )
6 try :
When using this product, readers must be aware of its number of pins. The upgraded ver-
sion of AM2305 is AM2315, which has 4 pins in stead of only 3 like AM2305. With its VCC
pin being compatible with wide voltage range (from 3.3V to 5V), AM2305 is suitable with
Microbit board. However, in large applications, 5V power source should be used for the
sensors in order to guarantee the stability. The accuracy for AM2305 is significantly better
than that of DHT11, with errors being only 0.1°C for temperature and 1% for humidity.
3. What is the name of the command group used for DHT11 and LCD programming that
was introduced in this section?
A. DHT11.
B. LCD.
C. NPNBitKit.
D. All of the above.
4. How many pins are needed to connect DHT11 with the Microbit extension board?
A. 1.
B. 2.
C. 3.
D. 4.
6. Which of the following sensors are compatible with DHT11’s connection pins?
A. DHT22.
B. AM2305.
C. AM2315.
D. A and B.
Solution
1. D 2. C 3. C 4. C 5. D 6. D 7. C
Due to the fact that operating this sensor is simple, projects which specifically related
to educational purple generally support the ADC output. Even the sensor with complex
components still supports the output with ADC standards, e.g. Analog Gravity sensor in
DFRobot, supports up to a hundred sensors with ADC output. One of the most important
of this kind of sensor is to supply a suitable voltage, which is should neither too high nor
too low as voltage is a critical factor to keep the sensor working normally
In this tutorial, we will talk about the how ADC sensor works and using the gas sensor
for illustration. We will also introduce the Chipi sensors which is a simple sensor sys-
tem with the standard connection designed for educational purposes, targets secondary
students implementation will remain for the readers to design with your creativeness.
This chapter aims to:
Firstly, take a look at the resistor bridge on the left side, which includes resistor R1 and
resistor R2, wired from the source to the ground. The resistor R1 represents the sensor
and its changes depend on the environment while the R2 is a constant. Apply the Ohm’s
law, the voltage at SIG1 will be calculated as:
V CC ∗ R2
SIG1 =
R1 + R2
Apparently, when R1 changes, SIG1 will change too. Now recall the soil moisture sensor
in the previous chapter, when the soil dries the more resistant R1 is. As the R1 is under the
denominator, the less voltage at SIG1 will be. In reverse, when soil is humid, less R1 will
result in the high voltage at SIG1. This behavior is reversible when we change the position
of R1 and R2 in this circuit.
Most of the devices in the ChiPi system are designed by following this rule. Therefore, the
output of a sensor essentially includes 3 pins: VCC, GND, and SIG. However, in the ChiPi
system, there is an amplifier OPAM integrated on the right side to keep the signal at SIG2
more stable. This circuit is called a feedback amplifier as the output is feedback wired to
the OPAM pin. This wiring is to ensure the voltage at SIG2 and SIG1 is equal, however,
with the resistant capability of the OPAM, there is no current directly apply to Microbit.
Therefore, Microbit is more durable and does not overheat during operation. When there
is no OPAM, there is a small current from SIG1 apply to Microbin pins, hence the more
voltage SIG1 is (when the sensor hails or signal interferences) will, unfortunately, dam-
aged the Microbit
About the sensor which outputs a voltage, the programming in Microbit easily gets with
the function analog read. The return of this function is a number that ranges from 0 to
1023 (or ADC 10 bit). The result has no unit name. Therefore, to convert it to unit % of
the soil sensor, or lux of the intensity, even the ppm of the CO2 concentration, we need to
construct another conversion function. This construction will cost too much as we need
a stable product to map the voltage value to the desired value. In the book, we make it as
simple as possible so that we just differentiate between when it is over a defined threshold
or not, we do not deeply investigate the conversion function.
In the sensor market, there are gas sensors that work on the electrochemical rule, here is
the list of common sensors:
Hence, in this tutorial, we can extend to another application by replacing the MQ2 sensor
to another sensor in MQx family. However, most importantly, the sensor should be sup-
plied with a voltage of 5V, the reader must follow this rule when work with Microbit and
its based shield. We will use ChiPi Based Shield V2 in this section with the support of 2
ports of 5V. To supply voltage for these ports, we need a power supply called an adapter.
Then, MQ2 sensor will be attached to the based shield via a 4-pin wire, as shown in the
figure below:
Take a look at this arrangement, the gas sensor is attached to pin P0 of Microbit. To find
this pin position, readers should take care of the yellow wire which is connected to the
SIGNAL pin of the sensor and the ChiPi Base Shield V2.
With these simple applications, the above program is run to record the value from the
sensor. Readers need to choose your threshold for your comparison to intentionally give
a warning when it reaches over your threshold. Take an example with the gas sensor, when
we carefully chose a threshold to warn the user if the gas is above an allowed level. You
can further send the data to the ThingSpeak server and activate the warning email as we
had covered in the previous chapters.
The output value from the ADC ranges from 0 to 1023 when working with the Microbit.
On the other hand, an ADC converter on Microbit represents 10 bits. Therefore, with the
voltage input from the sensor, we choose it to range from 0V to 3.3V to result in a linear
mapping in the 10-bit domain value, from 0 to 1023 (210 − 1). In case we need to calculate
In the example program, two variables are declared to temporarily store the calculating
value, includes gas_raw to read the raw data and gas_mV to store the result value when
converted to mV. Because the value range of gas_raw is from 0 to 1023, the corresponding
value range of voltage is from 0 to 3300 mV (3.3V), hence the parameter of the block is
scaled as in the example program.
When the raw data is converted to the voltage, readers should use one more conversion
function to finalize the desired unit. This second conversion depends on which sensor is
used, so we don’t mention it in detail. When applying this second conversion, readers will
use the calculation function from Math category, we also don’t mention it in detail for this
section.
For the infrared obstacle sensor, when an obstacle is nearby, the voltage increases (due to
the reflecting light from the sensor). In reverse, when an obstacle is placed further or there
is no obstacle, the voltage decreases. Moreover, the soil sensor or the sound sensor also
works based on this rule. There is some precaution when connecting with the Microbit:
• Analog sensors are supported at pins: P0, P1, P2, P3, P4, and P10. Therefore, we just
connect at most 6 analog sensors in a single Microbit. If we want to connect more
analog sensors, we can use another Microbit and then using the Radio to commu-
nicate between them
• When connecting via P3, P4, and P10, block on start will need to use the statement
led enable false to initialize the ADC control of these pins. As the result, we cannot
use the LED display of the Microbit
• We should choose the threshold carefully. When you cannot use the 25 LEDs in
Microbit (as statement led enable false), you can send the data to your computer or
using Data Streamer add-on of Excel.
When you work with a worthier sensor, such as a water quality sensor or air quality sensor
in the sensor market with an ADC output, you can integrate it into the Microbit. There-
fore, readers should take care of supply a suitable voltage prior to the specification of your
sensor.
With the implementation of sensors and sending the data to the center node, we will leave
it for the readers for further investigation. Readers should define a keyword when sending
the data of the sensor to the center node and processed it in a processData function of
the Gateway. Furthermore, not only one node but you can use multiple nodes and send
the data concurrently to the center node. In this case, readers should define an identifier
called ID for each sensor node so that the center node can differentiate between all sensor
nodes
5. Which is the conversion function supported in the Makecode to convert the raw data
to desired voltage?
A. Math
B. map
C. linear
D. None of the above
6. When connect the sensor to pin P3, which statement is used in block on start?
A. led enable true
B. led enable false
C. led turn on
D. led turn off
7. When we turn off the LEDs control in Microbit, which statement will have no effect?
A. show number
B. show icon
C. show string
D. All of the above
Solution
1. B 2. A 3. C 4. B 5. B 6. B 7. D