MIT App Inventor Projects 50+ Apps With Raspberry Pi, ESP32 and Arduino - Compressed
MIT App Inventor Projects 50+ Apps With Raspberry Pi, ESP32 and Arduino - Compressed
Dogan Ibrahim
Projects
MIT App Inventor Projects
This book is about developing apps for Android and iOS compatible
mobile devices using the MIT App Inventor online development
environment. MIT App Inventor projects can be in either standalone
●
mode or use an external processor. In standalone mode, the
developed application runs only on the mobile device (e.g. Android
or iOS). In external processor-based applications, the mobile device
All projects presented in this book have been developed using the
MIT App Inventor visual programming language. There is no need
to write any text-based programs. All projects are compatible with
Android and iOS-based mobile devices. Full program listings for
all projects as well as detailed program descriptions are given in
Elektor International Media the book. Users should be able to use the projects as they are
presented, modifying them to suit their own needs.
Dogan Ibrahim
www.elektor.com
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE
RN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
SIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHAR
RN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
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-89-9
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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Chapter 1 • Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.7 Project 2 – Using a Button, a Label, and Text Boxes – Language Translation . . . . . 32
3.15 Project 10 – R
eading a Message and Sending a Reply Message
Automatically when Busy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
●5
3.24 Project 19 – Global Positioning System – Latitude, Longitude, Altitude, and Speed 70
3.31 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Chapter 4 • M
IT App Inventor projects using mathematical &
logical operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Chapter 5 • R
aspberry Pi 4 – specifications – setup –
installing the operating system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
●6
5.8.3 Method 3 – Create a Python File in GUI mode – Using the Thonny . . . . . . . . . . 119
5.10 Accessing Raspberry Pi 4 Hardware and Peripheral Devices from Python . . . . . . 121
7.2 Project 1 – Getting and Displaying the Local Wi-Fi Parameters . . . . . . . . . . . . . . 174
●7
Chapter 8 • R
aspberry Pi Node-Red based projects using
MIT App Inventor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Chapter 9 • A
rduino Uno Bluetooth based projects using
MIT App Inventor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
9.10 Project 6 – Sending the Ambient Temperature to Android Mobile Phone . . . . . . . 228
Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor . . . . . . . . . . 259
●8
Chapter 11 • ESP32 based projects using the MIT App Inventor . . . . . . . . . . . . . 290
11.3.1 Installing the Arduino IDE for the ESP32 DevKitC . . . . . . . . . . . . . . . . . . . . . 292
Appendix E • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
●9
● 10
Preface
Statistics show that the number of smartphones sold to end-users in the last decade from
2007 to 2017 has been steadily increasing. In 2016, around 1.5 billion smartphones were
sold to end-users worldwide. In 2017 this number increased to around 1.54 billion, which is
a significant increase over just one year. In the fourth quarter of 2016, 81.7% of all smart-
phones sold to end users were phones with operating Android. This number increased to
85.9% in the first quarter of 2018, 85.9% (source: https://www.statista.com).
Developing apps for mobile phones is not an easy task and can require extensive knowl-
edge of programming. Program development also takes a considerable amount of time.
Android-based apps are available in the Google Play Store. Most of these apps are free
of charge and can easily be downloaded to your mobile device. The problem with most of
these apps is that they are not tested by any authority and therefore are available as you
find them. Also, most of these applications contain advertisements which can be annoying
for their users. It is however, possible to purchase more professional apps without any
built-in advertisements.
This book is about developing apps for Android and iOS compatible mobile phones and tab-
lets using MIT App Inventor. MIT App Inventor is a visual graphical programming language
based on blocks. Users drag and drop visual objects (called blocks) to create applications
that can run on mobile devices. MIT App Inventor was developed as an educational tool to
teach visual programming skills to newcomers, especially children in primary and second-
ary education. Moreover, it is used in higher education institutions as well as by professional
programmers. MIT App Inventor enables users to quickly create complex programs to run
on mobile devices. For example, an application program can easily and quickly be devel-
oped on a mobile device to display ambient temperature and humidity readings. The de-
velopment of such a program using classical text-based programming languages requires
significant programming skills and will take much longer time to develop.
MIT App Inventor projects can be in standalone mode, or use an external processor. In
standalone mode, the developed application runs on the mobile device only (e.g. Android
or iOS). In external processor-based applications, the mobile device communicates with
an external microcontroller-based processor, such as a Raspberry Pi, Arduino, ESP8266,
ESP32, etc.
In this book, many tested and fully working projects have been developed both in stan-
dalone mode and using an external processor. Full design steps, block programs, and QR
codes are given for all projects. In external processor-based applications (for example
using the Raspberry Pi), block diagrams, circuit diagrams, and full program listings are
provided with complete documentation for all projects.
Users will find all program listings on the Web site of this book. The MIT App Inventor pro-
grams can easily be imported to your MIT App Inventor projects. Additionally, the programs
of the external processor-based projects can be uploaded to the appropriate external pro-
cessors to save you the time of typing them.
● 11
Although all of the projects have been tested using an Android mobile phone, they should
equally work on Android tablets and iOS compatible mobile phones and tablets without any
changes.
I hope you like reading the book and find it useful for your next Android-based apps project.
● 12
Chapter 1 • Introduction
Scratch was one of the early block-based programming languages which are currently
used by children of all ages. It is an online tool where children can create projects by join-
ing blocks. Figure 1.1 shows the online screen of Scratch. Using Scratch, children can mix
various tools in their programs, such as music, sound effects, graphics, etc. Scratch pro-
gramming environment consists of three main sections: a stage area, blocks of palettes,
and a coding area. Users bring the required palettes into the coding area and join them
to make the final code. The stage area shows the results, such as the animation. Scratch
is very popular in the United Kingdom and the United States and there are several coding
clubs that children join to share their projects with others. Many children create interesting
applications including simple but interesting games as well. Scratch is used as the introduc-
tory computer programming language in many primary and secondary schools. After gain-
ing experience with Scratch, children are introduced to Python (and Java) as their second
language. Scratch is also used in some higher education institutes, such as it is used in the
first week of the Harvard University introductory computer science course.
● 13
Many people claim that the block-based visual programming tool does not teach the prin-
ciples of programming. This is not true since children at an early stage understand the
principles of programming and it becomes easier for them to develop complex text-based
programs in later life. When people hear of block-based programming, they tend to associ-
ate it with teaching children or beginners to programming languages. Although block-based
programming is popular among children, it can also be used by adults and professional
programmers to develop projects quickly and with little effort.
Block-based programming has the advantage that it is easy to modify a program because
all that is required is to manipulate the blocks. Another very important advantage of block-
based programming is that complex programs can be developed in a few seconds instead
of hours required with text-based languages. For example, consider the project where it
may be required to read the ambient temperature and send it to someone's mobile phone
as an SMS message. This project will probably take less than 30 minutes to develop us-
ing a block-based programming language, assuming that there is a block to handle SMS
messages. The same program, when written using text-based programming, can easily
take several days to develop and test. This is because the SMS block hides away all of the
complexities of establishing communication with the receiver and sending packets of data.
Another advantage of block-based programming is that the users do not have to memorize
the syntax of the language. For example, in a text-based programming language missing
a semicolon in a program can result in errors which sometimes can take some time to find
out the cause of the error.
This book is about using the MIT App Inventor to develop projects. This is a block-based
web programming language that is currently very popular all over the world. MIT App
Inventor is an online tool and it is free of charge (there is also an offline version). It was
developed originally by Google, but now it is maintained by the Massachusetts Institute of
Technology (MIT). App Inventor allows people of all ages to use to develop programs for
mobile phones. It supports both the Android and the iOS operating systems (iOS support
● 14
started by the 8th of July, 2019). The final program is compatible with both operating sys-
tems and can be installed and used on both Android and iOS compatible mobile phones and
tablets. In this book, only the Android operating system is considered since the developed
programs can be uploaded to both operating systems and they are fully compatible and will
work without any modifications.
MIT App Inventor is GUI based and is similar to Scratch and StarLogo, where developers
drag and drop and join visual blocks to create an application. Many blocks are offered in
the MIT App Inventor that enable users to create projects using components such as text
boxes, labels, buttons, sliders, checkboxes, switches, notifiers, camcorders, cameras, text
to speech components, speech recognizer, drawing and animation components, web tools,
sensors, maps, storage components, Bluetooth connectivity and so on. These components
are organized under the heading Palette and are placed at the left-hand side of the MIT
App Inventor startup screen as shown in Figure 1.2.
When a new application is started, a mobile phone image is shown in the middle part of
the screen. The development of a project is in two stages: Designer and Blocks. A pro-
ject starts in the Designer stage where the user places the required components onto the
mobile phone image to build the view of the final application. Some components are hidden
and are only shown outside at the bottom of the phone image. After designing the screen
layout, the user clicks the Blocks menu where the second stage of the development starts.
Here, the block program is constructed by clicking, dragging, dropping and joining the re-
quired blocks on the mobile phone image.
● 15
When the design is complete it is required to test the project. Here, the user has the option
of either using a built-in Emulator, to connect to the mobile phone using a USB cable, or to
upload the developed application to the mobile phone using a wireless Wi-Fi link. Emulator
option is useful if the user has no mobile phone at the time of the development, or if an
Android or iOS compatible mobile phone is not available. The second option is useful if there
is no Wi-Fi connection where the developed application is uploaded to the mobile phone via
a USB cable. The third option is the preferred option where the developed block program
is uploaded to the mobile phone using a Wi-Fi link. In this book, we will be using this third
option to upload the program.
Perhaps the easiest way to understand how to use the MIT App Inventor is to look at a very
simple example. In the example below the stages of the development are summarized.
1.3 Example
This is perhaps the simplest example one can build. This example aims to show the stages
of developing a project using the MIT App Inventor.
In this example, we will insert a button and a textbox on the mobile phone screen. Pressing
the button will display the message Hello there! in the textbox.
Design: Click menu option Designer. Figure 1.3 shows the mobile phone screen where a
button and a textbox are placed on the mobile phone screen.
Block Program: Click menu option Blocks. Figure 1.4 shows the block program. It is
clear from these blocks that when the button is clicked the message Hello there! will be
displayed in the textbox.
● 16
Build the program: Click menu option Build in the top menu and select App (provide
QR code for .apk). Wait until the QR code of the application is generated as shown in
Figure 1.5
Upload the program to your mobile phone: Start apps MIT AI2 Companion (we will
see in later chapters) on your mobile phone and scan the QR code. Click to install the ap-
plication on your mobile phone
Testing: Start the application on your mobile device to test it. The output in this example
is shown in Figure 1.6.
MIT App Inventor projects can either be in standalone mode, or they use an external pro-
cessor. In standalone mode, the developed application runs only on the mobile device (e.g.
Android or iOS). In external processor-based applications, the mobile device communicates
● 17
In this book, many tested and fully working projects have been developed both in stan-
dalone mode and also using an external processor. Full design steps, block programs, and
QR codes are given for all projects. In external processor-based applications (for example
using the Raspberry Pi), block diagrams, circuit diagrams, and full program listings are
given with complete documentation for all projects.
Users will find all the program listing on the Web site of the book. The MIT App Inventor
programs can easily be imported to your MIT App Inventor projects. Additionally, the pro-
grams of the external processor-based projects can be uploaded to the appropriate exter-
nal processor to save you the time of typing them.
● 18
2.1 Overview
In this chapter, we will look at the various ways MIT App Inventor can be used to create
projects. The nice thing about MIT App Inventor (called the App Inventor in this book for
short) is that the PC software is cloud-based and there is no need to install it before use.
Note that in this and future chapters, all references to the Android operating system are
also valid for iOS.
The following are required to create applications using the App Inventor:
Optionally:
• You can use the Emulator if you do not have an Android compatible phone or
tablet
• You will need to connect the Android device to a PC using a USB cable if you do
not have a Wi-Fi link.
There are 3 options for setting up and using App Inventor. These are described in the next
section briefly.
● 19
Figure 2.1 Option 1 – Using the Android device with Wi-Fi link
This option requires the apps MIT AI2 Companion to be installed from the Play Store to
your Android device as shown in Figure 2.2.
Figure 2.2 Install the MIT AI2 Companion to your Android device
After you create your project, the next step is to upload (install) it to your Android device
for testing. The steps to upload your project to the Android device are as follows (these
steps will become clearer when we look at the steps to create a simple project in the next
section):
• After the project is complete, click Connect and then AI Companion as shown
in Figure 2.3, or, choose Build and then App (provide QR code for .apk) to
install the project permanently on your Android device.
● 20
• Start the apps MIT AI2 Companion on your Android device and click the scan
the displayed QR code (note that the QR code is only valid for 2 hours) and
hold your device to scan the displayed QR code
• After a few seconds, the project will be uploaded to your device. Follow the in-
structions to install the project.
Alternatively, you can enter the 6-character code displayed next to the QR code (Figure
2.4) to your Android device to upload the project.
● 21
Here, the application is built on the computer and is uploaded to the Android device through
a USB cable. This option requires a driver to be loaded to the Windows-based PCs (there
is no need to load a driver for the Mac or Linux machines). The steps are as follows (you
must install from an account that has administrator privileges). See also the following link:
https://appinventor.mit.edu/explore/ai2/setup-device-usb
appinv.us/aisetup_windows
• Open the file and click through the steps to install the file. It is recommenda-
ble to not change the installation directory. You will find the path to the file is:
C:\Program Files\Appinventor\commands-for-Appinventor
• Download and install the apps MIT AI2 Companion from the Play Store to your
Android device (see Figure 2.2)
• Using the USB cable (also the emulator) requires the use of the program named
aiStarter. There should be a shortcut on your Windows-based computer to this
program (On a Mac, aiStarter runs automatically when you log in), or you should
be able to locate it in your Start menu. Start the aiStarter, you should see the
aiStarter icon in your taskbar. You should see a window as shown in Figure 2.6
(On GNU/Linux, aiStarter will be in the folder /usr/google/commands-for-Appin-
ventor and you'll need to launch it manually. You can launch it from the command
line with /usr/google/appinventor/commands-for-Appinventor/aiStart-
er)
● 22
• Connect your Android device to your computer using a USB cable, and make
sure that it is not mounted as a drive on your computer. You may have to go to
My Computer (on Windows) and right-click to disconnect any drives (e.g. eject)
that were mounted when you connected your Android device. The device should
be connected as a mass storage device (not as a media device, i.e. as trans-
ferring files, but not as sending pictures). You may get the message saying Allow
USB Debugging?. Press OK.
• Once you complete your project and there is a successful USB connection be-
tween the computer and Android device, you should click Connect and then USB
to upload your project to the Android device.
● 23
You will have to install software on your computer before the emulator can be used. The
steps are:
appinv.us/aisetup_windows
• Open the file and click through the steps to install the file. You are recommended
not to change the installation directory. You will find that the path to the file is:
C:\Program Files\Appinventor\commands-for-Appinventor
• Using the emulator (as with the direct link) requires the aiStarter program to run.
This program was installed in the previous step and you should run it manually
(On a Mac, aiStarter will start automatically when you log in to your account and
it will run in the background). You should see a screen similar to Figure 2.6.
• After you complete your project on the computer, click Connect and then Emula-
tor as shown in Figure 2.10
● 24
• You should see a message saying the emulator is connecting (see Figure 2.11).
You might have to wait a few minutes for the connection to complete.
• You should see a virtual Android mobile phone displayed with the screen chang-
ing until the project screen is displayed, as shown in Figure 2.12.
Note: if you get aiStarter not available messages even though the software has already
been started, you should click to run the program adbrestart in directory C:\Program Files
(x86)\AppInventor\commands-for-appinventor\adbrestart.
2.3 Summary
In this chapter, we learned how to set up the MIT App Inventor software. There are 3 differ-
ent methods we can test our developed project with, depending on whether or not we have
an Android device and Wi-Fi. Method 1 is the most commonly used and it assumes that the
user has an Android device and also the device is assumed to be connected to the same
Wi-Fi network as the computer where the software has been developed. Method 2 assumes
that there is an Android device but no Wi-Fi link. Here, the Android device is connected to
the computer using a USB cable. In method 3 it is assumed the user has no Android device
and the developed program is emulated on a virtual Android phone on a computer screen.
In the next chapter, we will develop some simple projects using MIT App Inventor.
● 25
3.1 Overview
In the last chapter, we learned how to set up MIT App Inventor (it will simply be called App
Inventor in this chapter). In this chapter, we will develop simple projects to make readers
familiar with the various features of App Inventor. Note that the QR codes given in the pro-
jects were valid only for 2 hours at the time they were created, and they cannot be used to
install the apps to your mobile phone. They are only given here for completeness.
• Enter the words MIT App Inventor to the Google search engine and click to
start the project
https://appinventor.mit.edu/explore/get-started
• You should be presented with the startup screen: Getting Started with MIT
App Inventor screen
• Click Create Apps! On the top left-hand side of the screen to start App Inventor.
● 26
Figure 3.1 The Designer startup screen (taken from the MIT App Inventor web site)
The Blocks screen is shown in Figure 3.2. The middle part is the Viewer where the visual
programming components are selected from the component-specific drawers on the left-
hand side of the screen.
Figure 3.2 The Blocks screen (taken from the MIT App Inventor web site)
In the projects in this book an Android mobile phone is used to test the developed projects.
Additionally, a Windows 10 based laptop is used to develop the projects using the App In-
ventor. It is assumed that the mobile phone is connected to the same Wi-Fi router as the
laptop.
Description: In this project, we will have a button on our Android screen. When the button
is clicked a bell sound will be generated by the Android phone which can be heard on the
speakers.
● 27
Aim: This project aims to show how a button can be used together with a sound clip.
• Click and drag a Button from the User Interface to the Viewer
• Set the properties of the button on the right-hand side as follows (only the re-
quired changes are shown):
FontBold: tick
Text: Click to sound
• Click Media in the Palette and drag and drop Sound onto the Viewer. Notice
that the sound icon is displayed outside the mobile phone.
• Now we have to upload our sound file. There are many free of charge MP3 sound
files that can be used in projects. In this project, the telephone bell sound file
● 28
• Make sure that Sound1 is highlighted on the right-hand side and click Upload
File. Browse and select the sound file you have downloaded. You should see the
filename displayed just above Upload File
This completes the visual design of the project in the Designer menu. Now, we have to
select the Blocks menu and do the visual programming part of the project. The steps are:
• Click Blocks
• Click on block when Button1.Click do as shown in Figure 3.4. You should now
see that this block is displayed in the Viewer
• Join call Sound1.Play with the when Button1.Click do as shown in Figure 3.5
This completes the design of the visual program. As can be seen from Figure 3.5, when the
button is pressed, we are telling the program to play sound1.
● 29
We should now compile and upload our project to the Android mobile phone. The steps are:
• Click Build and then App (provide QR code for .apk) and wait until the project
is compiled
• You should be presented with the QR code as shown in Figure 3.6 (this code is
valid only for 2 hours and is given here for completeness). Start the apps MIT
AI2 Companion on your mobile phone and click scan QR code. Hold the phone
to view the QR code on the screen
• Accept to download the project to your Android device and then click Install to
install it.
• You might see the message Blocked by Play Protect. Click INSTALL ANYWAY
and then click Open to run the project as an app on your Android device
• You should see that the app with the name BellSound is installed on your An-
droid device
• You should hear the bell sound when you click the button on your mobile phone.
You may want to use the emulator if you do not have an Android device. The steps are as
follows:
• Click Connect followed by Emulator and wait until the emulator is connected as
shown in Figure 3.7
● 30
• Make sure that the sound volume of your computer is turned ON. Click the button
in the emulator and you should hear the bell sound on your computer
• Click My Projects
• The project will be stored in the Download folder of your computer and it can be
copied to other places if required
• The option Export all projects can be used to save all of your projects
● 31
• Click View Trash, select the project and click Delete From Trash
• After the download is complete, you can share the project with your friends by
sending them the .apk file so that they can install it on their mobile devices
3.7 Project 2 – Using a Button, a Label, and Text Boxes – Language Translation
Description: This project translates words from English to German. The English word to
be translated is written and the button is clicked. The translation of the word is German is
displayed in another text box.
Aim: This project aims to show how a button, a label, and text boxes can be used in a
project. The project also shows how words can be translated into other languages using
App Inventor.
• Click and drag a Label to the Viewer, and configure the label as follows:
FontBold: ticked
Fontsize: 20
Text: Word to be translated
• Click and drag a TextBox to the Viewer under the label, rename it as SourceT-
ext, and tick box FontBold. Clear box Hint
● 32
FontBold: ticked
Text: Click to Translate
• Click and drag a TextBox to the Viewer, rename it as DestText and tick box
FontBold. Clear box Hint
• Click and drag a YandexTranslate to the Viewer. This will only be visible under
the mobile phone image
This completes the visual design of the project in the Designer, which is shown in Figure
3.8.
Now, we have to select the Blocks menu and do the visual programming part of the pro-
ject. The steps are:
• Click Blocks
• Click Button1 from the Palette on the left-hand side and select block when
Button1.Click do
• Click YandexTranslate1 from the Palette on the left-hand side and select call
YandexTranslate1.RequestTranslation. Join the two blocks as shown in Fig-
ure 3.9
● 33
• Click Text under Built-in and join it to the two blocks. This text will define that
the translation will be from English to German. Enter en-de inside this text.
• Click SourceText on the left-hand side and select SourceText.Text (see Figure
3.10)
So far we have translated the word in textbox SourceText, but have not told the program
where to put the translated word. This can be done as follows:
• Click YandexTranslate1 from the left-hand side and select when Yandex-
Translate1.GotTranslation do
• Click DestText from the left-hand side and select set DestText.Text to
● 34
Figure 3.13 shows an example run of the program on an Android mobile phone where the
English word large is translated into German.
3.8 Project 3 – F
ormatting the Layout of the Components –
Language Translation
Description: In Project 2 the components were placed under each other and there was
no way to change this layout. In this project, we will learn how to format the layout of the
components on the screen of the Android device. The project translates English words to
German as in the previous project.
Aim: This project aims to show how the layout of the components on the screen can be
formatted.
• Click Layout on the left-hand side and click, drag and drop HorizontalArrange-
ment to the Viewer, and configure it as follows:
AlignHorizontal: Center:3
AlignVertical: Center:2
Height: 5 percent
Width: Fill parent
● 35
FontBold: ticked
FontSize: 20
Text: English to German
AlignHorizontal: Center:3
AlignVertical: Center:2
Height: 10 percent
Width: Fill parent
• Place another HorizontalArrangement onto the Viewer with the following con-
figuration:
AlignHorizontal: Center:3
AlignVertical: Center:2
Height: 10 percent
Width: Fill parent
● 36
• Place a Button with its Text set to Click to Translate and a TextBox named
DestText on the HorizontalArrangement. Configure them as in the previous
project.
This completes the design of the project. The Block program of this project is the same as
the previous one and therefore is not repeated here. Compile the program and upload to
your Arduino device. The QR code of the project is shown in Figure 3.16.
Figure 3.17 shows an example run of the program on an Android mobile phone where the
English word book is translated into German.
Description: This is a simple text to speech project. When a button is clicked, the text
message Hello from the App Inventor is spoken on the Android device speaker.
Aim: This project aims to show how a text to speech program can be developed.
AlignHorizontal: Center:3
AlignVertical: Center:2
Height: 5 percent
Width: Fill parent
● 37
FontBold: ticked
Text: Text To Speech
AlignHorizontal: Center:3
AlignVertical: Center:2
Height: 10 percent
Width: Fill parent
FontBold: ticked
FontSize: 20
Text: Click to Listen
• Click Media and click, drag and drop the TextToSpeech onto the Viewer. This is
a hidden component and is only shown outside the phone image
• Click Blocks
• Click Text under Built-in and select Text String. Join this block to the end of
the previous block
• Enter the text Hello from the App Inventor inside the Text String
● 38
Build the program to get the QR code as shown in Figure 3.20. Scan and install the program
on your Android device. Click the button to listen to the text. Figure 3.21 shows the Android
screen for the project.
Description: This project is similar to the previous project. Here, the user enters text into
a textbox. When a button is clicked, the contents of the textbox is spoken on the Android
device speaker.
Aim: This project aims to show how any text message can be spoken on the Android device
speaker.
AlignHorizontal: Center:3
AlignVertical: Center:2
● 39
Height: 5 percent
Width: Fill parent
FontBold: ticked
Text: Text To Speech
AlignHorizontal: Left:1
AlignVertical: Center:2
Height: 10 percent
Width: Fill parent
FontBold: ticked
FontSize: 20
Text: Text:
FontBold: ticked
Hint: cleared
Text: cleared
AlignHorizontal: Center:3
AlignVertical: Center:2
Height: 10 percent
Width: Fill parent
FontBold: ticked
FontSize: 20
Text: Click to Listen
● 40
• Click Blocks
• Click TextBox1 on the left-hand side and select TextBox1.Text. Join this block
to the end of the previous block
Build the program to get the QR code as shown in Figure 3.24. Scan and install the program
on your Android device. Enter a text and click the button to listen to the text. Figure 3.25
shows the Android screen for the project.
● 41
Description: This project is similar to the previous project. Here, the user enters text in
English into a textbox. When a button is clicked, the contents of the textbox is translated
into German and is spoken on the Android device speaker.
Aim: This project aims to show how text to speech and translation can be combined in a
project.
Steps: The Designer of the project is the same as in Project 4 (see Figure 3.22), except
that here a YandexTranslate is placed onto the Viewer. This project is named as TTS3.
The steps for the design of the Block program are as follows:
• Click Blocks
• Click Button1 from the Palette on the left-hand side and select block when
Button1.Click do
• Click YandexTranslate1 from the Palette on the left-hand side and select call
YandexTranslate1.RequestTranslation. Join the two blocks as shown in Fig-
ure 3.9
• Click Text under Built-in and join it to the two blocks. This text will define that
the translation will be from English to German. Enter en-de inside this text.
So far we have translated the contents of TextBox1, but have not told the program to
speak the translated text. This can be done as follows:
• Click YandexTranslate1 from the left-hand side and select when Yandex-
Translate1.GotTranslation do
• Click TextToSpeech1 at the left hand side and select call TextToSpeech1.
Speak message
● 42
Build the program to get the QR code as shown in Figure 3.27. Scan and install the pro-
gram on your Android device. Enter a text in English, click the button to listen to the text
in German.
Description: In this project, the images of some objects are displayed on the Android
screen. The names of the objects are spoken when the user clicks on the objects.
Aim: This project aims to show how images can be displayed on the screen and how ac-
tions can be taken when these images are clicked.
In this project, we will be using images of 4 objects for demonstration purposes. The num-
ber of images can easily be extended if required. These images are icons in the form of JPG
files and are taken from the Internet. The following images are used in the project: car,
balloon, banana, apple.
● 43
AlignHorizontal: Center: 3
AlignVertical: Center: 2
Height: 20 percent
Width: Fill parent
Height: 15 percent
Width: 20 percent
Text: clear
• Click Upload File and browse and click on the apple image. Go to the Proper-
ties on the right-hand side for Button1, click Image, and select apple.jpg. You
should see an apple image displayed on the screen
Height: 15 percent
Width: 20 percent
Text: clear
• Click Upload File and browse and click on the banana image. Go to the Proper-
ties on the right-hand side for Button2, click Image, and select banana.jpg.
You should see a banana image displayed on the screen
Height: 15 percent
Width: 20 percent
Text: clear
• Click Upload File and browse and click on the balloon image. Go to the Prop-
erties on the right-hand side for Button3, click Image, and select baloon.jpg.
You should see a balloon image displayed on the screen
Height: 15 percent
Width: 25 percent
Text: clear
● 44
• Click Upload File and browse and click on the car image. Go to the Properties
on the right-hand side for Button4, click Image, and select car.jpg. You should
see a car image displayed on the screen
• Click, drag and drop a TextToSpeech onto the Viewer from the Media on the
left-hand side. This is hidden and will not show on the screen
• Click Blocks
• Click Text under Built-in and join it to the blocks. Set the text inside this block
to This is an apple
• Click Text under Built-in and join it to the blocks. Set the text inside this block
to This is a banana
• Click Text under Built-in and join it to the blocks. Set the text inside this block
to This is a balloon
● 45
• Click Text under Built-in and join it to the blocks. Set the text inside this block
to This is a car
Build the program to get the QR code as shown in Figure 3.30. Scan and install the program
on your Android device. Click on an image and you should hear the description of the image
through the speaker.
● 46
Description: In this project, the SMS messages received by the Android device are spoken
on the speaker.
Aim: This project aims to show how SMS messages can be received by the Android device
and also how these emails can be sent to the text-to-speech component of App Inventor.
The component Texting under the Social tab on the left-hand side of the screen is used
to send and receive SMS messages. When the SendMessage method is called, a text
message specified in the Message property will be sent to the phone number specified in
the PhoneNumber property. If the ReceivingEnabled property is set to 1, messages will
not be received. If ReceivingEnabled is set to 2 messages will be received only when the
application is running. Finally, if ReceivingEnabled is set to 3, messages will be received
when the application is running and when the application is not running they will be queued
and a notification displayed to the user. When a message arrives, the MessageReceived
event is raised and this provides both the phone number of the sender and the message
itself.
An app that includes the Texting component will receive messages even when it is in the
background (i.e. when it's not visible on the screen) and, even if the app is not running, so
long as it is installed on the phone. If the phone receives a text message when the app is
not in the foreground, the phone will show a notification in the notification bar. Selecting
the notification will bring up the app. An option can be given to the user such that receiving
an SMS message can be ignored.
• Place a HorizontalArrangement onto the Viewer and insert a Label onto this,
set the Title of this label to Speak the received Emails
• Place another HorizontalArrangement onto the Viewer and insert a Button onto
this, set the button Title to Click to Start, click the FontBold, and set the TextColor
to Red
● 47
• Drag and drop a Texting component from the Social tab. This will not be visible
on the phone image
• Drag and drop a TxtToSpeech component from the Media tab. This will not be
visible on the phone image
Now we have to do the Block programming. First of all, we have to initialize components
Texting and TextToSpeech. The Texting component must be enabled so that we can
receive emails. In this project, we will be setting the ReceivingEnabled parameter to 2.
We are also going to set the speech rate of the TextToSpeech component. Valid values
are 0, 1, 2. 0 is the slowest rate while 2 is the fastest rate. We will choose the speech rate
as 1 in this project.
• Click Blocks
• Click Math under Built-in and select the first block (the number block). Enter
number 2 into this block and join the blocks
• Click Math under Built-in and select the number block as before. Enter number
1 into this block and join the blocks as shown in Figure 3.33.
● 48
We now have to create the blocks to receive SMS messages and then to speak them on the
Android device's speaker. The steps are as follows:
• Click and drag the first block in Text under Built-in so that we can insert a text
message. Join this block to block Join and enter text Email received from
The block program of the project is complete as shown in Figure 3.34. When a new mes-
sage arrives, block when Texting1.MessageReceived will be activated. This block will
call the TextToSpeech block. The phone number of the sender and the received message
will be extracted from block Texting. The message Email received from will be spoken,
followed by the phone number of the sender and the received message.
Build the program to get the QR code as shown in Figure 3.35. Scan and install the program
on your Android device. Click the button to start the program. When the program is started,
you might be asked to allow the phone to send and view SMS messages, just click Allow.
The program can easily be tested by sending an SMS message from another phone.
● 49
Description: In this project, we will learn how to send an SMS message to another device.
Aim: This project aims to show how an SMS message can be sent using App Inventor.
The steps are as follows:
• Place a HorizontalArrangement onto the Viewer and insert a Label onto this,
set the Text of this label to SEND SMS
• Insert another HorizontalArrangement and drop a Button. Set the Text of the
Button to Click to Send, and its FontColor to Red
● 50
We now have to create the blocks to send SMS messages. The steps are as follows:
• Click TxtNumber and select TxtNumber.Text and join to the previous block
• Click TxtMessage and select TxtMessage.Text and join to the previous blocks
The block program of the project is complete as shown in Figure 3.37. When the button is
clicked, the phone number and the message entered by the user are copied to component
Texting1. Then the message is sent to the specified phone number.
Build the program to get the QR code as shown in Figure 3.38. Scan and install the program
on your Android device. Enter the phone number and the message and then click the button
to send the SMS message. Note that you can send a message to your phone for testing.
Figure 3.39 shows the Android phone screen running the project.
● 51
3.15 Project 10 – R
eading a Message and Sending a Reply Message
Automatically when Busy
Description: Sometimes it may not be safe to read and reply to an SMS message. For
example, it is not safe to read or answer an SMS message while driving. Also, we may not
want to reply to an SMS message when we are busy. In this project, the received SMS mes-
sage is spoken on the Android device speaker, and the message Sorry, I am busy now, I
will reply later is sent back to the sender automatically.
Aim: This project aims to show how to receive and reply to an SMS message automatically
using App Inventor.
The design of the project is very simple and the steps are as follows:
• Place a HorizontalArrangement onto the Viewer and insert a Label onto this,
set the Text of this label to Read SMS and Reply Busy
• Drag and drop a TextToSpeech and a Texting component. These are not shown
on the phone image
We now have to design the Block program of the project. The initialization part of the block
program is the same as in Project 7 where Texting is enabled to receive messages and the
speech rate of TextToSpeech is set to 1. The remaining steps are again similar to the ones
given in Project 7, but the following changes are made:
• The phone number of the sender is stored using block set Texting1.Phone-
Number to
• The message Sorry, I am busy now, I will reply later is stored in block set
Texting1.Message to
● 52
Build the program to get the QR code as shown in Figure 3.41. Scan and install the program
on your Android device. Click the button to start the program. When the program is started,
you might be asked to allow the phone to send and view SMS messages, just click Allow.
The program waits until it receives an SMS. The received message is spoken on the Android
device speaker and then the message Sorry, I am busy now, I will reply later is sent
to the sender automatically.
Description: In this project, the received SMS message and the phone number of the
sender are displayed in text boxes.
Aim: This project aims to show how the displayed SMS messages and the phone numbers
of the senders can be displayed on the Android device screen.
The design of the project is very simple and the steps are as follows:
● 53
• Click Screen1 on the left-hand side and select when Screen1.Initialize do.
This block will be activated as soon as the program is started on the Android
device
Build the program to get the QR code as shown in Figure 3.44. Scan and install the pro-
gram on your Android device. Send an SMS to your mobile device from another device. You
should see the phone number and the message displayed on your Android device.
Figure 3.45 shows a message received on the Android mobile phone (part of the phone
number is masked for security).
● 54
Description: In this project, we will call to a fixed telephone number from our Android
mobile phone. In this project, the program calls to number: 07860295594.
Aim: This project aims to show how we can make a call using App Inventor software.
The design of the project is very simple and the steps are as follows:
• Click tab Social on the left-hand side and click and drop component PhoneCall
onto the Viewer. This is a hidden component. This completes the design of the
project.
The steps to design the Block program are as follows. Here, we have to use the component
PhoneCall of App Inventor to call the number when the button is clicked:
• Click the top text block under Built-in and join the blocks as shown in Figure
3.47.
● 55
This completes the block program of the project. Notice that there are two blocks for mak-
ing a call: MakePhoneCall and MakePhoneCallDirect. In the first case, the user must
press the call button on the Android mobile phone to make a call, while in the second case
the call is made directly without having to press the call button.
Build the program to get the QR code as shown in Figure 3.48 Scan and install the program
on your Android device and call the fixed number to test it.
Description: In this project, we will call to 3 fixed telephone numbers from our Android
mobile phone.
Aim: This project aims to show how we can call to several fixed phone numbers.
● 56
The block program consists of 3 groups of blocks (see Figure 3.50), one group for mother,
one group for father, and one group for sister. Each block is configured to store the tele-
phone number of the corresponding person. The structures of the blocks are similar to the
ones given in the previous project and are not repeated here.
Build the program to get the QR code as shown in Figure 3.51. Scan and install the program
on your Android device. Start the program on your Android mobile phone and test it by
calling the fixed numbers.
Figure 3.52 shows a snapshot of the application on the Android mobile phone.
● 57
Description: In this project, we will call a number by selecting it from the Contacts list of
your mobile phone.
Aim: This project aims to show how we can choose a number from the Contacts list and
then dial the chosen number using App Inventor.
• Click Social and insert a PhoneCall component onto the phone image. This will
not be visible as was described earlier
The block program is shown in Figure 3.54 and the steps are as follows:
● 58
Build the program to get the QR code as shown in Figure 3.55. Scan and install the program
on your Android device. Start the program on your Android mobile phone and test it by
calling a number from the Contacts list.
Description: In this project when a button is clicked the camera view opens and the user
is requested to take a picture by pressing the camera shutter. After the picture is saved,
the message The photo has been taken successfully is spoken on the speaker and the
taken photo is displayed on the Android device's screen.
Aim: This project aims to show how we can take pictures using App Inventor.
In this application, we will be using a new component called Camera.
● 59
• Click User Interface and insert an Image component onto the Viewer. This
image component will show the photo taken
• Click Media and insert components Camera and TextToSpeech onto the View-
er. Both of these components are not visible
Figure 3.56 shows the design of the project on the phone image.
The block program is shown in Figure 3.57 and the steps are as follows:
• At this point when the button is clicked the camera view will be opened and a
photo will be taken when the camera shutter is clicked
• We now need another group of blocks that will show the taken photo and also
speak the message The photo has been taken successfully
• Click Text under Built-in and select the first block. Enter text The photo has
been taken successfully
● 60
Build the program to get the QR code as shown in Figure 3.58. Scan and install the pro-
gram on your Android device. Start the program on your Android mobile phone and click
the button to see the camera view. Click the shutter to take a picture and then save it. The
screen will return to the opening screen where the picture will be displayed by the Image
component.
Figure 3.59 shows a snapshot of the Android phone screen after a picture is taken. Notice
that you can change the dimensions of the picture during the design phase of the project.
Description: In this project, we design a one-octave basic piano with 8 musical notes from
C3 to C4. 8 buttons are used in the design where each button represents a musical note.
Aim: This project aims to show how sound can be generated using App Inventor.
● 61
In this application, we will be using two new components called Sound and Player. Com-
ponent Sound is set to a musical note file (e.g. c3.mp3, or to any other sound file), and
component Player plays the selected note (or sound).
Text Name
C ButtonC1 (lower C)
D ButtonD
E ButtonE
F ButtonF
G ButtonG
A ButtonA
B ButtonB
C ButtonC2 (upper C)
• Click Media and insert components Player and Media onto the phone image.
These are hidden components
• Click Upload File at the bottom right-hand side and upload all the 8 musical note
files in either mp3 or wav format. In this project, the musical note files are in
mp3 format and they were taken from the web site: https://freeSound.org. The
filenames were made shorter so that they are easier to manipulate and they were
given the names: c3.mp3, d3.mp3, e3.mp3, f3.mp3, g3.mp3, a3.mp3, b3.mp3,
c4.mp3 as shown in Figure 3.61.
● 62
The block program is shown in Figure 3.62 and it consists of a screen initialization block and
a group of 8 similar blocks, one group for each note. Only the initialization block and one of
the note blocks are described here.
• Click Screen1 and select when Screen1.Initialize do. This block will be acti-
vated when the application is started on the Android device
● 63
• Click Math under Built-in and select the first block to enter a number. Join this
block to the previous one and set it to 1. MinimumInterval is in milliseconds
and it is the maximum time between two sounds. In this example, we have set it
to 1 millisecond so that the sounds are short when buttons are clicked
• Click ButtonC1 and select when Button1.Click do. This block will be activated
when ButtonC1 is clicked
• Click Sound1 and select set Sound1.Source to. Click Text under Built-in and
select the first block to enter text. Enter the name of the mp3 sound file that
corresponds to musical note C lower (c3.mp3)
• Click Player1 and select call Sound1.Play so that the program plays the se-
lected musical note
Build the program to get the QR code as shown in Figure 3.63. Scan and install the program
on your Android device. Start the program on your Android mobile phone and start playing
with the musical notes.
● 64
Figure 3.64 shows a snapshot of the Android phone with the application running.
Description: Android compatible devices have built-in accelerometer modules. In this pro-
ject, we will display the acceleration vectors on the screen in 3 dimensions as the Android
device is moved or shaken. Additionally, the magnitude of the acceleration vector will be
displayed. Just to remind readers, the magnitude vector is given by the square root of the
sum of the squares of vectors in each direction.
Aim: This project aims to show how the built-in accelerometer can be used in App Inventor
projects.
● 65
The block program is shown in Figure 3.66. The steps are as follows:
• Click Variables under Built-in and select Initialize global name to. Change
the name to M. This variable will store the magnitude of the acceleration
• We now have the acceleration in all three dimensions. The next step is to calcu-
late the magnitude of the acceleration
● 66
• At this point, variable M is equal to the square root of the sum of the squares of
the three acceleration vectors. i.e. M = sqrt(x2 + y2 z2)
Build the program to get the QR code as shown in Figure 3.67. Scan and install the program
on your Android device. Start the program on your Android mobile device and you should
see the acceleration in three dimensions as shown in Figure 3.68.
● 67
Description: Android mobile devices have built-in light level sensors. This project meas-
ures the ambient light level and displays it in lux on the screen. If the light level is less
than 20 lux than the message Light Level too LOW to study! is displayed, otherwise, the
message Light Level good to study is displayed
Aim: This project aims to show how the built-in light level sensor can be used in App In-
ventor projects.
This project uses the LightSensor component under the Sensors tab.
● 68
The block program is shown in Figure 3.70. The steps are as follows:
• Click on Math and select the block with = sign in it. Change the = sign to < sign
• Click Math and insert the first block to enter a number. Enter number 20 as
shown in the figure
• Click Text and insert the first block to enter text. Enter text Light Level too
LOW to study!. This block will be executed if the light level is less than 20 lux,
otherwise, the next block under else will be executed
• Click Text and insert the first block to enter text. Enter text Light Level good
to study
Build the program to get the QR code as shown in Figure 3.71. Scan and install the program
on your Android device. Start the program on your Android mobile device and you should
see the light level displayed in lux together with the suggestion of whether or not there is
enough light to study.
● 69
3.24 Project 19 – G
lobal Positioning System – Latitude, Longitude, Altitude,
and Speed
Description: Android mobile devices have built-in GPS modules. In this project, we use
the GPS module to extract the geographical co-ordinates of our position. Additionally, we
extract the altitude and the speed and display them on the Android device screen.
Aim: This project aims to show how the built-in GPS module can be used in App Inventor
projects.
This project uses the component called LocationSensor under the Sensors tab. In addi-
tion to the latitude, longitude, and altitude, we can also extract the speed of travel and the
name of the provider (e.g. GPS).
Label TextBox
Latitude: TxtLatitude
Longitude: TxtLongitude
Altitude: TxtAltitude
Speed: TxtSpeed
Provider: TxtProvider
● 70
• Click the Sensors tab and insert a LocationSensor component onto the Viewer.
This is a hidden component.
The block program is shown in Figure 3.74. The steps are as follows:
• Click on Math and select the top block to enter a number. Enter 1000. The
TimeInterval is the frequency of updating the GPS data in milliseconds. In this
example, we have set this parameter to 1000ms (1 second)
• Repeat the above steps for the longitude, altitude, and speed
● 71
Build the program to get the QR code as shown in Figure 3.75. Scan and install the program
on your Android device. Start the program on your Android mobile device and you should
see the latitude, longitude, altitude, and speed displayed on the Android device. The pro-
vider is displayed as GPS.
Description: In this project, the latitude and longitude of your position will be extracted
from the GPS module and then your position will be marked on a map.
Aim: This project aims to show how a point whose latitude and longitude are known can be
pinpointed on a map using App Inventor.
As in the previous project, this project uses the components called LocationSensor and
WebViewer. A point whose latitude and longitude are known can be pinpointed on a map
by using the following URL (for further information, see the Google map URL developer
guide at https://developers.google.com/maps/documentation/urls/guide):
https://www.google.com/maps/search/?api=1pquery=latitude,longitude
In this project, we will extract the latitude and longitude of our current position and then
create the above URL. The URL will then be submitted to the WebViewer to pin-point and
display our position on a map. Notice that in the Northern hemisphere latitude is positive,
● 72
and it is negative in the southern hemisphere. Also, the longitude is positive at the East of
longitude 0, and negative at the West of longitude 0.
The block program is shown in Figure 3.78. The steps are as follows:
• Click Variables and select Initialize global name to, set the name to URL.
This variable will be used to store the URL
• Insert an empty Text block and join to the previous block as in the Figure
• Insert blocks to extract the latitude and the longitude as in the previous project
• Click Button1 and select when Button1.Click do. This block will be executed
when the button is clicked
• Click Variables and select set-to. Set the name to global URL
• Click Text under Built-in and select the block called Join. The Join block by
default has two connectors, but we need four connectors. Click on the star sign
in block Join and click and move a string block under the existing blocks to in-
crease the connectors to four
● 73
• We now have to add the latitude to the URL. Click TxtLatitude and select Txt-
Latitude.Text
• We now have to insert a comma. Insert a Text and enter a comma inside this
Text
• We now have to add the longitude to the URL. Click TxtLongitude and select
TxtLongitude.Text
• The URL now contains all the fields. Sending this URL to a web browser will dis-
play a map and pinpoint our position on the map. Click WebViewer1 and select
call WebViewer1.GoToUrl
• Click Variables and select get, click to select name global URL as shown in the
Figure
Build the program to get the QR code as shown in Figure 3.79. Scan and install the program
on your Android device. Start the program on your Android mobile device and you should
see the latitude and longitude displayed on the Android device. Click the button to see your
position pin-pointed on a map
● 74
Aim: This project aims to show how the current time can be displayed and set if required
using App Inventor.
• Click component TimePicker under User Interface and place it on the Horizon-
talArrangement (see Figure 3.81)
● 75
FontBold: ticked
FontSize: 20
Text: DISPLAY/SET TIME
Build the program to get the QR code as shown in Figure 3.83. Scan and install the program
on your Android device. Start the program on your Android mobile device and you should
see the current time displayed as shown in Figure 3.84. You can change the time if you wish
to use the controls displayed on the screen.
● 76
Note: The DatePicker component can be used to display/set the current date
Description: This project is used to record and play sound. Two buttons are used to start
and stop the recording. Clicking the other button plays the recorded sound.
Aim: This project aims to show how sound can be recorded using App Inventor.
This project uses the components called SoundRecorder and Player inside the Media tab
The steps are:
Initially, the font colours of the buttons are all set to be black. The recording starts when
ButtonStart is clicked and its colour changes to red. The recording stops when Button-
Stop is clicked and the colour of ButtonStart changes back to black. Clicking Button-
StartPlay starts playing the recorded sound and the button colour changes to green. Click-
ing ButtonStopPlay stops playing the recorded sound and the ButtonStartPlay colour
changes back to black.
● 77
• Click the Media tab and insert components Player and SoundRecorder. Both
of these components are hidden
The block program is shown in Figure 3.86. When ButtonStart is clicked, we change the
colour of this button to red and insert block call SoundRecorder1.Start to start the re-
cording. Clicking ButtonStop activates the second group of blocks where the ButtonStart
colour is changed back to black and call SoundRecorder1.Stop is called to stop recording.
After the sound recording terminates, the third group of blocks is activated where the re-
corded sound is stored in Player1.Source. Clicking ButtonStartPlay activated the fourth
group of blocks where the colour of the button changes to green and the recorded sound
is played back. Finally, clicking ButtonStopPlay changes the colour of ButtonStartPlay
back to black and stops the playback.
Note: You may get an error on your Android device saying that permission is required to
write to external storage. This permission can be given as follows:
• Click Settings
• Click Apps
● 78
• Click Permissions
• Click Storage
Description: This is an interesting project. The project recognizes words and sentences in
English and translates and speaks them in German.
Aim: This project aims to show how the speech recognizer can be used with App Inventor.
This project uses the components called SpeechRecognizer, YandexTranslate, and
TextToSpeech inside the Media tab
● 79
Figure 3.88 shows the block program of the project. The steps are:
• Initialize two variables called speech and trans. speech will store the speech in
English and trans will store the translated speech in German.
• At the end of the speech we have to store the spoken message. Click
SpeechRecognizer1 and select when SpeechRecognizer1.AfterGetting-
Text do
• Set variable speech to the result, i.e. the spoken message. So far we have
stored the spoken message in variable speech.
• Now, we have to translate the speech into German. Click ButtonTranslate and
select when ButtonTranslate1.Click do
• Now, we have to get the translated message and speak it through the speaker.
Click YandexTranslate1 and select when YandexTranslate1.GetTranslation
do
• Click TextToSpeech and select call TextToSpeech1.Speak and set the mes-
sage to variable trans so that the contents of trans is spoken
● 80
Build the program to get the QR code as shown in Figure 3.89. Scan and install the program
on your Android device. Start the program on your Android mobile device. Click button
CLICK TO START and speak something in English. Click button CLICK TO TRANSLATE to
hear the spoken message in German.
Description: This is a chronograph project which counts in seconds and displays the count
on the screen. 3 buttons are provided: Clicking START starts counting up, clicking STOP
stops counting, and clicking CLEAR stops counting and clears the displayed count so that
the chronograph can be re-started.
Aim: The aim of this project is to show how a simple chronograph can be designed using
App Inventor
This project uses the component called Clock inside the Sensors tab
● 81
• Click Sensor tab and insert a Clock component. This component is not visible
Figure 3.91 shows the block program of the project. The steps are:
• Click Screen1 and select when Screen1.Initialize do. Disable the timer when
the application is started. Click Clock1 and select set Clock1.TimerEnabled to
• Insert a ButtonStart block and set the time interval to 1000ms (1 second). The
timer is enabled when this button is clicked. The timer
• Insert a ButtonStop block and disable the timer when this button is clicked
• Insert a ButtonClear block and disable the timer and clear the count in TextBox
TxtSecs
• Click Clock1 and select when Clock1.Timer do. This block is activated every
time the timer interval is reached i.e. every second in this project
● 82
• Click Math and insert an addition block. Insert TxtSecs.Text and number 1
(the first block in Math) to the addition block. The value of TxtSecs.Text will
be incremented by one every time the timer expires
Build the program to get the QR code as shown in Figure 3.92. Scan and install the program
on your Android device. Start the program on your Android mobile device. Click button
START to start the chronograph. You should see the count incrementing every second.
Click STOP to stop he counting, and CLEAR to clear the count.
● 83
Description: This is a seconds down counter project. The user enters a number and clicks
the START button. The project counts down every second and when it reaches 0 a bell
sound is output to indicate that the count stopped.
Aim: This project aims to show how a simple seconds down counter can be designed using
App Inventor
This project uses the component called Clock inside the Sensors tab
• Click Media tab and insert a Sound component. Also, click Sensors tab and
insert a Clock component
Figure 3.95 shows the block program of the project. The steps are:
• When the value of TxtSecs.Text is 0, play the short bell sound to indicate that
the count is 0. At the same time, disable the timer. In this project, the short bell
sound named 96521__kleinhirn2000__reception-bell1.mp3 is used (you
can choose your sound to be activated at the end of counting. You can also dis-
play an image when the count terminates)
● 84
Build the program to get the QR code as shown in Figure 3.96. Scan and install the pro-
gram on your Android device. Start the program on your Android mobile device and enter
a number into the TextBox. Click button START to start counting down. When the count
reaches 0 the counting stops and you should hear a short bell sound.
Figure 3.97 shows a snapshot of the application on the Android mobile phone.
3.31 Summary
In this chapter, we developed many projects and learned how to use some of the key
features of App Inventor on an Android device. In the next chapter, we will develop App
Inventor projects using mathematical operations.
● 85
4.1 Overview
In the last chapter, we developed projects and have learned many features of App Inventor.
Mathematical operations are important in many scientific and engineering applications. In
this chapter, we will develop further projects using the mathematical operations of App In-
ventor. Additionally, other important features of App Inventor are described. Note that the
QR codes given in the projects were valid only for 2 hours at the time they were created,
and they cannot be used to install the apps to your mobile phone. They are only given here
for completeness..
It is assumed that readers are familiar with using the components and blocks described in
the previous chapter as detailed steps of the designs will not be given in this chapter.
Description: This project calculates and displays the area of a triangle given its base and
height.
Aim: This project aims to show how multiplication can be performed using App Inventor
Steps are as follows:
• In this project, the base (TxtBase), height (TxtHeight), and the area (TxtAr-
ea) of the triangle are configured as TextBoxes as shown in Figure 4.1
The block program is shown in Figure 4.2. We have to multiply TxtBase with TxtHeight
and with 0.5. Then, the result must be stored in TxtArea. We need a multiplication block
that can multiply 3 numbers. Click Math and select a multiplication block with 2 inputs.
Click on the star at the top left corner of this block and move the number at the top left
corner to the bottom of the two other numbers. The result will be a multiplication block with
3 numbers as shown in Figure 4.3
● 86
Figure 4.5 shows a snapshot of the Android mobile running the application.
● 87
Description: This project gives the user a choice to calculate and displays the areas of a
square, rectangle, or triangle. The lengths of the sides of the shapes are entered in Text-
Boxes on the screen.
Aim: This project aims to show how checkboxes can be used in App Inventor based pro-
jects.
The following data is required to be entered for each shape:
● 88
Figure 4.7 shows the block program of the project. The steps are:
• Click ChkSquare and select when ChkSquare1Changed do. This block will be
activated when checkbox ChkSquare is clicked
• Insert a conditional block and if the checkbox is checked (i.e if it is true) then
set TxtArea to TxtSquare x TxtSquarea so that the area is displayed on the
screen
• When the button CLICK TO CLEAR is clicked, we want to clear all the check-
boxes and the textboxes on the screen. This is shown on the right-hand side of
Figure 4.6 where all the text boxes are cleared and also the Checked state of all
the checkboxes are set false
Build the application to generate the QR code (Figure 4.8) and download the application to
your Android device. As an example, let us calculate the area of a triangle whose base is 10
units and the height is 5 units. Start the application, enter 10 and 5 into the TextBoxes after
b= and h= respectively. Click checkbox Triangle and you should see the area displayed as
shown in Figure 4.9
● 89
Description: This project finds the real roots of a quadratic equation and displays them
on the screen.
Aim: This project aims to show how the real roots of a quadratic equation can be found
using App Inventor.
Give the quadratic equation: ax2 + bx + c = 0, the roots are given by the well-known for-
mula:
In this project, coefficients a, b, c will be read from a TextBox and the program will use
Math functions to calculate the roots of the equation.
• Insert a TableArrangement having 4 columns and 3 rows and enter the follow-
ing components on it (Figure 4.10):
● 90
Figure 4.11 shows the block program of the project. The steps are:
• Initialize a variable called det. This variable will store the result of the square
root in the formula
• Insert a block that will be activated when ButtonCalc (Calculate) is clicked. Set
det to be equal to . If det is greater than or equal to 0 then the equation
has real roots.
• If det is less than 0 then the equation has complex roots and the message Com-
plex roots is displayed in TxtRoot1 and TxtRoot2.
● 91
• When the TxtClear button (Clear) is clicked, clear all the TextBoxes as shown
in Figure 4.11.
The QR code of the project is shown in Figure 4.12. A sample run of the program on an
Android mobile phone is shown in Figure 4.13.
● 92
Description: This project generates two random integer numbers between 1 and 6 when
the mobile device is shaken. The numbers generated are displayed as dice numbers on the
screen.
Aim: This project aims to show how random numbers can be generated using App Inven-
tor.
The AccelerometerSensor is used in this project to detect when the Android device is
shaken. In this project, the application is identified with a dice image as shown in Figure
4.14.
• Upload the image dice.jpg. Click Screen1 and click on Icon. Select image dice.
jpg. This image identifies the application.
● 93
Figure 4.16 shows the block program of the project. The steps are:
• Click Math and select block random integer from 1 to 6. His block will generate
a random integer number between 1 and 6
• Repeat for TxtDice2
The QR code of the project is shown in Figure 4.17. Run the program and shake the Android
device. You should see two dice numbers displayed on the screen as shown in Figure 4.18.
Description: In this project, two random numbers are generated between 1 and 100 when
the button START is clicked, and the user is requested to calculate their product. Clicking
the answer button checks the answer and displays either CORRECT or WRONG. If the an-
swer is wrong, the correct answer is also displayed. Clicking the CLEAR button clears the
entries on the mobile device screen.
Aim: This project aims to show how random numbers can be generated using App Inventor.
● 94
The design of the project is shown in Figure 4.19. Three HorizontalArrangments are
inserted on the Viewer with the following components:
Figure 4.20 shows the block program of the project. The steps are:
• Initialize 3 variables called no1, no2, and no3. no1 and no2 will store the mul-
tiplier and the multiplicand, and no3 will store the result of the multiplication
• When the Answer button is clicked, the value entered by the user (TxtAnswer.
Text) is compared with the correct answer in no3. If the user's answer is correct
then message CORRECT is displayed, otherwise the message WRONG. Correct
answer is: nnn is displayed.
• Clicking the Clear button clears all the entries on the screen
● 95
The QR code of the project is shown in Figure 4.21. An example run of the program is
shown in Figure 4.22.
Description: In this project the trigonometric functions sine, cosine, and tangent are dis-
played in the form of a table for the angles from 0 to 45 in steps of 5 degrees.
Aim: This project aims to show how the trigonometric functions can be used with App
Inventor
● 96
AlignHorizontal: Center: 3
AlignVertical: Top: 1
Height: 30 percent
Width: Fill parent
Figure 4.24 shows the block program of the project. The steps are:
● 97
Figure 4.25 shows the QR code of the project. A sample run of the program is shown in
Figure 4.26.
Description: This project displays the time table for a given number. The table displays
the results of multiplying the given number with 1, 2, 3, up to 12.
Aim: This project aims to show how a time table can be created using App Inventor.
The steps are:
● 98
• Insert a Label named TxtTable with its FontBold ticked and FontSize set to
20. This Label will store the time table elements
Figure 4.28 shows the block program of the project. The steps are:
• Insert a block that will be activated when ButtonStart is clicked. Store the re-
quired time table number in variable multiplier
• Insert a loop block with variable number, and configure it to run from 1 to 12
in steps of 1
• Store the result of multiplying number with the multiplier in variable result
• Insert a Join block and store the multiplicand, multiplier, X sign, and = sign
in variable multtable. Insert a new-line character at the end of every line
• Insert a block that will be activated when ButtonClear is clicked. Clear TxtTa-
blefor.Text and TxtTable.Text when this button is clicked
● 99
Figure 4.29 shows the QR code of the project. A sample run of the program is shown in
Figure 4.30.
Using a Procedure
Procedures are useful when certain blocks of operations are to be repeated several times in
a program. A complex program can also be broken down into manageable sections in the
form of functions and these functions can be tested on their own.
Functions in App Inventor are called Procedures and they can be created using the Proce-
dures block under Built-in. As an example, the block program given in Figure 4.28 can be
● 100
modified such that the sections of the program after the loop can be executed as a proce-
dure. The steps are as follows (see Figure 4.31, program times2):
• Separate the block diagram in Figure 4.28 into two groups where the second
group starts with the loop.
• Click Procedures under Built-in and select to procedure do. Change the name
of the procedure to Times.
• Click Procedures and select call Times. Join this block to the end of the first
group of blocks
• The first group of blocks now calls procedure Times which is the second group
of blocks
4.9 Summary
In this chapter, we learned how to use important mathematical and logical operations in
App Inventor projects. In the next chapter, we will develop App Inventor projects using
Raspberry Pi.
● 101
5.1 Overview
Raspberry Pi has recently become one of the most popular and powerful single-board com-
puters used by students, hobbyists, and professional engineers. Raspberry Pi 4 is the latest
and the most powerful version of the Raspberry Pi. In this chapter, we will look at the basic
specifications and requirements of Raspberry Pi 4 computer and also learn how to install
the latest operating system, Raspbian Buster, on a blank SD card.
Figure 5.1 shows a Raspberry Pi 4 board with its major components identified.
● 102
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.
• Power supply
• Micro SD card
• Operating system software
● 103
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 5.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.
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
● 104
the CPU can go as high as 80 degrees Centigrade. Using a fan (see Figure 5.3) makes the
CPU more efficient as it can lower its temperature by about 50%.
● 105
• 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 5.6). 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/
● 106
• Put your blank micro SD card into the card slot on your computer. You may need
to use an adapter to do this
• Download the Etcher program on your PC to flash the disk image. The link is (see
Figure 5.7):
https://www.balena.io/etcher/
• Double click to Open Etcher, and click Select image. Select the Raspbian Buster
file you just downloaded.
● 107
• Click Flash (see Figure 5.8). 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.
• Connect your Raspberry Pi 4 to an HDMI monitor (you may need to use an adapt-
er 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 5.9)
● 108
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
programs 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 An-
droid 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
addition to the IP address, other parameters such as the MAC address, gateway address, IP
mask, etc are all displayed by this program.
Go to the configuration menu and select Interface Options. Go down to P2 SSH (see
Figure 5.10) and enable SSH. Click <Finish> to exit the menu.
● 109
You should also enable VNC so that the 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.
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 5.11). The message shown
in Figure 5.12 will be displayed the first time you access the Raspberry Pi. Click Yes to
accept this security alert.
● 110
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.
● 111
• 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 the Putty, select the saved session and click Load followed
by Open to start a session with the saved configuration
● 112
The steps to install and use the VNC Viewer onto your PC are given below:
• There are many VNC Viewers available, but the recommended one is the Tight-
VNC which can be downloaded from the following web site:
https://www.tightvnc.com/download.php
• Download and install the TightVNC software for your PC. You will have to choose
a password during the installation.
• Start the TightVNC Viewer on your PC and enter the Raspberry Pi IP address
(see Figure 5.13) followed by:1. Click Connect to connect to your Raspberry Pi.
● 113
In this book, we will be using Python 3 in all of the Raspberry Pi-based projects.
• At the command prompt enter python3. You should see the Python command
mode which is identified by three characters >>>
• The required text will be displayed interactively on the screen as shown in Figure
5.16
Notice that by default, entering command python invokes version 2.7. If you wish to use
version 3.7 then you should enter the command python3 instead.
● 114
Some notes are given in this section on using the nano text editor.
You should see the editor screen as in Figure 5.18. The name of the file to be edited is
written at the top middle part of the screen. The message "New File" at the bottom of the
screen shows that this is a newly created file. The shortcuts at the bottom of the screen are
there to perform various editing functions. These shortcuts are accessed by pressing the
Ctrl key together with another key. Some of the useful shortcuts are given below:
Ctrl+J: Justify
● 115
● 116
Step 2: Look for word simple by pressing Ctrl+W and then typing simple in the window
opened at the bottom left-hand corner of the screen. Press the Enter key. The cursor will
be positioned on the word simple (see Figure 5.20).
Step 3: Cut the first line by placing the cursor anywhere on the line and then pressing
Ctrl+K. The first line will disappear as in Figure 5.21.
Step 4: Paste the line cut after the first line. Place the cursor on the second line and press
Ctrl+U (see Figure 5.22).
● 117
Step 5: Place cursor at the beginning of the word simple in the first row. Enter Ctrl+C.
The row and column positions of this word will be displayed at the bottom of the screen
(Figure 5.23).
Step 6: Press Ctrl+G to display the help page as in Figure 5.24. Notice that the display is
many pages long and you can jump to the next pages by pressing Ctrl+Y or to the previous
pages by pressing Ctrl+V. Press Ctrl+X to exit the help page.
● 118
Step 7: Replace word example with word file. Press Ctrl+\ and type the first word as the
example (see Figure 5.25). Press Enter and then type the replacement word as file. Press
Enter and accept the change by typing y.
Step 8: Save the changes. Press Ctrl+X to exit the file. Type Y to accept the saving, then
enter the filename to be written to, or simply press Enter to write to the existing file (first.
txt in this example). The file will be saved in your current working directory.
pi@raspberrypi ~ $
In summary, nano is a simple and yet powerful text editor allowing us to create new text
files or to edit existing files.
5.8.3 Method 3 – Create a Python File in GUI mode – Using the Thonny
In this method, we will log in to our Raspberry Pi 4 using the VNC and create and run our
program in GUI mode on the Desktop. The steps are given below:
• Click Programming and then click Thonny Python IDE (see Figure 5.26)
● 119
• Type in your program as shown in Figure 5.27 and save it e.g. with the name
hello2
• Run the program by clicking Run. You should see the program output displayed
at the bottom part of the screen as shown in Figure 5.28.
Thonny is based on Python 3 (not available for Python 2). Several icons are given at the
top of the Thonny screen to manage some of the menu items quickly. Thonny screen offers
the following menu options:
● 120
File: Used to save a file, open an existing file, rename a file, or print a file.
Edit: Used to edit the existing file. Submenu options are items like cut, paste, toggle, se-
lect, find and replace, etc.
View: this menu includes items such as exception, files, heap, help, notes, shell, variables,
font size, etc.
Run: This menu option is used to run or debug the existing file
Device: This menu option includes items: soft reboot, upload current script as main or as
boot script, show device's not script, etc.
Tools: This menu option includes: manage packages, open system shell, open Thonny
program folder, manage plug-ins, etc.
Help: This is the help menu which includes items such as: help contents, version history,
reporting problems, and about Thonny.
There are many project-based books on using Python to access peripheral devices connect-
ed to Raspberry Pi. Interested readers can search the Elektor web site, Google, or Amazon
for articles and books in this field. The author has the following publications on this topic:
Before going into the details of the hardware interface, it is worthwhile to look at the Rasp-
berry Pi 4 GPIO connector. This is a 40-pin dual-in-line 2.54mm wide connector as shown
in Figure 5.29.
● 121
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 3 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 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.
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.
● 122
If you get an error while trying to import the GPIO library then it is possible that the library
is not installed. Enter the following commands while in the command mode (identified by
the prompt pi@raspberrypi:~ $) to install the GPIO library (characters that should be
entered by you are in bold):
The GPIO provides several useful functions. Some of the available functions are given in
the next sections
Pin Numbering
There are two ways that we can refer to the GPIO pins. The first is using the BOARD num-
bering, where the pin numbers on the GPIO connector of the Raspberry Pi 4 are used. Enter
the following statement to use the BOARD method:
GPIO.setmode(GPIO.BOARD)
The second numbering system, also known as the BCM method is the preferred method
and it uses the channel numbers allocated to the pins. This method requires that you know
which channel number refers to which pin on the board. In this book, we shall be using this
second method. Enter the following statement to use the BCM method:
GPIO.setmode(GPIO.BCM)
The GPIO is a 40 pin header, mounted at one side of the board. Appendix A shows the
Raspberry Pi 4 GPIO pin configuration.
Input Configuration
You need to configure the channels (or port pins) you are using whether they are input or
output channels. The following statement is used to configure a channel as an input. Here,
channel refers to the channel number based on the setmode statement above:
GPIO.setup(channel, GPIO.IN)
● 123
When there is nothing connected to an input pin, the data at this input is not defined. We
can specify additional parameters with the input configuration statement to connect pull-up
or pull-down resistors by software to an input pin. The required statements are:
For pull-down:
For pull-up:
We can detect an edge change of an input signal at an input pin. Edge change is when
the signal changes from LOW to HIGH (rising edge), or from HIGH to LOW (falling edge).
For example, pressing a push-button switch can cause an edge change at the input of a
pin. The following statements can be used to wait for an edge of the input signal. These
are blocking functions. i.e. the program will wait until the specified edge is detected at the
input signal. For example, if this is a push-button, the program will wait until the button is
pressed:
GPIO.wait_for_edge(channel, GPIO.RISING)
GPIO.wait_for_edge(channel, GPIO.FALLING)
We can also wait until either a rising or a falling edge is detected by using the following
statement:
GPIO.wait_for_edge(channel, GPIO.BOTH)
We can use event detection function with an input pin. This way, we can execute the event
detection code whenever an event is detected. Events can be rising edge, falling edge, or
change in either edge of the signal. Event detection is usually used in loops where we can
check for the event while executing other code.
GPIO.add_event_detect(channel, GPIO.RISING)
● 124
We can check whether or not the event occurred by the following statement:
If GPIO.event_detected(channel):
……………………………
……………………………
GPIO.remove_event_detect(channel)
We can also use interrupt facilities (or callbacks) to detect events. Here, the event is han-
dled inside a user function. The main program carries on its usual duties and as soon as
the event occurs the program stops whatever it is doing and jumps to the event handling
function. For example, the following statement can be used to add interrupt based event
handling to our programs on rising edge of an input signal. In this example, the event han-
dling code is the function named MyHandler:
def MyHandler(channel):
………………….
………………….
We can add more than one interrupt by using the add_event_callback function. Here the
callback functions are executed sequentially:
GPIO.add_event_detect(channel, GPIO.RISING)
GPIO.add_event_callback(channel, MyHandler1)
GPIO.add_event_callback(channel, MyHandler2)
……………………………………………………….
……………………………………………………….
def MyHandler1(channel):
……………………
……………………
def MyHandler2(channel):
……………………
……………………
When we use mechanical switches in our projects we get what is known as the switch
bouncing problem. This occurs as the contacts of the switch bounce many times until they
settle to their final state. Switch bouncing could generate several pulses before it settles
down. We can avoid switch bouncing problems in hardware or software. GPIO library pro-
● 125
vides a parameter called bounce-time that can be used to eliminate the switch bouncing
problem. An example use of this parameter is shown below where the switch bounce time
is assumed to be 10ms:
GPIO.add_event_detect(channel,GPIO=RISING,callback=MyHandler,
bouncetime=10)
We can also use the callback statement to specify the switch bouncing time as@
To read the state of an input pin we can use the following statement:
GPIO.input(channel)
Output Configuration
The following statement is used to configure a channel as an output. Here, channel refers
to the port number based on the setmode statement described earlier:
GPIO.setup(channel, GPIO.OUT)
We can specify a value for an output pin during its setup. For example, we can configure a
channel as output and at the same time set its value to logic HIGH (+3.3V):
To send data to an output port pin we can use the following statement:
GPIO.output(channel, value)
At the end of the program, we should return all the used resources to the operating system.
This is done by including the following statement at the end of our program:
GPIO.cleanup()
Background Information: The forward voltage of an LED is around 1.8V. The current
through the LED depends on the required light intensity and the type of LED used. In gen-
eral, 3mA should give enough visible light for small LEDs. Because the output voltage of
● 126
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
Figure 5.30 shows the LED connected to pin GPIO 2 of the Raspberry Pi.
Program Listing: The program is very simple and is shown in Figure 5.31 (program: LED.
py). At the beginning of the program, the RPi.GPIO and the time modules are imported to
the program. Then the pin numbering is configured to use BCM notation and GPIO 2 is con-
figured as an output pin. The remainder of the program is run indefinitely in a while loop
where the LED is turned ON and OFF with a one-second delay between each output. Notice
that the try-except statements are used to catch the keyboard Cntrl+C interrupts so that
the program can be terminated cleanly. If you created the program using the nano editor
you can run it by entering the command: python3 LED.py from the command line. You
can enter Cntrl+C to terminate the program. Alternatively, if the program is created using
Thonny, simply save the program and click the Run button to run the program. Click Stop/
Restart backend to stop the program. You should see the LED flashing every second.
#---------------------------------------------------------------
#
# FLASHING LED
# ============
#
# In this project a small LED is connected to GPIO 2 of the
# Raspberry Pi 4.The program flashes the LED every second
#
# Program: LED.py
# Date : February 2020
# Author : Dogan Ibrahim
#--------------------------------------------------------
import RPi.GPIO as GPIO # import GPIO library
import time # import time library
GPIO.setwarnings(False) # disable warning messages
● 127
try:
while True:
GPIO.output(2, 1) # turn ON LED
time.sleep(1) # wait 1 second
GPIO.output(2, 0) # turn OFF LED
time.sleep(1) # wait 1 second
except KeyboardInterrupt:
GPIO.cleanup()
Figure 5.32 shows the circuit built on a breadboard and connected to Raspberry Pi using
jumper wires (notice that a fan is used to cool down the CPU).
5.12 Summary
In this chapter, we learned the basic specifications of Raspberry Pi 4. Additionally, we
learned how to install Raspbian Buster on a blank SD card. The chapter also introduced
the Python programming language and has specified the ways that this language can be
used to develop projects. A simple example project is given towards the end of the chap-
ter where an LED connected to one of the GPIO ports of the Raspberry Pi is flashed every
second.
In the next chapter, we will look at how to develop Raspberry Pi projects using MIT App
Inventor software.
● 128
Chapter 6• R
aspberry Pi Bluetooth based projects using the
MIT App Inventor
6.1 Overview
In the last chapter, we learned how to set up Raspberry Pi 4 and how to use the Python
programming language. In this chapter, we will develop projects with the Raspberry Pi 4
using App Inventor. The following sub-headings are given for each project. Note that the
QR codes given in the projects were valid only for 2 hours at the time they were created,
and they cannot be used to install the apps to your mobile phone. They are only given here
for completeness:
Description: In this project, an LED is connected to one of the GPIO ports of the Raspberry
Pi through a current limiting resistor. The LED is turned ON and OFF by sending commands
from an Android mobile phone. Communication between the Android device and Raspberry
Pi is established using Bluetooth.
Circuit Diagram: The circuit diagram of the project is as in Figure 5.30 where the LED is
connected to port pin GPIO 2.
App Inventor Application: In this project, we will have 3 buttons: A button to turn ON
the LED when clicked, a button to turn OFF the LED when clicked, and a button to connect
to the Raspberry Pi through Bluetooth. Additionally, a Label will be provided to show the
status of the Bluetooth communication.
● 129
The steps are as follows (see Figure 6.2). Full details of the component configurations will
be given in this project:
AlignHorizontal: Center: 3
AlignVertical: Center: 2
BackgroundColor: Orange
Height: 10 percent
Width: Fill parent
Image: none
Visible: ticked
Name: Label1
FontBold: ticked
FontSize: 25
Height: Automatic
Width: Automatic
Text: LED CONTROLLER
TextColor: Blue
AlignHorizontal: Center: 3
AlignVertical: Center: 2
BackgroundColor: Yellow
Height: 10 percent
Width: Fill parent
Image: none
Visible: ticked
First Button:
Name: ButtonON
BackgroundColor: Default
FontBold: ticked
● 130
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: None
Shape: default
Text: LED ON
TextColor: White
Second Button:
Name: ButtonOFF
BackgroundColor: Default
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: None
Shape: default
Text: LED OFF
TextColor: White
AlignHorizontal: Center: 3
AlignVertical: Center: 2
BackgroundColor: None
Height: 30 percent
Width: Fill parent
Image: none
Visible: ticked
• Insert a Label onto the Vertical Arrangement. This label will show the status of
the Bluetooth link. Configure the Label as follows. Notice that the TextColor is
set to None so that the Label is not normally visible. It will display the connec-
tion status as Connected or Disconnected:
Name: LblStatus
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Text: Status
TextColor: None
● 131
• Insert a ListPicker. This component will be used to select the Bluetooth name
and address of the Android device. Configure this component as follows:
Name: ListPicker1
BackgroundColor: default
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: None
ItemBackgroundColor: Default
ItemTextColor: Default
Text: Connect
TextColor: White
• Click the Connectivity tab and insert a BluetoothClient onto the Viewer. Also,
click the Sensors tab and insert a Clock component onto the Viewer. Both of
these components are not visible on the Viewer. The BluetoothClient will be
used to establish a connection with the Raspberry Pi. The Clock component will
be used to periodically check for the Bluetooth connection.
Figure 6.2 Design of the project (notice that LblStatus is not visible)
Figure 6.3 shows the block program of the project. Initially, the ListPicker will be used
to select the Bluetooth name and address of the Raspberry Pi. After this, a connection will
be made with the Raspberry Pi. If a connection has been established then the message
Connected will be displayed on the LblStatus in green colour, otherwise, the message
Disconnected will be displayed in red colour. When ButtonON is clicked, if there is a Blue-
tooth connection then the button text colour will change to red, and number 49 (character
● 132
"1") will be sent to Raspberry Pi to request the LED to be turned ON. If on the other hand,
ButtonOFF is clicked then the Bluetooth connection will be checked and the button text
colour will be set to red to indicate that the LED is turned OFF. Number 48 (character "0")
will be sent to Raspberry Pi to request the LED to be turned OFF.
• We now insert a Clock block so that the Bluetooth connection is checked period-
ically. Click Clock1 and select when Clock1.Timer do
• Click Control and select an if-then block and extend it to if-then-else block
• If the Bluetooth connection has been made then display Connected in green
colour by label LblStatus, otherwise display Disconnected in red colour by
LblStatus
• When the user clicks button LED ON, block when ButtonON.Click do is activat-
ed. If the Bluetooth is connected, set the ButtonON text colour to red and the
ButtonOFF text colour to white. At the same time, click BluetoothClient1 and
select call BluetoothClient1.Send1ByteNumber
• Click Math and select the top block to enter number 49. Remember that 49 cor-
responds to ASCII character "1"
● 133
• When the user clicks button LED OFF, block when ButtonOFF.Click do is acti-
vated. If the Bluetooth is connected, set the ButtonOFF text colour to red and
the ButtonON text colour to white. At the same time, click BluetoothClient1
and select call BluetoothClient1.Send1ByteNumber
• Click Math and select the top block to enter number 48. Remember that 48 cor-
responds to ASCII character "0"
Build the program. The QR code of the program is shown in Figure 6.4.
● 134
Python Program: In this project, we are assuming that the Bluetooth is enabled on your
Raspberry Pi and it is already paired with your Android mobile phone. Before developing
your program, you will need to install the Bluetooth library on your Raspberry Pi. This is
done by entering the following command on your Raspberry Pi while in command mode:
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:
• Start the nano text editor and edit the following file:
• 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
The Python 3 program for this project is named blut.py and it was developed under Thonny
and the program listing is shown in Figure 6.5. Notice that the program does not run under
Python version 2. At the beginning of the program, the LED at GPIO port 2 is defined as
LED. The program then creates a Bluetooth socket, binds and listens on this socket, and
then waits to accept a connection. The remainder of the program is executed in a loop
where the program issues statement client.recv and waits to receive commands from
the mobile phone. The received command is decoded and the LED is turned ON or OFF as
requested by the Android mobile phone. Notice that the program makes use of the MAC
address of the Raspberry Pi. This can be obtained by entering the following command in
terminal mode:
In this example project, the MAC address of the Raspberry Pi was found to be:
DC:A6:32:00:E4:2A.
Notice that what is returned into variable data is byte objects which is actually arrays of
integers. Here, we are using the built-in decode function to convert them into their equiv-
alent ASCII characters (utf-8 is the default encoding and decoding parameter in Python 3):
● 135
try:
while True:
data = client.recv(1024) ## Receive data bytes
if data.decode('utf-8') == "1": # 1 received
GPIO.output(LED, 1) # LED ON
elif data.decode('utf-8') == '0': # 0 received
GPIO.output(LED, 0) # LED OFF
#---------------------------------------------------------------
#
# LED CONTROL FROM ANDROID MOBILE PHONE
# =====================================
#
# In this project a small LED is connected to port GPIO 2 of the
# Raspberry Pi through a current limiting resistor. The LED is
# turned ON and OFF from an Android mobile phone
#
# Program: blut.py
# Date : February 2020
# Author : Dogan Ibrahim
#-----------------------------------------------------------------
import socket # import socket library
import RPi.GPIO as GPIO # import GPIO library
GPIO.setwarnings(False) # disable warnings
GPIO.setmode(GPIO.BCM) # set BCM pin numbering
#
# LED is on GPIO 2, configure GPIO 2 as output
#
LED = 2 # LED on GPIO 2
GPIO.setup(LED, GPIO.OUT) # conf LED as output
#
# Turn OFF the LED to start with
#
GPIO.output(LED, 0)
#
# Start of main program loop. Read commands from the Android
# mobile phone, decode them, and control the LED
#
#
● 136
Port = 1
MAC = 'DC:A6:32:00:E4:2A'
s=socket.socket(socket.AF_BLUETOOTH,socket.SOCK_STREAM,socket.
BTPROTO_RFCOMM)
s.bind((MAC, Port))
s.listen(1)
client, addr = s.accept()
#
# Turn ON the LED if the command is: 1
# Turn OFF the LED if the command is: 0
#
try:
except KeyboardInterrupt:
client.close() # Close
s.close()
• Make Bluetooth Discoverable by clicking the Bluetooth icon on the top right-hand
side of your Raspberry Pi.
• You may have to accept to pair the two Bluetooth devices. If it asks for a pass-
word, enter 1234
• Run your program either inside Thonny or from the command line as:
• Start the mobile application on your Android device and click button Connect.
You should see the Bluetooth devices that can be reached as shown in Figure 6.6.
Click on Raspberry Pi
● 137
• Click on button LED ON to turn ON the LED, then click on LED OFF to turn OFF
the LED.
Notice that in this project we are controlling an LED. Instead of the LED, we could have
connected a relay to the Raspberry Pi so that electrical devices (e.g. appliances) could be
controlled from the Android device.
Description: This project is very similar to the previous project, but here additionally
sound output is produced. The LED is connected to one of the GPIO ports of the Raspberry
Pi as in the previous project and the LED is turned ON and OFF by sending commands from
an Android mobile phone.
The following sounds are output from the Android mobile phone by using the TextTo-
Speech component of App Inventor:
● 138
The Python program remains the same, but the following modifications are required to App
Inventor:
Modifications in Designer:
• Click the Media tab and insert component TextToSpeech onto the Viewer. This
is a hidden component
• Click Text under Built-in and select the top block to enter text. Enter the text
Select Raspberry Pi name and address. This text will be spoken when Con-
nect is clicked
● 139
Figure 6.9 shows the QR code of the project. Run the program as in the previous project.
You should hear sound messages when you select the Raspberry Pi Bluetooth name and
address and when you turn the LED ON or OFF.
Description: This project is similar to Project 1, but here the LED is controlled by speech
commands, spoken to the Android mobile phone.
● 140
LED ON
LED OFF
The Python program remains the same, but both the Designer and Blocks parts of App
Inventor program require changes.
Name: ButtonStart
BackgroundColor: Default
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: none
Text: Start
TextColor: White
Name: LblStatus
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Text: Status
TextColor: None
• Insert a ListPicker. This component will be used to select the Bluetooth name
and address of the Android device. Configure this component as follows:
● 141
Name: ListPicker1
BackgroundColor: default
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: None
ItemBackgroundColor: Default
ItemTextColor: Default
Text: Connect
TextColor: White
Name: LblComamnd
FontBold: ticked
FontSize: 20
Height: Automatic
Width: Automatic
Text: Command
• Click the Connectivity tab and insert a BluetoothClient onto the Viewer. The
BluetoothClient will be used to establish a connection to the Raspberry Pi.
• Click the Sensors tab and insert a Clock component onto the Viewer. The Clock
component will be used to periodically check for the Bluetooth connection
• Click the Media tab and insert a SpeechRecognizer component onto the View-
er. This component will recognize the spoken commands.
● 142
Figure 6.11 shows the block program of the project. Most parts of the block program are
the same as in Figure 6.3, and only the modifications are given here:
• Click ButtonStart and select when ButtonStart.Click do. This block will be
activated when button Start is clicked. Here we want to enable the speech rec-
ognizer so that the spoken commands can be received
• If on the other hand the spoken command is LED off then we send number 48
(character "0") to request the LED to be turned OFF.
• Notice that LblCommand displays the messages LED turned ON or LED turned
OFF after a valid command is received by the Android device.
● 143
Figure 6.12 shows the QR code of the project. The steps to test the project are as follows:
• Make Bluetooth Discoverable by clicking the Bluetooth icon on the top right-hand
side of your Raspberry Pi.
• You may have to accept to pair the two Bluetooth devices. If it asks for a pass-
word, enter 1234
• Run your program either inside Thonny or from the command line as:
• Start the mobile application on your Android device and click button Connect.
You should see the Bluetooth devices that can be reached and select Raspberry
Pi as in the previous projects. You should see a Connected message displayed.
• Click on button Start and speak your command. e.g. LED ON. You should see
the LED to be turned ON. At the same time, the message LED turned ON will
be displayed on the screen.
● 144
Description: This project is similar to Project 1, but here 4 LEDs are used and the LEDs are
controlled by 8 buttons: 4 buttons to turn them ON and 4 buttons to turn them OFF. The
following commands are sent to the Raspberry Pi when a button is clicked (the first number
is the LED number, the second number is the required LED state: 1 for ON, 0 for OFF)
Block Diagram: Figure 6.13 shows the block diagram of the project.
Circuit Diagram: The circuit diagram of the project is shown in Figure 6.14. The LEDs are
connected to Raspberry Pi through 470 Ohm current limiting resistors as follows:
● 145
App Inventor Application: Figure 6.15 shows the design of the project. Clicking the Con-
nect ListPicker enables the user to select the Raspberry Pi Bluetooth name and address and
then connects to Raspberry Pi. The LEDs are turned ON and OFF by clicking the required
buttons.
• Insert a HorizontalArrangement and insert a Label with its Text set to 4 LED
CONTROLLER
Name: LED1ON
BackgroundColor: Blue
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: none
Shape: oval
Text: LED1 ON
TextColor: White
● 146
• Insert labels between the horizontally placed buttons so that there are spaces
between them. Set the Height of these labels to Automatic and their Width to
5%. Clear the Text fields of these labels so that they are not visible.
Figure 6.16a and Figure 6.16b show the block program of the project. Parts of this program
(ListPicker and Clock blocks) that connect to Raspberry Pi are the same as in the previous
projects and are not repeated here. Only the LED-based parts of the blocks are described:
• Create a procedure called ALLOFF and set all button colours to white in this pro-
cedure. This procedure will be called in every button (that's why it is configured
as a procedure) activated block so that all button colours are white. Only the
colour of the clicked button will be set to red
• Click LED1ON and select when LED1ON.Click do. This block will be activated
when button LED1 ON is clicked.
• Call procedure ALLOFF to turn all button colours to white (no button selected)
• Set the colour of button LED1ON to red since this is the button clicked by the
user
● 147
• Repeat the above for all the other 7 buttons. Notice that the command sent to
Raspberry Pi is made up of 2 characters. The first character is the LED number
and the second character specifies whether the LED must be turned ON (if "1")
or OFF (if "0")
● 148
Python Program: The Python program (blut4.py) for the Raspberry Pi is shown in Fig-
ure 6.18. At the beginning of the program the socket library and the Rpi.GPIO libraries
are included in the program. The LED connections to Raspberry Pi are then defined and
these ports are configured as outputs. All the LEDs are turned OFF at the beginning of the
program. The data packet received from the Android device is stored in variable data. The
LEDs are controlled depending on the contents of this data packet as described earlier in
this project.
#---------------------------------------------------------------
#
# LED CONTROL FROM ANDROID MOBILE PHONE
# =====================================
#
# In this project 4 LEDs are connected to GPIO ports of the
# Raspberry Pi through current limiting resistors. The LEDs are
# turned ON and OFF from an Android mobile phone
#
# Program: blut4.py
# Date : February 2020
# Author : Dogan Ibrahim
#-----------------------------------------------------------------
import socket # import socket library
import RPi.GPIO as GPIO # import GPIO library
GPIO.setwarnings(False) # disable warnings
GPIO.setmode(GPIO.BCM) # set BCM pin numbering
● 149
#
# Configure the LEDs as outputs
#
LED1 = 2 # LED1 on GPIO 2
LED2 = 3 # LED2 on GPIO 3
LED3 = 4 # LED3 on GPIO 4
LED4 = 17 # LED4 on GPIO 17
GPIO.setup(LED1, GPIO.OUT) # conf LED1 as output
GPIO.setup(LED2, GPIO.OUT) # conf LED2 as output
GPIO.setup(LED3, GPIO.OUT) # conf LED3 as output
GPIO.setup(LED4, GPIO.OUT) # conf LED4 as output
#
# Turn OFF all LEDs to start with
#
GPIO.output(LED1, 0)
GPIO.output(LED2, 0)
GPIO.output(LED3, 0)
GPIO.output(LED4, 0)
#
# Start of main program loop. Read commands from the Android
# mobile phone, decode them, and control the LED
#
#
Port = 1
MAC = 'DC:A6:32:00:E4:2A'
s=socket.socket(socket.AF_BLUETOOTH,socket.SOCK_STREAM,socket.
BTPROTO_RFCOMM)
s.bind((MAC, Port))
s.listen(1)
client, addr = s.accept()
#
# Turn ON the LED if the command is: 1
# Turn OFF the LED if the command is: 0
#
try:
● 150
GPIO.output(LED2, 1) # LED2 ON
elif data.decode('utf-8') == "20": # 20 received
GPIO.output(LED2, 0) # LED2 OFF
elif data.decode('utf-8') == "31": # 31 received
GPIO.output(LED3, 1) # LED3 ON
elif data.decode('utf-8') == "30": # 30 received
GPIO.output(LED3, 0) # LED3 OFF
elif data.decode('utf-8') == "41": # 41 received
GPIO.output(LED4, 1) # LED4 ON
elif data.decode('utf-8') == "40": # 40 received
GPIO.output(LED4, 0) # LED4 OFF
except KeyboardInterrupt:
client.close() # Close
s.close()
• Make Bluetooth Discoverable by clicking the Bluetooth icon on the top right-hand
side of your Raspberry Pi.
• You may have to accept to pair the two Bluetooth devices. If it asks for a pass-
word, enter 1234
• Run your program either inside Thonny or from the command line as:
• Start the mobile application on your Android device and click button Connect.
You should see the Bluetooth devices that can be reached and select Raspberry
Pi as in the previous projects. You should see a Connected message displayed.
• Click a button to turn ON the LED. e.g. click LED1 ON to turn LED1 ON. Try for
the other LEDs. Notice that the text colour of the clicked button changes to red,
while the other button colours are in white.
Figure 6.19 shows the program running on an Android mobile phone where button LED2
ON is clicked.
● 151
In this project, we used 4 LEDs. In real applications, these LEDs can be replaced by relays
so that real equipment (e.g. appliances at home) can easily be controlled from an Android
mobile phone.
Description: This project is similar to Project 4, but here sound output is added to the
project so that the state of the LEDs is spoken out by the Android mobile device.
In this project, only the changes from Project 4 are given. These changes are in button click
blocks only. The Python program is the same as in Figure 6.18.
Changes in Designer:
Changes in Blocks:
Figure 6.20a and Figure 6.20b show the modified button click blocks. The TextToSpeech1
block is added to these button blocks so that the status of the LEDs is spoken from the
Android device.
● 152
● 153
The QR code of the project is shown in Figure 6.21. Start the Python program and connect
the two devices via Bluetooth. As an example, when LED1 ON button is clicked, LED1
should turn ON and the message LED 1 turned ON will be heard from the Android device
speaker.
● 154
Figure 6.22 shows the circuit built on a breadboard and connections made to Raspberry Pi
using jumper wires.
Background Information: DC motors, heaters, and similar loads requiring large currents
are driven from microcontroller ports using PWM (Pulse Width Modulated) waveforms. A
PWM waveform is a positive square waveform with a fixed period. The average voltage of
the PWM waveform is varied by changing the On-time of the waveform. The ratio of the ON
time to the period of the waveform is known as the Duty Cycle of the waveform. As shown
in Figure 6.23, a 25% duty cycle corresponds to a quarter of the average voltage given to
the load. Similarly, a 50% duty cycle corresponds to half of the average voltage given to
the load. Therefore, by changing the duty cycle of the waveform, we can effectively change
the average voltage supplied to the load.
● 155
In this project, the duty cycle of the voltage applied to the motor is varied using a slider
component on the Android mobile phone and this is sent to the Raspberry Pi over a Blue-
tooth interface using App Inventor software. As a result, the speed of the motor changes
accordingly.
Block Diagram: Figure 6.24 shows the block diagram of the project.
Circuit Diagram: The circuit diagram of the project is shown in Figure 6.25. An NPN tran-
sistor switch is used to drive the DC motor since the output current of the Raspberry Pi is
not enough to drive a motor.
● 156
App Inventor Application: In this project, we will use a slider component on our Android
mobile phone to change the required duty cycle.
• Insert another HorizontalArrangement. Click the User Interface tab and in-
sert a Slider component. Configure this component as follows:
Name: Slider1
ColorLeft: Black
ColorRight: Default
Width: 70 percent
MaxValue: 100
MinValue: 0
ThumbEnabled: ticked
ThumbPosition: 1
Visible: ticked
● 157
Figure 6.27 shows the block program of the project. The steps are as follows:
• Insert the ListPicker and Clock blocks as in the previous projects. These blocks
are used to establish Bluetooth connection to the Raspberry Pi
• Click Slider1 and select when Slider1.PositionChanged do. This block will be
executed when the slider position is changed
• Click LblDuty and select set LblDuty.Text to. Set its text to display the slider
position, followed by symbol %.
Python Program: The Python program (motor.py) listing is shown in Figure 6.29. At the
beginning of the program, the socket library and Rpi.GPIO library are imported to the pro-
gram. Motor is then assigned to GPIO port 2 and it is configured as output. Function GPIO.
PWM initializes a GPIO port as a PWM port where the first argument is the port number and
the second argument is the frequency of the PWM waveform. In this project, the frequency
is chosen as 100Hz. PWM waveform is generated on the selected port when function pwm.
start is called. The argument to this function is the duty cycle (DC) of the waveform. Initial-
● 158
ly, DC is set to 0 so that the motor is idle. The program then makes Bluetooth connection to
the Arduino mobile phone and receives the user commands. String variable DCSTR stores
the received command which is the duty cycle set by the user (between "0" and "100").
This string is converted into an integer number and stored in DC which is then used to
change the duty cycle of the PWM waveform by calling function ChangeDutyCycle.
#---------------------------------------------------------------
#
# MOTOR SPEED CONTROL FROM ANDROID MOBILE PHONE
# =============================================
#
# In this project a small DC motor is connected to port GPIO 2
# of Raspberry Pi through a transistor switch. The speed of the
# motor is varied by moving the slider on Android mobile phone
#
# Program: motor.py
# Date : February 2020
# Author : Dogan Ibrahim
#-----------------------------------------------------------------
import socket # import socket library
import RPi.GPIO as GPIO # import GPIO library
GPIO.setwarnings(False) # disable warnings
GPIO.setmode(GPIO.BCM) # set BCM pin numbering
#
# MOTOR is on GPIO 2, configure GPIO 2 as output
#
MOTOR = 2 # MOTOR on GPIO 2
GPIO.setup(MOTOR, GPIO.OUT) # conf MOTOR as output
DC = 0 # Duty cycle
#
# Start of main program loop. Read commands from the Android
# mobile phone, decode them, and control the Motor
#
#
Port = 1
MAC = 'DC:A6:32:00:E4:2A'
s=socket.socket(socket.AF_BLUETOOTH,socket.SOCK_STREAM,socket.
BTPROTO_RFCOMM)
s.bind((MAC, Port))
s.listen(1)
client, addr = s.accept()
● 159
#
# The duty cycle is between 0 and 100
#
try:
except KeyboardInterrupt:
client.close() # Close
s.close()
• Start the Raspberry Pi program either from Thonny or from the command line
• Start the program on the Android mobile phone. Click Connect to make a con-
nection between the Raspberry Pi and the Android mobile phone
• Move the arm of the slider on your mobile phone and you should see the motor
starting to run
Figure 6.30 shows the snapshot of a sample run on the Android mobile phone.
● 160
Background Information: In this project, the popular DHT11 temperature and sensor
module (Figure 6.31) is used. This is a 3-pin sensor (some modules have 4 pins but one of
the pins is not used) having the following specifications:
• 3 to 5V operation
• 3 pins: +Vcc, GND, and Signal (S)
• 2.5mA current consumption
• 20-80% humidity measurement range with 5% accuracy
• 0-50ºC temperature measurement range with ±2ºC accuracy
• Output one every second
Block Diagram: Figure 6.32 shows the block diagram of the project.
Circuit Diagram: The circuit diagram of the project is shown in Figure 6.33. The signal pin
of the DHT11 sensor module is connected to GPIO 2 of Raspberry Pi.
● 161
App Inventor Application: The steps are as follows (see Figure 6.34).
AlignHorizontal: Center: 3
AlignVertical: Center: 2
BackgroundColor: Orange
Height: 10 percent
Width: Fill parent
Image: none
Visible: ticked
Name: Label1
FontBold: ticked
FontSize: 25
Height: Automatic
Width: Automatic
Text: TEMPERATURE & HUMIDITY
TextColor: Blue
AlignHorizontal: Center: 3
AlignVertical: Center: 2
BackgroundColor: None
Height: 30 percent
Width: Fill parent
Image: none
Visible: ticked
• Insert a Label on to the Vertical Arrangement. This label will show the status
of the Bluetooth link. Configure the Label as follows. Notice that TextColor is set
to None so that the Label is not normally visible. It will display the connection
status as Connected or Disconnected:
Name: LblStatus
FontBold: ticked
FontSize: 20
FontTypeface: default
● 162
Height: Automatic
Width: Automatic
Text: Status
TextColor: None
Name: ButtonDisconnect
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: None
Shape: rounded
Text: Disconnect
TextColor: Red
Name: ListPicker1
BackgroundColor: default
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: None
ItemBackgroundColor: Default
ItemTextColor: Default
Text: Connect
TextColor: White
AlignHorizontal: Center: 3
AlignVertical: Center: 2
BackgroundColor: Yellow
Height: 10 percent
Width: Fill parent
Image: none
● 163
Name: Label2
BackgroundColor: None
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Text: Temperature (C):
TextColor: Red
Name: TxtTemperature
BackgroundColor: default
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: 20 percent
Hint: blank
TextColor: default
Name: Label3
BackgroundColor: None
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Text: Humidity (%):
TextColor: White
Name: TxtHumidity
BackgroundColor: default
FontBold: ticked
● 164
FontSize: 20
FontTypeface: default
Height: Automatic
Width: 20 percent
Hint: blank
TextColor: default
• Click the Connectivity tab and insert a BluetoothClient onto the Viewer. Click
the Sensors tab and insert a Clock component onto the Viewer, name this Clock
as Clock1. Also, insert another Clock component onto the Viewer. Name the
second Clock component as THClock. All of these components are not visible on
the Viewer. The BluetoothClient will be used to establish a connection with the
Raspberry Pi. The Clock1 component will be used to periodically check for the
Bluetooth connection. THClock will read the temperature and humidity from the
Raspberry Pi periodically.
Figure 6.35 shows the block program of the project. The steps are as follows:
• Insert the ListPicker1 and Clock1 blocks as in the previous projects. These
blocks establish Bluetooth connection with the Raspberry Pi
● 165
• Click THclock and select when THClock.Timer do. This block will be called pe-
riodically to display the temperature and humidity on the screen
• Insert an if-then block and insert the block to check if Bluetooth connection has
been established
• Click Variables and create a new variable called TH. This variable will be loaded
with the temperature and humidity data received from the Raspberry Pi
• The first 2 bytes of the received data is the temperature and this is loaded into
TxtTemperature. A segment text block (in Text under Built-in) is used to ex-
tract the first 2 bytes of the received data. Notice that the segment text byte
numbering starts from 1
• Another segment text block extracts 2 bytes starting from byte 4 and loads this
value into TxtHumidity
● 166
Python Program: Before writing the Python program we have to install the Adafruit
DHT11 library to our Raspberry Pi. Enter the following command:
The Raspberry Pi program (dht11.py) listing is shown in Figure 6.37. At the beginning of
the program libraries time, socket, and RPi.GPIO are imported into the program. Variable
sensor is assigned to Adafruit_DHT.DHT11 to specify that we will be using DHT11 (and
not DHT22). Variable pin is set to 2 and this is where the DHT11 signal pin is connected
to. In the remaining parts of the program, we establish Bluetooth communication with the
Android mobile phone. The ambient temperature and humidity are received from DHT11 at
the beginning of the block of code starting with statement while True:. The temperature
and humidity readings are then converted into string and stored in variables datat and
datah respectively. If the temperature is less than 10 then a 0 is added to its beginning to
make sure that the total byte count is always 5 (ambient humidity is always 2 digits). The
temperature and humidity readings are combined and separated with a comma so that in
total there are 5 bytes of data. Variable datas encodes the data and then sends it over the
Bluetooth link using function send. The loop is repeated after 5 seconds delay.
#---------------------------------------------------------------
#
# DHT11 TEMPERATURE AND HUMIDITY SENSOR
# =====================================
#
# In this project a DHT11 sensor module is connected to port GPIO 2
# of Raspberry Pi. The temperature and humidity readings are sent
# to the Android mobile phone over the Bluetooth link
#
# Program: dht11.py
# Date : February 2020
# Author : Dogan Ibrahim
#-----------------------------------------------------------------
import time # import time library
import socket # import socket library
● 167
#
# Start of main program loop. Read temperature and humidity and
# send to the Android mobile phone over Bluetooth link
#
Port = 1
MAC = 'DC:A6:32:00:E4:2A'
s=socket.socket(socket.AF_BLUETOOTH,socket.SOCK_STREAM,socket.
BTPROTO_RFCOMM)
s.bind((MAC, Port))
s.listen(1)
client, addr = s.accept()
try:
except KeyboardInterrupt:
client.close() # Close
s.close()
To test the program, start the Raspberry Pi program and then start the Android program
and click Connect to establish Bluetooth connection between the two devices. You should
see the connected message displayed on the Android screen. The temperature and humidi-
ty readings should then be displayed on the Android mobile phone as shown in Figure 6.38.
● 168
Description: There are some applications where we may want to password protect our
Android application. For example, suppose that we are using a relay to control our central
heating remotely. In such applications, we do not want unauthorized people to have access
to our central heating. In this project, we will learn how to include password protection in
our applications.
In this project, we will check the username and password and if they are correct then
a second screen will be called to display the message This is the second screen… For
simplicity, the username and password are hardcoded to be rpi and project respectively.
App Inventor Application: The steps are as follows (see Figure 6.39):
Columns: 3
Height: 20 percent
Width: Fill parent
Rows: 2
● 169
Name: TxtUsername
BackgroundColor: default
FontBold: ticked
FontSize: 20
Height: Automatic
Width: Automatic
Hint: blank
TextColor: Default
Name: TxtPassword
BackgroundColor: default
FontBold: ticked
FontSize: 20
Height: Automatic
Width: Automatic
Hint: blank
TextColor: Default
Name: ButtonLogin
BackgroundColor: Blue
FontBold: ticked
FontSize: 20
Height: Automatic
Width: Automatic
Text: Login
TextColor: White
Name: LblStatus
BackgroundColor: None
FontBold: ticked
FontSize: 20
Height: Automatic
Width: Automatic
Text: test
TextColor: Default
Visible: not ticked
● 170
• Click Add Screen and give the second screen the name LED
• Now, go to Screen1 and create the blocks as shown in Figure 6.41. Notice that
there is no block program for the LED screen in this simple project. The steps
are:
• Click Variables and initialize two variables with the names username and pass-
word. Set the username to rpi and the password to project
• Click ButtonLogin and select when ButtonLogin.Click do. This block will be
activated when the Login button is clicked after entering the username and pass-
word
● 171
• If the correct username and password are entered, then display the message
Successful login… and then click Control under Built-in and select open an-
other screen screenName and set it to string LED so that the second screen
will be displayed when the correct username and password are entered.
Notice that you could have used a PasswordTextBox instead of an ordinary TextBox to
hide the password entered by the user.
● 172
6.10 Summary
In this chapter, we developed several hardware projects using the Bluetooth link to estab-
lish communication between an Android device and Raspberry Pi. In the next chapter, we
will develop similar projects but this time using Wi-Fi instead of Bluetooth.
● 173
7.1 Overview
In the last chapter, we developed projects based on Bluetooth communication between
Raspberry Pi and an Android mobile phone. In this chapter, we will develop similar projects
but this time using Wi-Fi to establish communication between Raspberry Pi and an Android
mobile phone. Note that the QR codes given in the projects were valid only for 2 hours at
the time they were created, and they cannot be used to install the apps to your mobile
phone. They are only given here for completeness.
Description: In this project, local Wi-Fi parameters, such as the IP address, MAC address,
and signal strength of the Android device are obtained and displayed on its screen.
App Inventor Application: In this project, the Taifun WiFi component extension is used
to get the local Wi-Fi parameters. The steps are (see Figure 7.1):
AlignHorizontal: Center: 3
AlignVertical: Center: 2
Height: 30 percent
Width: Fill parent
• Insert a Label with the following configuration. This Label will display the local
Wi-Fi parameters:
Name: LblStatus
BackgroundColor: None
FontBold: ticked
FontSize: 20
Height: Automatic
Width: Automatic
Text: Status
TextColor: None
Visible: ticked
• Insert a Button with the following configuration. This button will disconnect from
Wi-Fi when clicked:
Name: ButtonDisconnect
BackgroundColor: Default
● 174
FontBold: ticked
FontSize: 20
Height: Automatic
Width: Automatic
Text: Disconnect
TextColor: Red
• Insert a Button with the following configuration. This button will connect to Wi-Fi
when clicked
Name: ButtonConnect
BackgroundColor: Default
FontBold: ticked
FontSize: 20
Height: Automatoc
Width: Automatic
Text: Connect
TextColor: Blue
• Go to the end of following web site and click Download TaifunWiFi extension
(aix file) and download it to a folder:
https://puravidaapps.com/wifi.php
• Click Extension tab on the left-hand side of your App Inventor project
• Click Import extension and browse to the file you just downloaded
• You should see a new component called TaifunWiFi under Extension. Click and
drop it on your Viewer. This is a hidden component and will only be displayed
under the phone image as TaifunWiFi1
● 175
Figure 7.2 shows the block program of the project. The steps are:
• Initialize two variables named ssid and password. Enter your Wi-Fi SSID name
and password into these blocks respectively
• Insert a Join block and extend it to 8 connectors. Enter blocks as shown in Figure
7.2 to display the IP address, MAC address, and the signal strength
● 176
Figure 7.3 shows the QR code of the project. An example run of the project on an Android
mobile phone is shown in Figure 7.4.
Description: In this project, an LED is connected to the Raspberry Pi and is controlled from
an Android mobile phone using a web server application.
● 177
App Inventor Application: This project uses the component Web to communicate with
the Raspberry Pi over a web server interface.
• Click the Connectivity tab and insert a Web component on the Viewer. This is
a hidden component.
Figure 7.6 shows the block program of the project. The steps are:
• Initialize a variable called RaspberryPi and set it to the IP address of your Rasp-
berry Pi
• Click ButtonON and select when ButtonON.Click do. This block will be execut-
ed when button LED ON is clicked.
• Insert a Join block and set the URL to the IP address of your URL and add string
/LED/on to this block as shown in the Figure
• Click on Web1 and select call Web1.Get. In this project, the URL is set to
http://192.168.1.202/LED/on
• Set the colour of ButtonON to red, and the colour of ButtonOFF to white
● 178
• Repeat for the ButtonOFF as shown in the second group of blocks in the figure,
but this time set the URL to http://192.168.1.202/LED/off
Flask should already be available in Python on your Raspberry Pi, but if it isn't, it can be
installed on Raspberry Pi using the following command:
Figure 7.8 shows the Python program (webled.py) listing of the project. The LED is set to
2 which is the GPIO 2 port it is connected to. This port is configured as an output and the
LED is turned OFF at the beginning of the program. An app.route is created with parame-
ters device and action. For every actuator, we must have an action. If the action is on,
the LED is turned ON, otherwise, if the action is off, the LED is turned OFF.
● 179
Notice that the LED can be turned ON by entering the URL: 192.168.1.202/LED/on to
our web browser. Similarly, the LED can be turned OFF by the URL: 192.168.1.202/LED/
off
#-------------------------------------------------------------
# WEB SERVER LED CONTROL
# ======================
#
# In this project an LED is connected to GPIO 2 of the
# Raspberry Pi. The LED is controlled using a web server
#
# File: webled.py
# Date: February 2020
# Author: Dogan Ibrahim
#------------------------------------------------------------
app=Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
LED = 2 # LED at GPIO 2
GPIO.setup(LED, GPIO.OUT) # Configure as output
GPIO.output(LED, 0) # LED OFF
@app.route("/<device>/<action>")
def action(device, action):
actuator = LED
if action == "on":
GPIO.output(actuator, GPIO.HIGH) # LED ON
if action == "off":
GPIO.output(actuator, GPIO.LOW) # LED OFF
return ""
if __name__ == '__main__':
app.run(debug=True, port=80, host='0.0.0.0')
To test the project, start Python program on your Raspberry Pi either through Thonny or
from the command line as:
● 180
Then, start the program on the Android mobile phone Click LED ON to turn the LED ON, and
click LED OFF to turn OFF the LED.
Note, when you start the program on the Raspberry Pi you will see statements similar
to the ones shown in Figure 7.9. As you click the buttons on your Android device you
should see statements displayed on the PC screen as shown in Figure 7.10. In this display,
192,168.1.178 is the IP address of the Android device. Enter Cntrl+C when you finish your
testing.
Description: In this project, a 4 channel relay module is connected to the Raspberry Pi.
The relay channels are controlled individually by clicking buttons on the Android mobile
phone. The relays can easily be used to control various electrical equipment (e.g. lamps,
home appliances, etc).
Background Information: In this project, a 4-channel relay board (see Figure 7.11) 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 on 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 +5V. Jumper JD is used to select the voltage
for the relay. Because the current drawn by a relay can be over 80mA, you must re-
move this jumper and connect an external power supply (e.g. +5V) to pin JD-VCC.
● 181
Block Diagram: Figure 7.12 shows the block diagram of the project.
Circuit Diagram: The circuit diagram of the project is shown in Figure 7.13. IN1, IN2, IN3
and IN4 inputs of the relay board are connected to Raspberry Pi GPIO pins 2, 3, 4, and 17
respectively. Also, GND and +3.3V pins of the development board are connected to GND
and VCC pins of the relay board. You must make sure that jumper JD is removed from the
board. Connect an external +5V power supply to the JD-VCC pin of the relay board.
● 182
App Inventor Application: This project uses the component Web to communicate with
the Raspberry Pi.
The steps are (see Figure 7.14, although parts of some of the Buttons seem to be missing
in this figure, they are correctly displayed on the actual mobile phone):
• Click tab Connectivity and insert the hidden Web component on the Viewer.
● 183
Figure 7.15 shows the block program of the project. The relay channels are controlled by
sending the following HTTP requests to the Raspberry Pi web server:
• Initialize a variable called RaspberryPi and enter the IP address of your Rasp-
berry Pi
• There are 8 buttons, 4 to turn the relays ON, and 4 to turn the relays OFF. In the
remainder of this project, one group of blocks will be described. As can be seen
from Figure 7.15, the groups of blocks are similar to each other
• Click Relay1ON and select when Relay1ON.Click do. This block will be acti-
vated when the user clicks button RELAY1 ON. We want to turn ON channel 1 of
the relay, and at the same time to change the text colour of button RELAY1 ON
to red, and the colour of RELAY1 OFF to black
• Click Web1 and select set Web1.Url to and insert a Join block. Insert the IP
address block and a Text block with the text set to /RELAY/on1. The command
that will be sent to Raspberry Pi is: http://192.168.1.202/RELAY/on1
● 184
• Set the Text colour of button Relay1ON to red to indicate that the channel 1 of
the relay has been activated. At the same time set the colour of button Relay1
OFF to black to indicate that this button is not active (it may already be a black
colour)
• Click Web1 and select call Web1.Get to send a request to the webserver to
activate channel 1 of the relay module
• Repeat the blocks for the other buttons similarly as shown in Figure 7.15a and
Figure 7.15b.
● 185
Python Program: The Python program (relay4.py) is shown in Figure 7.17. At the be-
ginning of the program the libraries used in the program are imported, relay control pins
are assigned to GPIO ports 2,3,4, and 17. Additionally, these port pins are configured as
outputs and they are set to 1 so that all the relay channels are deactivated at the beginning
of the program (a relay channel is activated if a logic 0 is sent to that channel, and is de-
activated if a logic 1 is sent). The commands received from the Android mobile phone are
then checked and the relays are controlled as follows:
● 186
#-------------------------------------------------------------
# WEB SERVER RELAY CONTROL
# ========================
#
# In this project a 4 channel Relay module is connected to
# Raspberry Pi. The Relay channels are controlled using a
# web server
#
# File: relay4.py
# Date: February 2020
# Author: Dogan Ibrahim
#------------------------------------------------------------
app=Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#
# Assign Relay ports
#
RELAY1 = 2 # Relay IN1 at GPIO 2
RELAY2 = 3 # Relay IN2 at GPIO 3
RELAY3 = 4 # Relay IN3 at GPIO 3
RELAY4 = 17 # RElay IN4 at GPIO 17
#
# Configure Relay ports as outputs
#
GPIO.setup(RELAY1, GPIO.OUT) # Conf RELAY1 as output
GPIO.setup(RELAY2, GPIO.OUT) # Conf RELAY2 as output
GPIO.setup(RELAY3, GPIO.OUT) # Conf RELAY3 as output
GPIO.setup(RELAY4, GPIO.OUT) # Conf RELAY4 as output
#
# De-activate all Relay channels at the beginning
#
GPIO.output(RELAY1, 1) # Relay chan 1 OFF
GPIO.output(RELAY2, 1) # Relay chan 2 OFF
GPIO.output(RELAY3, 1) # Relay chan 3 OFF
GPIO.output(RELAY4, 1) # Relay chan 4 OFF
● 187
@app.route("/<device>/<action>")
def action(device, action):
actuator = RELAY1
if action == "on1":
GPIO.output(actuator, GPIO.LOW) # Relay 1 ON
if action == "off1":
GPIO.output(actuator, GPIO.HIGH) # Relay 1 OFF
actuator = RELAY2
if action == "on2":
GPIO.output(actuator, GPIO.LOW) # Relay 2 ON
if action == "off2":
GPIO.output(actuator, GPIO.HIGH) # Relay 2 OFF
actuator = RELAY3
if action == "on3":
GPIO.output(actuator, GPIO.LOW) # Relay 3 ON
if action == "off3":
GPIO.output(actuator, GPIO.HIGH) # Relay 3 OFF
actuator = RELAY4
if action == "on4":
GPIO.output(actuator, GPIO.LOW) # Relay 4 ON
if action == "off4":
GPIO.output(actuator, GPIO.HIGH) # Relay 4 OFF
return ""
if __name__ == '__main__':
app.run(debug=True, port=80, host='0.0.0.0')
To test the project, start the Python program either from Thonny or from the command
line as follows:
Then, start the application on your Android mobile phone. Click a button to activate the
required relay channel. You should hear the relay clicking and at the same time the relay
LED turns ON. Figure 7.18 shows an example run on the Android mobile phone. The circuit
built using jumper wires is shown in Figure 7.19.
● 188
7.5 Project 4 – S
ending Ambient Temperature and Humidity to
Android Mobile Phone
Block Diagram: The block diagram of the project is as in Figure 6.32, but Bluetooth should
be replaced with Wi-Fi.
Circuit Diagram: The circuit diagram of the project is as in Figure 6.33 where a DHT11
type sensor module is used and its signal pin is connected to GPIO 2 of the Raspberry Pi.
App Inventor Application: This project uses the component Web to communicate with
the Raspberry Pi.
• Insert a HorizontalArrangement and insert a Label with its Text set to TEM-
PERATURE & HUMIDITY
● 189
Figure 7.21 shows the block program of the project. The steps are:
• Initialize a variable called RaspberryPi and load the IP address of your Raspber-
ry Pi into this variable
• Click ButtonClick and select when ButtonClick.Click do. Clicking this button
will send a request for data to the Raspberry Pi.
• Click Web1 and select set Web1.Url to and join the IP address block to this
block
● 190
• Click Web1 and select call Web1.Get to send a GET request to the webserver
• Click Web1 and select when Web1.GotText do. This block will be executed
when temperature and humidity data arrives on the Android mobile phone.
• The received data is a string in the form tt,hh where tt and hh are the temper-
ature and humidity values respectively in string format, separated by a comma.
Extract the first two characters (temperature) and store them in TxtTempera-
ture.Text
• Extract the two characters starting from position 4 (humidity) and store in
TxtHumidity.Text
Python Program: The Python program (temphum.py) is shown in Figure 7.23. At the
beginning of the program libraries time, Flask, RPi.GPIO and Adafruit_DHT are imported to
the program. The variable sensor is set to type DHT11 with the pin number set to 2. When
a request is made by the Android mobile phone, the temperature and humidity readings
are obtained from DHT11 and stored in variables tempint and humint in integer format
respectively. If the temperature is less than 10 then a 0 is added to the front of the tem-
● 191
perature string. The two readings are combined in string variable datath with a comma
between them. This data is then returned which is sent to the Android mobile phone for
processing and displaying.
#-------------------------------------------------------------
# WEB SERVER TEMPERATURE AND HUMIDITY
# ===================================
#
# In this project a DHT11 type temperature and humidity sensor
# module is used to get the ambient temperature and humidity
# readings. These readings are sent to the Android mobile phone
# where they are displayed
#
# File: temphum.py
# Date: February 2020
# Author: Dogan Ibrahim
#------------------------------------------------------------
import time
from flask import Flask,render_template
import RPi.GPIO as GPIO
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
pin = 2
app=Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
@app.route('/', methods=['GET','POST'])
def get_data():
temp,hum = Adafruit_DHT.read_retry(sensor, pin)
tempint = int(temp)
humint = int(hum)
if tempint < 10:
datat = "0" + str(tempint)
else:
datat = str(tempint)
datath = datat + "," + str(humint)
return (datath)
if __name__ == '__main__':
app.run(debug=True, port=80, host='0.0.0.0')
● 192
To test the program, start the Python program either using Thonny or from the command
line as:
Start the Android mobile phone program and click button Get T, H to display the ambient
temperature and humidity readings. Figure 7.24 shows an example display.
7.6 Summary
In this chapter, we developed several Wi-Fi-based projects using Raspberry Pi and App
Inventor. In the next chapter, we will use Node-RED to develop App Inventor based Rasp-
berry Pi projects.
● 193
8.1 Overview
In the last chapter, we developed several projects based on Wi-Fi communication between
Raspberry Pi and an Android mobile phone. In this chapter, we will develop similar projects
but this time using Node-RED with Bluetooth and Wi-Fi connectivity to establish communi-
cation between the Raspberry Pi and the Android mobile phone.
It is assumed that the readers are familiar with Node-RED and they have developed at least
one project using Node-RED with Raspberry Pi.
Description: In this project, an LED is connected to one of the GPIO ports of the Raspberry
Pi through a current limiting resistor as in Project 1 in Chapter 6. The LED is turned ON and
OFF by sending commands from an Android mobile phone. Communication between the
Android device and Raspberry Pi is via a web server application.
Circuit Diagram: The circuit diagram of the project is as in Figure 5.30 where the LED is
connected to port pin GPIO 2.
App Inventor Application: The App Inventor block program of this project is the same
as the one given in Project 1 in Chapter 1 (Figure 6.3), except that variable RaspberryPi
must be set to http://192.168.1.202:1880 where 192.168.1.202 is the IP address of your
Raspberry Pi. Figure 8.1 shows the block program (WEB_NODE) of the project.
● 194
pi@raspberrypi:~ $ node-red-start
Start your web browser (e.g. Firefox) and enter the address: 192.168.1.202:1880 (use
the IP address of your own Raspberry Pi here)
Figure 8.3 shows the flow program (WEB_LEDFLOW) of the project which consists of 5
nodes: two http in nodes to get the HTTP requests, a function node to format the data for
the output, a rpi gpio out node to control the LED, and a http response node.
Method: GET
URL: /LED/on
Method: GET
URL: /LED/off
● 195
• Create a function node and name it as LED ON-OFF. Enter the following code
inside this node (see Figure 8.4). This function checks the received command
and if it is /LED/on then the payload is set to 1 to turn ON the LED. If on the
other hand, the command is /LED/off then the payload is set to 0 to turn OFF
the LED.
var T = msg.req.url;
var var1 = null;
if(T == "/LED/on")
var1 = {payload: 1}
else if(T == "/LED/off")
var1 = {payload: 0}
return [var1];
• Create an rpio gpio out node and name it as LED. Set the Pin to GPIO2, Type
to Digital output, and the initial level to 0.
• Create a http response node and join to the two http in nodes
To test the project, start the Android application, and click button LED ON. You should see
the LED turning ON. Click LED OFF and the LED will turn OFF.
Notice that you can import the Node-RED program (WEB_LEDFLOW) from the book web
site into your Node-RED.
Block Diagram: The block diagram of the project is as shown in Figure 7.12.
● 196
Circuit Diagram: The circuit diagram of the project is as shown in Figure 7.13. You must
make sure that jumper JD is removed from the board. Connect an external +5V power
supply to the JD-VCC pin of the relay board.
App Inventor Application: This project uses the component Web to communicate with
the Raspberry Pi. The App Inventor program of this project (Relay_Node) is the same
as the one given in Figure 7.15a and Figure 7.15b, except that the variable RaspberryPi
should be changed to http://192.168.1.202:1880 (change this to the IP address of your
own Raspberry Pi). Figure 8.5 shows the required change to the Figure 7.15 block program.
Node-RED flow program: Figure 8.7 shows the Node-RED flow program (NODE_RE-
LAY) of the project. The program consists of 14 nodes: 8 http in nodes, a function node,
4 rpi gpio out nodes, and a http response node.
• Create a function node named RELAYS ON-OFF having 4 outputs, and enter
the following code (see Figure 8.8 for part of the function code). This code acti-
vates the required relay channel. Notice that a channel is activated when its input
is set to 0, and deactivated when it is set to 1:
● 197
var T = msg.req.url;
var var1 = null;
var var2 = null;
var var3 = null;
var var4 = null;
switch(T)
{
case "/RELAY/on1":
var1 = {payload: 0};
break;
case "/RELAY/off1":
var1 = {payload: 1};
break;
case "/RELAY/on2":
var2 = {payload: 0};
break;
case "/RELAY/off2":
var2 = {payload: 1};
break;
case "/RELAY/on3":
var3 = {payload: 0};
break;
case "/RELAY/off3":
var3 = {payload: 1};
break;
case "/RELAY/on4":
var4 = {payload: 0};
break;
case "/RELAY/off4":
var4 = {payload: 1};
break;
}
return [var1, var2, var3, var4];
• Create 4 rpi gpio out nodes, one for each input (IN1,IN2,IN3 and IN4) of the
relay. Assign the Pins of these nodes to GPIO2, GPIO3, GPIO4 and GPIO17. Set
these nodes to have Digital outputs, and initialize the output states to logic 1 so
that the relays are deactivated at the beginning of the program (see Figure 8.9
for the configuration of the node to drive RELAY4).
• Create a http response node and connect to the outputs of all the http in
nodes. This is required to return a response to the Http requests, otherwise, error
messages will be displayed on the Android mobile phone.
• Join all the nodes as shown in Figure 8.7 and click Deploy.
● 198
● 199
Notice that you can import the Node-RED flow program (NODE_RELAY) from the book
web site. To test the program, run the Android application and click to activate the relays.
You should hear the relays clicking and the LED of the corresponding relays turning ON.
8.4 Summary
In this chapter, we developed several projects using Node-RED together with App Inventor
in a Raspberry Pi environment.
In the next chapter, we will develop Bluetooth based projects using an Arduino Uno proces-
sor and Android mobile phone with App Inventor.
● 200
9.1 Overview
In the last chapter, we developed projects using Node-RED together with App Inventor in a
Raspberry Pi environment. In this chapter, we will develop Bluetooth based projects using
an Arduino Uno together with App Inventor. It is assumed that readers are familiar with
Arduino Uno. Note that the QR codes given in the projects were valid only for 2 hours at the
time they were created, and they cannot be used to install the apps to your mobile phone.
They are only given here for completeness.
Before going into detail of the projects, it is worthwhile to review the basic features of the
Arduino Uno.
Notice that when the Arduino Uno is powered by the USB port (e.g. from a computer) the
maximum current capacity is around 400mA for the +5V pin and 150mA for the +3.3V
pin. When powered by an external source, the maximum current for the 5V pin is around
900mA and 150mA for the +3.3V pin. Any current drawn from the +3.3V goes through the
+5V pin. Therefore, you have to take this into account when powering external devices.
● 201
The absolute maximum current for any I/O pin is specified as 40mA (it is however recom-
mended not to exceed 20mA). The absolute total current from all the I/O pins is 200mA.
https://www.arduino.cc/en/Main/Software
The steps to writing and uploading a program to your Arduino Uno are as follows:
● 202
• Click Tools -> Board and select board type as Arduino/Gerduino Uno
• Click Tools -> Port and select the serial port that your Arduino Uno is connected
to
• Click Sketch -> Verify/Compile to compile your program. Make sure there are
no compilation errors
HC-05
This module has 6 pins and a button on the board. HC-05 can be used either as a master or
a slave, i.e. the module can initiate Bluetooth connections to other devices, or it can accept
Bluetooth connections. The button is used for entering AT commands to the module.
HC-06
This module has only 4 pins and it does not have a button. HC-06 can only be used as a
slave device, i.e. it can only accept Bluetooth connections from other devices. In this book,
we will be using the HC-06 module whose picture is shown in Figure 9.3.
● 203
The pin names of the module are marked at its back as follows:
STATE: (not available as a pin. A HIGH is returned if the module is connected via
Bluetooth)
RXD: This is the serial data (UART) receive pin
TXD: This is the serial data (UART) transmit pin
GND: This is the power supply ground pin
VCC: This is the power supply pin
EN: (not available as a pin. Pulling this pin LOW disables the module)
HC-06 can operate with a power supply in the range +3.6V – 6V. Arduino Uno accepts
+3.3V as HIGH voltage and therefore the TX pin (out) of the HC-06 can be directly connect-
ed to an input of Arduino Uno. The HC-06 RX pin (in) cannot accept 5V and it should not be
connected directly to an Arduino Uno output pin. The simplest solution is to use a resistive
potential divider circuit made up of a 1K and 2K resistors.
By default, HC-06 operates at 9600 Baud and the Bluetooth pairing key is 1234.
Description: In this project, the on-board LED of Arduino UNO is controlled from an An-
droid mobile phone over a Bluetooth link.
Block Diagram: Figure 9.4 shows the block diagram of the project.
Circuit Diagram: As shown in Figure 9.5, HC-06 TX and RX pins are connected to pins 6
and 7 of the Arduino respectively. SoftwareSerial is used to communicate with the HC-06
module. A resistive potential divider circuit is used to lower the voltage input to the RX pin.
● 204
App Inventor Program: The App Inventor program of this project is the same as in chap-
ter 6, Project 1 (program: LED). You should install the program on to your Android mobile
phone using the QR code given in Figure 6.4.
Arduino Uno Program: Figure 9.6 shows the program listing (Arduino_LED). The pro-
gram uses the SoftwareSerial library and at the beginning of the program pins, 6 and 7
are configured as serial RX and TX respectively. The on-board LED at port 13 is configured
as an output and is turned OFF at the beginning of the program, and the Bluetooth link is
configured to operate at 9600 Baud. Inside the main program loop, the program checks
if data has been received through the Bluetooth link. If data is received and the received
character is "1" then the LED is turned ON. If on the other hand the received character "0"
then the LED is turned OFF.
/*---------------------------------------------------------------
BLUETOOTH LED CONTROL
=====================
In this project the on-board LED (at port 13) is controlled from
an Android mobile phone over a Bluetooth link using the HC-06
Bluetooth module on the Arduino Uno
Program: Arduino_LED
Date : February 2020
Author : Dogan Ibrahim
-------------------------------------------------------------------*/
#include <SoftwareSerial.h> // Software UART
SoftwareSerial Bluetooth(6, 7); // RX, TX
int rd;
int LED = 13; // LED port
void setup()
{
pinMode(LED, OUTPUT); // Conf as output
digitalWrite(LED, LOW); // LED OFF at start
Bluetooth.begin(9600); // Bluetooth speed
● 205
void loop()
{
if(Bluetooth.available() > 0) // If data available
{
rd = Bluetooth.read(); // Read data
Testing the Project: The steps to test the project are as follows:
• Power up your circuit with the HC-06 connected. You should see the red LED
flashing on your HC-06 module
• Pair the HC-06 with your Android mobile phone. If asked for a password, enter
1234
• Install App Inventor on your Android mobile phone (e.g. Figure 6.4) and start
the application
• Click Connect on your Android mobile phone and select HC-06 to make a con-
nection to the HC-06 on your Arduino Uno. You should see the text Connected
displayed in green after a short while. Also, the red LED will stop flashing on your
HC-06.
• Click LED ON and you should see the LED on your Arduino UNO turned ON as
shown in Figure 9.7
● 206
Figure 9.8 shows the circuit where the potential divider resistors are placed on a bread-
board and connection between the HC-06 and Arduino UNO is made using jumper wires.
Description: In this project, the 4 channel relay used in Project 2 in Chapter 8 is connect-
ed to the Arduino UNO and it is controlled from an Android mobile phone over a Bluetooth
link. Relay contacts can be connected to control various electrical equipment, such as home
appliances, toys, heating, and cooling equipment, etc.
Block Diagram: Figure 9.9 shows the block diagram of the project.
● 207
Circuit Diagram: The circuit diagram of the project is shown in Figure 9.10. The input pins
IN1, IN2, IN3 and IN4 of the relay module are connected to pins 8,9,10 and 11 of Arduino
UNO respectively.
App Inventor Program: In the design of the App Inventor, there are 8 buttons used to
turn ON or OFF the relay channels. The steps are as follows (see Figure 9.11):
• Insert a HorizontalArrangement and insert a Label on it. Set the Text of the
Label to 4 RELAY CONTROLLER
AlignHorizontal: Center: 3
AlignVertical: Center: 2
BackgroundColor: None
Height: 20 percent
Width: Fill parent
• Insert a Label on the VerticalArrangement. This Label will display the Blue-
tooth connection status. Configure this Label as follows:
● 208
Name: LblStatus
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Text: Status
TextColor: None
Visible: ticked
Name: ListPicker1
BackgrundColor: Default
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: none
TextColor: White
• Insert a BluetoothClient and a Clock component onto the Viewer. These are
shown at the bottom of the phone image
● 209
Figure 9.12 shows the block program of the project. Notice that part of the blocks that in-
terface with the Bluetooth device are the same as described in Project 1 of Chapter 6 and
are not repeated here. Only the additional blocks are described here.
The relay channels are controlled by sending the following string commands to them:
• Click Relay1ON and select when Relay1ON.Click do. This block will be activat-
ed when user clicks on button RELAY1 ON.
• Repeat for all the other 7 buttons as shown in Figure 9.12a and Figure 9.12b.
● 210
● 211
Arduino Uno Program: The Arduino UNO program (Arduino_Relays) listing is shown
in Figure 9.14. At the beginning of the program SoftwareSerial library is included and pins
6 and 7 are configured as UART RX and TX pins respectively. Relay input pins IN1, IN2,
IN3, and IN4 are assigned to port numbers 8, 9, 10, and 11 respectively. Inside the setup
routine, the relay inputs are configured as outputs and all relay inputs are set to LOW so
that the relays are deactivated at the beginning of the program. Inside the main program
loop, the program waits to receive data from the Android device over the Bluetooth link. If
the received data is 1on then relay pin IN1 is set LOW so that relay channel 1 is activated.
This is repeated for all the 4 relay inputs.
/*---------------------------------------------------------------
BLUETOOTH MULTIPLE RELAY CONTROL
================================
In this project a 4 channel relay module is connected to Arduino UNO.
The relays are controlled from the Android mobile phone.
Program: Arduino_Relays
Date : February 2020
Author : Dogan Ibrahim
-------------------------------------------------------------------*/
#include <SoftwareSerial.h> // Software UART
SoftwareSerial Bluetooth(6, 7); // RX, TX
String rd;
int IN1 = 8; // Relay IN1 pin
int IN2 = 9; // Relay IN2 pin
int IN3 = 10; // Relay IN3 pin
int IN4 = 11; // Relay IN4 pin
void setup()
{
pinMode(IN1, OUTPUT); // Conf IN1 as output
pinMode(IN2, OUTPUT); // Conf IN2 as output
pinMode(IN3, OUTPUT); // Conf IN3 as output
pinMode(IN4, OUTPUT); // Conf IN4 as output
● 212
void loop()
{
if(Bluetooth.available() > 0) // If data available
{
rd = Bluetooth.readString(); // Read data
if(rd == "1on")
digitalWrite(IN1, LOW); // Relay1 ON
else if(rd == "1off")
digitalWrite(IN1, HIGH); // Relay1 OFF
else if(rd == "2on")
digitalWrite(IN2, LOW); // Relay2 ON
else if(rd == "2off")
digitalWrite(IN2, HIGH); // Relay2 OFF
else if(rd == "3on")
digitalWrite(IN3, LOW); // Relay3 ON
else if(rd == "3off")
digitalWrite(IN3, HIGH); // Relay3 OFF
else if(rd == "4on")
digitalWrite(IN4, LOW); // Relay4 ON
else if(rd == "4off")
digitalWrite(IN4, HIGH); // Relay4 OFF
}
}
Figure 9.14 Arduino UNO program (Arduino_Relays) of the project
• Power up your circuit with the HC-06 connected. You should see the red LED
flashing on your HC-06 module
• Pair the HC-06 with your Android mobile phone. If asked for a password, enter
1234
• Install App Inventor on your Android mobile phone and start the application
● 213
• Click Connect on your Android mobile phone and select HC-06 to make a con-
nection to the HC-06 on your Arduino Uno. You should see the text Connected
displayed in green after a short while. Also, the red LED will stop flashing on your
HC-06.
• Click RELAY1 ON and you should see channel 1 of the relay clicking and at the
same time the LED of channel 1 should turn ON. An example run of the applica-
tion on an Android mobile phone is shown in Figure 9.15
Description: This project is very similar to Project 2, but here the state of a relay channel
is spoken through the Android mobile phone speaker after the corresponding button is
clicked to change it.
Block Diagram: The block diagram is the same as in Figure 9.9.
The Block program of the project is very similar to Figure 9.12a and Figure 9.12b except
that here, TextToSpeech component call TextToSpeech1.Speak Message is added to
every block with a button and the appropriate Text box is joined to speak the state of the
relay channel. Figure 9.16a and Figure 9.16b show the block program of the project.
● 214
● 215
Arduino Uno Program: The Arduino Uno program is the same as the one given in Figure
9.14 (Arduino_Relays).
The steps to test the project are the same as in the previous project. Make sure that you
turn up the volume control of your Android mobile phone.
Description: This project is very similar to Project 2, but here the relays are controlled
with speech.
App Inventor Program: In this project, it is assumed that the relays are connected to the
following electrical equipment and the commands sent to the Arduino UNO for controlling
each equipment is shown below:
• Insert a HorizontalArrangement and a Label and set the Text of the Label to
RELAY SPEECH CONTROL
● 216
Name: ButtonStart
BackgroundColor: Blue
FontBold: ticked
FontSize: 20
FontTypeface: default
Height: Automatic
Width: Automatic
Image: none
Shape: oval
Text: Start
Figure 9.19 shows the block program of the project. This is very similar to the one given
in Figure 9.1a and Figure 9.12b, but here the SpeechRecognizer blocks are added to the
program. The steps are as follows:
• Initialize a variable called speech. This variable will hold the text form of the
spoken command
• Initialize a variable called result. This variable will hold the command to be sent
to the Arduino Uno
● 217
• Create the LisPicker1 and Clock1 blocks for the Bluetooth as in the previous
projects
• Click ButtonStart and select when ButtonStart.Click do. Clicking this button
will enable the user to speak the required command
● 218
Arduino Uno Program: The Arduino Uno program is exactly the same as the one given in
Figure 9.14 (Arduino_Relays).
● 219
• Power up your circuit with the HC-06 connected. You should see the red LED
flashing on your HC-06 module
• Pair the HC-06 with your Android mobile phone. If asked for a password, enter
1234
• Click Connect on your Android mobile phone and select HC-06 to make a con-
nection to the HC-06 on your Arduino Uno. You should see the text Connected
displayed in green after a short while. Also, the red LED will stop flashing on your
HC-06.
• Click Start and you should see a request asking your permission to use the
audio. Give permission and speak your command, for example, say heater on.
You should now hear RELAY1 clicking and the LED corresponding to RELAY1 will
turn ON.
Figure 9.21 shows the application running on the Android mobile phone.
● 220
Description: In this project, a 16x2 (16 columns x 2 rows) LCD is connected to the Ardui-
no UNO, and data sent from the Android mobile phone are displayed on the LCD. Data can
be displayed on both rows of the LCD.
Background Information: In this project, the highly popular standard HD44780 compat-
ible LCD is used. HD44780 is one of the most popular alphanumeric LCD modules used in
industry and also by hobbyists. This module is monochrome and comes in different sizes.
Modules with 8, 16, 20, 24, 32, and 40 columns are available. Depending on the model
chosen, the number of rows varies between 1, 2 or 4. The display provides a 14-pin (or 16-
pin) connector to a microcontroller. Table 9.1 gives the pin configuration and pin functions
of a 14-pin LCD module. Below is a summary of the pin functions:
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 contrast
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 the contrast can be adjusted.
● 221
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 to write commands or character
data to the LCD module. When this pin is HIGH, character data or status information 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.
Block Diagram: The block diagram of the project is shown in Figure 9.22.
Circuit Diagram: The circuit diagram is same as in Figure 9.23. The connections between
the LCD and the Arduino UNO are as follows:
● 222
App Inventor Program: The App Inventor design (LCD_Arduino) is shown in Figure
9.24. The steps are as follows:
Columns: 3
Height: Automatic
Width: Fill parent
Rows: 2
Visible: ticked
• Insert 2 Labels and 2 TextBoxes onto the TableArrangement with the fol-
lowing configurations. Data for row 1 of the LCD should be entered to the top
TxtBox, while the data in the bottom TxtBox is displayed at row 2 of the LCD:
Name: ButtonSend
BackgroundColor: Default
FontBold: ticked
FontSize: 20
● 223
Height: Automatic
Width: Automatic
Text: Click to Send
TextColor: Red
Name: ButtonClear
BackgroundColor: Default
FontBold: ticked
FontSize: 20
Height: Automatic
Width: Automatic
Text: Click to Clear
TextColor: Blue
Figure 9.25 shows the block program of the project. The steps are as follows:
• Insert the blocks ListPicker1 and Clock1 as in the previous project as these
blocks establish Bluetooth communication with the Android mobile phone
• Click ButtonSend and select when ButtonSend.Click do. This block will be
activated when button Click to Send is clicked. Here we check if the Bluetooth
connection is established and then click BluetoothClient1 and select call Blue-
● 224
• Click ButtonClear and insert blank texts for both row1 and row2 of the LCD.
Clicking this button will clear the LCD screen
● 225
Arduino UNO Program: Figure 9.27 shows the Arduino UNO program (LCD_TEST). At
the beginning of the program, the Software Serial and LiquidCrystal header files are includ-
ed in the program. The RX and TX pins of the serial UART are defined as 6 and 7 respec-
tively. The connections between the LCD and the Arduino UNO are then defined. Inside the
setup routine, the LCD is initialized as 16x2 and the Bluetooth Baud rate is set to 9600. The
remainder of the program runs inside the main program loop. Here, the program checks if
data has arrived from the Bluetooth serial port. If so, the received data is stored in string
variable rd. Integer variable hash stores the position of character # in the receive data by
calling the built-in function indexOf(). Remember that the data for row1 and row2 of the
LCD are separated with the # character, and the first character has position 0. Then, the
data for the first row is extracted using built-in function substring() and this data is stored
in string variable firstrow. Similarly, the data for the second row of the LCD is extracted
and is stored in string variable secondrow. The LCD is cleared and the data for row1 is
sent to the LCD by calling function lcd.print(). Notice that clearing the LCD sets its cursor
to the position (0, 0) which is the top left home position of the cursor. The cursor is then
set to row2 of the LCD by calling function lcd.setCursor(0, 1) and the contents of variable
secondrow are displayed at row2 of the LCD.
/*---------------------------------------------------------------
LCD
===
In this project an LCD is connected to the Arduino UNO. Messages
received from the Android mobile phone are displayed on the LCD.
Program: LCD_TEST
Date : February 2020
Author : Dogan Ibrahim
-------------------------------------------------------------------*/
#include <SoftwareSerial.h> // Software UART
#include <LiquidCrystal.h> // LCD library
SoftwareSerial Bluetooth(6, 7); // RX, TX
//
● 226
void setup()
{
lcd.begin(16, 2); // LCD os 16x2
Bluetooth.begin(9600); // Bluetooth speed
}
void loop()
{
if(Bluetooth.available() > 0) // If data available
{
rd = Bluetooth.readString(); // Read data
hash = rd.indexOf('#'); // LOcate second row
firstrow = rd.substring(0, hash); // First row data
secondrow = rd.substring(hash+1); // Second row data
lcd.clear(); // Clear LCD
lcd.print(firstrow); // Send first row data
lcd.setCursor(0,1); // At second row
lcd.print(secondrow); // Send second row data
}
}
Some of the additional LCD functions available on the Arduino UNO IDE are given below (for
full details, see link: https://www.arduino.cc/en/Reference/LiquidCrystal):
Figure 9.28 shows an example run of the program on the Android mobile phone where the
texts First row and Second row are sent to the Arduino UNO. The texts displayed on the
LCD are shown in Figure 9.29. Notice that the character length must not be greater than
16 for each row.
● 227
Background Information: In this project, the LM35DZ analog temperature sensor chip
is used. This is a 3-pin small sensor as shown in Figure 9.30. The sensor has the following
pin definitions:
The output voltage is directly proportional to the temperature where the temperature is
given by the formula:
T = Vo / 10
Where, T is the measured temperature in ºC, and Vo is the sensor output voltage in milli-
volts. For example, if the output voltage is 250mV then the measured temperature is 25ºC.
● 228
Block Diagram: The block diagram of the project is shown in Figure 9.31.
Circuit Diagram: Figure 9.32 shows the circuit diagram of the project.
● 229
App Inventor Program: Figure 9.33 shows the App Inventor design. The steps are:
Name: Label1
BackgroundColor: None
FontBold: ticked
FontSize: 30
Height: Automatic
Width: Automatic
Text: Temperature (C)
TextColor: Red
Name: TxtTemperature
BackgroundColor: Orange
FontBold: ticked
FontSize: 70
Height: 15 percent
Width: 65 percent
Hint: blank
Text: blank
TextColor: Blue
● 230
Figure 9.34 shows the block program of the project. The steps are as follows:
• Insert the blocks ListPicker1 and Clock1 as in the previous project as these
blocks establish Bluetooth communication with the Android mobile phone
• Click TempClock and select when TempClock.Timer do. This block will be acti-
vated periodically which will get the temperature readings from the Arduino UNO.
If Bluetooth is connected, then call BluetoothClient1.ReceiveText and load
the received text into TxtTemperature.Text. You should insert a Join block and
insert characters º and C. To insert the degree symbol, press the Alt key and en-
ter 0176. The temperature will be displayed in this TextBox in the form of nn.nºC.
● 231
Arduino UNO Program: Figure 9.36 shows the Arduino UNO program (Arduino_LM-
35DZ). At the beginning of the program header file SoftwareSerial is included in the pro-
gram and the serial UART RX and TX pins are assigned to pins 6 and 7 respectively and
variable LM35DZ is assigned to analog input A0. Inside the setup routine, the Bluetooth
Baud rate is set to 9600. The remainder of the program runs inside the loop where the
temperature is read from analog input A0 using the built-in function call analogRead().
The value read is then converted into millivolts by multiplying with 5000 and dividing by
1024. This is because the ADC on the Arduino UNO is 10-bits wide, having 1024 quantiza-
tion levels and the ADC reference voltage is 5V. The temperature in Celsius is then found
by dividing the voltage by 10. Variable rd stores the temperature after converting it into a
string. The length of the converted data is kept as 4 digits so that the result is in the format:
nn.n or n.nn. Finally, the temperature reading is sent to the Android mobile phone using
the statement Bluetooth.print().
/*---------------------------------------------------------------
TEMPERATURE SENSOR
==================
Program: Arduino_LM35DZ
Date : February 2020
Author : Dogan Ibrahim
-------------------------------------------------------------------*/
#include <SoftwareSerial.h> // Software UART
SoftwareSerial Bluetooth(6, 7); // RX, TX
String rd;
int LM35DZ = A0; // Analog input A0
int val = 0;
float mV, T;
void setup()
● 232
{
Bluetooth.begin(9600); // Bluetooth speed
}
void loop()
{
val = analogRead(LM35DZ); // Read analog data
mV = val * 5000.0 / 1024.0; // Convert into mV
T = mV / 10.0; // Temperature in C
rd = String(T); // Convert to string
if(rd.length() > 4)rd = rd.substring(0, 4); // 4 digits only
● 233
Description: In this project, a sensor module is connected to Arduino UNO to measure and
send the ambient temperature, humidity, and the Dew Point readings to the Android mobile
phone over the Bluetooth link.
Background Information: In this project, the DHT11 module is used. This is a 3 pin sen-
sor module (some versions are 4 pins) that returns the ambient temperature and humidity.
The specifications of this module are:
• 3 to 5V operation
• 0 - 50ºC temperature range (±2ºC accuracy)
• 20-80% relative humidity range (5% accuracy)
• 2.5mA operating current
• 1Hz sampling rate
The Dew Point temperature is calculated using the following formula by Mark G. Lawrence
(this formula is very accurate for humidity values greater than 50%):
Td = T – [(100 – RH) / 5]
Where Td is the dew point temperature in degrees Celsius, T is the ambient temperature
in degrees Celsius, and RH is the relative humidity as a percentage. For example, if the
ambient temperature is 20ºC and the relative humidity is 60%, the dew point is calculated
to be 12ºC.
Block Diagram: Figure 9.39 shows the block diagram of the project.
● 234
Circuit Diagram: The circuit diagram of the project is shown in Figure 9.40 where the
Signal pin of the DHT11 sensor is connected to pin 8 of the Arduino UNO, and the HC-06
Bluetooth module is connected as in the previous projects.
App Inventor Program: Figure 9.41 shows the design of the project (see Figure 9.41)
• Insert a HorozontalArrangement with its Height and Width both set to Fill
parent and its BackgroundColor set to White
● 235
The block program is shown in Figure 9.42. Only the additional blocks to the Bluetooth
blocks are described here. The steps are:
• Initialize a variable called THD. This variable will store the data sent by the Ar-
duino Uno. Also, initialize a variable called list and assign an empty list to this
variable. This list variable will store the extracted temperature, humidity, and
dew point values.
• Click ClockGetData and select when ClockGetData.Timer do. This block will
be activated to read the data sent by the Arduino UNO. Check if Bluetooth is
connected
• The data items sent by the Arduino UNO are separated by commas. Thus, for
example, the temperature, humidity, and dew point are sent as nn.nn,mm.
mm,pp.pp. Here, we are using a split text at block with comma as the sep-
arator to extract the 3 items and store them in the list variable list. Index 1
of this variable is the temperature, index 2 is the humidity, and index 3 is the
dew point.
● 236
Arduino UNO Program: Figure 9.44 shows the program (program: Arduino_DHT11).
Before developing the program. we have to install the library for the DHT11 module. The
steps are as follows:
• Start your Arduino UNO and click Sketch -> Include Library -> Manage Li-
braries
• Enter DHT and look for DHT sensor library by Adafruit as shown in Figure
9.43.
• Click Install
• Search for the library Adafruit Unified Sensor by Adafruit (you may have to
scroll to find it), and click Install
● 237
At the beginning of the program DHT11 library is included in the program and the DHT11
signal pin is assigned to port number 8. SoftwareSerial is assigned to pins 6 and 7 as
before. Inside the setup routine DHT11 library and Bluetooth are started. The remainder
of the program runs inside the loop. Here, the temperature and humidity are read from
the DHT11 as floating-point numbers and the dew point is calculated. The temperature,
humidity and dew point are converted into strings and stored in variables TS, HS, and DS
respectively. The three variables are joined with a comma separating them and the result
(in string variable rd) is sent to the Android mobile phone using the Bluetooth link. This
process is repeated after a delay of 5 seconds.
/*--------------------------------------------------------------------
Temperature,Humidity,Dew Point
==============================
Program: Arduino_DHT11
Date : February 2020
Author : Dogan Ibrahim
------------------------------------------------------------------------*/
#include "DHT.h" // DHT library
#include <SoftwareSerial.h> // Software UART
void setup()
{
dht.begin(); // Start DHT11
Bluetooth.begin(9600); // Bluetooth speed
}
void loop()
{
float T = dht.readTemperature(); // Read temperature
String TS = String(T); // As string
float H = dht.readHumidity(); // Read humiddity
String HS = String(H); // As string
float D = T - ((100.0 - H)/5.0); // Dew point
String DS = String(D); // As string
● 238
An example run of the program on the Android mobile phone is shown in Figure 9.45.
Description: This is an ON-OFF temperature control project which controls the tempera-
ture of a room. A set-point temperature is entered by the user on the Android mobile phone
through a slider. The temperature of the room is compared to the set-point temperature
and if it is lower than the set-point then a relay is activated which turns ON a heater to
raise the temperature in the room When the room temperature is just above the set-point
then the relay is turned OFF. Thus, the temperature of the room is always very close to the
required set-point temperature.
● 239
Although the ON-OFF based temperature control is very simple, it has some disadvantages.
Firstly, the temperature is not controlled very accurately. i.e. room temperature is never
exactly equal to the set-point temperature. Secondly, relay lifetime may be short since it
is activated and deactivated many times unless a semiconductor type relay is used. Figure
9.46 shows the block diagram of the ON-OFF type temperature control in the form of a
feedback control system.
Block Diagram: Figure 9.47 shows the block diagram of the project.
Circuit Diagram: The circuit diagram of the project is shown in Figure 9.48, where an
LM35DZ type analog temperature sensor chip is connected to analog input A0 and the relay
is connected to pin 8 of the Arduino UNO.
● 240
App Inventor Program: Figure 9.49 shows the App Inventor design. The screen is in 3
parts: the upper part is used to make a connection to Arduino UNO through Bluetooth. The
middle part receives the room temperature measurements from the Arduino UNO and dis-
plays them on a TextBox. The bottom part has a TextBox and a Slider. The user moves the
slider arm to set the set-point temperature which is displayed by the TextBox. If the room
temperature is below the set-point then the background colour of the bottom part changes
to pink to indicate that the heater has been activated.
• Insert a VerticalArrangement with a Label and a TextBox on it. Set the Text
of the Label to ROOM TEMPERATURE (C), and the name of the TextBox to
TxtRoom. Set the Width of the TextBox to 20 percent
● 241
Figure 9.50 shows the block program of the project. The steps are as follows:
• Click Slider1 and select when Slider1.PositionChanged do. This block will
be activated when the slider arm is moved to set a new temperature set-point.
Assign the TxtSet.Text and variable SetTemp to the Slider value so that the
TxtSet displays the value selected by the user and also variable SetTemp holds
the set-point value set by the user
• Click ClockGetData and select when ClockGetData.Timer do. This block will
be executed at periodic intervals to read the room temperature sent by the Ar-
duino UNO. Check that the Bluetooth connection is established
• If there is data sent by the Arduino UNO, read the data and store it in variable
RoomTemp. Display this reading on TxtRoom
• If the room temperature is less than the set-point value, then change the back-
ground colour to pink and send a "1" to the Arduino UNO to command it to
activate the relay. If on the other hand, the room temperature is not less than
the set-point, then leave the background colour as it was and send a "0" to the
Arduino UNO to command it to deactivate the relay
● 242
The QR code of the project is shown in Figure 9.51. Figure 9.52 shows an example run of
the project when the set-point is lower than the room temperature. In Figure 9.53, the set-
point is higher than the room temperature and the background colour is changed to pink to
indicate that the relay is activated.
● 243
Arduino UNO Program: Figure 9.54 shows the program listing (program: Arduino_ON_
OFF_TEMP). This program is similar to the one given in Figure 9.36, except that here the
temperature is sent as an integer number to the Android mobile phone. Also, the relay is
activated if "1" is received from the Android mobile phone, and the relay is deactivated if
"0" is received from the mobile phone.
● 244
/*---------------------------------------------------------------
ON-OFF TEMPERATURE CONTROL
==========================
Program: Arduino_ON_OFF_TEMP
Date : February 2020
Author : Dogan Ibrahim
-------------------------------------------------------------------*/
#include <SoftwareSerial.h> // Software UART
SoftwareSerial Bluetooth(6, 7); // RX, TX
String rd;
int LM35DZ = A0; // Analog input A0
int val = 0;
int RELAY = 8; // Relay pin
float mV, T;
void setup()
{
pinMode(RELAY, OUTPUT); // Configure Relay as output
digitalWrite(RELAY, LOW); // Deactivate relay
Bluetooth.begin(9600); // Bluetooth speed
}
void loop()
{
val = analogRead(LM35DZ); // Read analog data
mV = val * 5000.0 / 1024.0; // Convert into mV
T = mV / 10.0; // Temperature in C
int Tint = (int)T; // Convert to int
Bluetooth.print(Tint); // Send to Android
● 245
}
Figure 9.54 Arduino UNO program (Arduino_ON_OFF_TEMP)
Description: In the previous project when the Bluetooth connection is broken the state
of the relay is not known. For example, if the relay is ON then it may stay ON after the
Bluetooth connection is broken. This may not be safe. In this modified project, when the
Bluetooth connection is broken the relay is deactivated automatically.
Figure 9.55 shows the design of the modified program (TEMP_ON_OFF_2). In this design,
a button named ButtonDisconnect is used. Clicking this button will deactivate the relay
and disconnect from the Bluetooth. As shown in Figure 9.55, two additional Clock com-
ponents are added to the design. These components are used to deactivate the relay and
disconnect from the Bluetooth.
Figure 9.56a and Figure 9.56b show the block program of the project. The disconnection
process is as follows:
● 246
● 247
Description: In this project, a stepper motor is connected to the Arduino UNO and the
motor is controlled from the Android mobile phone. A slider control on the mobile phone
controls how many times the motor should rotate. The motor is rotated only in one direc-
tion (Clockwise) for simplicity.
Background Information:
Stepper Motors
Stepper motors are DC motors that rotate in small steps. These motors have several coils
that are energized in sequence, causing the motor to rotate one step at a time. These mo-
tors are used in many precision motion control applications, in robotic arms, and in mobile
robots to drive the wheels.
Unipolar motors can be rotated in reverse by reversing the sequence of applied pulses.
Unipolar stepper motors can be driven in full stepping mode or half-stepping mode. The
most popular drive modes are 1 phase full-step, 2 phase full-step, and 2 phase half-step.
In 1 phase full-step mode, as shown in Table 9.1, each motor winding receives one pulse
per step. This mode has the disadvantage that the available torque is low.
Step a c b d
1 1 0 0 0
2 0 1 0 0
3 0 0 1 0
4 0 0 0 1
Table 9.1 1 Phase full-step mode
● 248
In 2 phase full-step mode, as shown in Table 9.2, two motor windings receive pulses per
step. The advantage of this mode is that a higher torque is available from the motor.
Step a c b d
1 1 0 0 1
2 1 1 0 0
3 0 1 1 0
4 0 0 1 1
Table 9.2 2 Phase full-step mode
In 2 phase half-step mode, as shown in Table 9.3, two motor windings sometimes receive
pulses and sometimes only one winding receives a pulse. Because the motor is driven at
half-step mode, 8 steps are required to complete a cycle instead of 4. This mode gives
higher precision, but at the expense of lower torque.
Step a c b d
1 1 0 0 0
2 1 1 0 0
3 0 1 0 0
4 0 1 1 0
5 0 0 1 0
6 0 0 1 1
7 0 0 0 1
8 1 0 0 1
● 249
RPM = 60β/360T
or, RPM = β/6T
where RPM is the number of revolutions per minute, β is the step constant of the motor in
degrees, and T is the time between the steps in seconds.
As an example, assume that the step constant of a stepper motor is 10 degrees (β = 10º).
If we want to rotate this motor at a speed of 1000 RPM (assuming that the motor is capable
of rotating this fast), the time between the pulses is calculated as:
n = v/β
For example, assuming that the step constant is 5º (β = 5) and that we want the motor to
rotate by 200 degrees, the required number of steps is:
n = 200/5 = 40
Block Diagram: Figure 9.59 shows the block diagram of the project. A stepper motor
driver module is used to drive the motor windings.
● 250
Circuit Diagram: In this project, a small 28BYJ-48 type unipolar stepper motor (see Fig-
ure 9.60) is used. This motor has the following specifications:
Rated voltage: 5V
Number of phases: 4
Gear ratio: 64
Frequency: 100Hz
Step angle: 11.25º / step
Maximum speed: 18 RPM
In this project, the motor is driven using a ULN2003 IC-based motor driver module shown
in Figure 9.61 together with its circuit diagram. This module has four input connections
labeled IN1, IN2, IN3, and IN4. The motor is plugged into the socket in the middle of the
module. Four LEDs, labeled A, B, C, D are provided to see the status of the motor windings.
Power to the module is applied through the bottom two header pins on the right-hand side
of the module. The LEDs can be enabled by shorting the two top header pins on the right-
hand side of the module. In this project, the module was powered from an external +5V
DC power supply for the motor.
Figure 9.62 shows the circuit diagram of the project. Port pins 8, 9 10, and 11 of the Ardui-
no UNO are connected to driver module inputs IN1, IN2, IN3, and IN4 respectively.
● 251
App Inventor Program: Figure 9.63 shows the App Inventor program. Here, a Slider
component is used to set the required number of turns of the stepper motor. The steps are:
• Insert a HorizontalArrangement and set its Height and Width to Fill parent.
Insert the image motor.jpg on it.
● 252
Figure 9.64 shows the block program of the project. Only the blocks other than the ones
used to establish Bluetooth communication are described here:
• Initialize a variable called Revs which will store the number of revolutions set by
the slider.
• Click Slider1 and select when Slider1.PositionChanged do. This block will be
executed when the slider arm position is changed to select the number of revo-
lutions. Store the selected value in variable Revs and also display it on TxtRevs.
• When the Start button is clicked check if the Bluetooth connection is valid, and if
so send the required number of revolutions to the Arduino UNO.
● 253
Arduino UNO Program: The 28BYJ-48 stepper motor can either be operated in full-step
or half-step modes.
Full-step Mode
In full-step mode, there are 4 steps per cycle and 11.25 degrees/step, corresponding to
32 steps per one revolution of the internal motor shaft. Because the motor is geared with
a gear ratio of 64 (in fact the gear ratio is 63.68395), the number steps for one external
complete revolution are 2048 steps/revolution (512 cycles with 4 steps per cycle).
Table 9.4 shows the motor winding sequence for the full-step mode (this sequence is re-
peated. Reversing the sequence reverses the direction of rotation).
1 1 1 0 0
2 0 1 1 0
3 0 0 1 1
4 1 0 0 1
Half-step Mode
The half-step mode with 8 steps per cycle is recommended by the manufacturer. In half-
step mode we have 5.625 degrees/step, corresponding to 64 steps per one revolution of
the internal motor shaft. Because the motor is geared with a gear ratio of 64, the number
of steps for one external complete revolution is 4096 steps/revolution (512 cycles with 8
steps per cycle).
Table 9.5 shows the motor winding pulse sequence for the half-step mode (this sequence
is repeated. Reversing the sequence reverses the direction of rotation).
● 254
1 1 0 0 0
2 1 1 0 0
3 0 1 0 0
4 0 1 1 0
5 0 0 1 0
6 0 0 1 1
7 0 0 0 1
8 1 0 0 1
In this project, the stepper motor is controlled in Full-Step mode and Figure 9.66 shows the
program listing (program: Arduino_Stepper). As described earlier, the speed depends on
the delay inserted between each step. In Full-step mode, there are 2048 steps in a com-
plete revolution. The motor speed in RPM is given by the following equation:
Where, RPM is the motor speed in revolutions per minute, and T is the delay between each
step in milliseconds. We usually want to know how much delay to insert between each step
so that the required number of revolutions can be achieved. This is given in milliseconds by:
T = 29.3 / RPM
At the beginning of the program, the StepsPerCycle of the motor is set to 512, motor
RPM (Revolutions Per Minute) is set to 10 (maximum is about 18), and the pulses to con-
trol the motor in Full-step mode are defined in integer array FullMode as follows:
The step delay (StpDelay) is calculated by dividing 29.3 by the required RPM as described
earlier. In this project, the motor is rotated in one direction (Clockwise) only for simplicity.
Function CLOCKWISE sends 4 pulses to the motor with a delay of StepDelay milliseconds
between each pulse. This ensures that the motor speed is as required. This is repeated
StepsPerRevolution times so that the motor makes a complete revolution. This whole
process is then repeated count times which is the number of times we want the motor to
rotate complete revolutions.
Function CLOCKWISE calls function SendPulse() which configures the output pins and
sends the required bit patterns to output pins IN1, IN2, IN3 and IN4 of the motor driver.
● 255
Function BitRead() extracts the bits from a variable. For example, if the input parameters
to this function (i and j) are 0b00011 and 2 respectively, then the function will return 1
which is the bit at position 2 of the data.
/*---------------------------------------------------------------
Stepper Motor CONTROL
=====================
Program: Arduino_Stepper
Date : February 2020
Author : Dogan Ibrahim
-------------------------------------------------------------------*/
#include <SoftwareSerial.h> // Software UART
SoftwareSerial Bluetooth(6, 7); // RX, TX
#define StepsPerCycle 512
int FullMode[4] = {0b01100, 0b00110, 0b00011, 0b01001};
#define RPM 10
int StpDelay = (29.3 / RPM);
String rd;
int IN1 = 8; // Driver pin IN1
int IN2 = 9; // Driver pin IN2
int IN3 = 10; // Driver pin IN3
int IN4 = 11; // Driver pin IN4;
//
// This function rotates the stepper motor CLOCKWISE by count turns
//
void CLOCKWISE(int count, unsigned int StepDelay)
{
unsigned int i, j, m, k;
● 256
}
}
}
//
// This function extract the bits of a variable
//
unsigned char BitRead(char i, char j)
{
unsigned m;
m = i & j;
if(m != 0)
return(1);
else
return(0);
}
//
// This function sends a bit to pins IN1,IN2,IN3,IN4 of the driver board
//
void SendPulse(int k)
{
int IN1bit, IN2bit, IN3bit, IN4bit;
void setup()
{
pinMode(IN1, OUTPUT); // Configure IN1 as output
pinMode(IN2, OUTPUT); // Configure IN2 as output
pinMode(IN3, OUTPUT); // Configure IN3 as output
pinMode(IN4, OUTPUT); // Configure IN4 as output
● 257
void loop()
{
if(Bluetooth.available()) // Is data available
{
rd = Bluetooth.readString(); // read no of revs
int Turns = rd.toInt(); // As integer
CLOCKWISE(Turns, StpDelay); // Rotate motor
}
}
Figure 9.66 Arduino UNO program listing (Arduino_Stepper)
9.15 Summary
In this chapter, we developed several projects using Arduino UNO with MIT App Inventor
and Bluetooth connectivity. We learned that external hardware is required for an Arduino
UNO to communicate using Bluetooth.
In the next chapter, we will develop projects using Wi-Fi with Arduino UNO and MIT App
Inventor.
● 258
10.1 Overview
In the last chapter, we developed several projects for Arduino UNO using MIT App Inven-
tor. In this chapter, we will develop similar projects but this time using Wi-Fi to establish
communication between Arduino UNO and Android mobile phone. Note that the QR codes
given in the projects were valid only for 2 hours at the time they were created, and they
cannot be used to install the apps to your mobile phone. They are only given here for com-
pleteness.
ESP-01 is used in the Wi-Fi projects of this Chapter. ESP-01 communicates with the host
processor through its TX and RX serial port pins. It is an 8-pin board, having the pin names:
● 259
ESP-01 pins are not standard breadboard compatible and an adaptor is required if the
board is to be attached to a breadboard (see Figure 10.2).
ESP-01 is controlled by AT commands. Some of the commonly used AT commands for Wi-Fi
operation are:
Figure 10.3 shows how the ESP-01 can be connected to the Arduino UNO. The TX and RX
pins of ESP-01 are connected to the serial receive and transmit pins of the Arduino UNO
respectively. Here, either the on-board UART at pins 0 and 1 can be used, or the soft-
ware-based serial UART can be used. The RX input pin of the ESP-01 is not compatible with
the Arduino output since the Arduino output can be as high as +5V. As a result of this, a
resistive potential divider circuit is used to lower the voltage to the RX pin of the ESP-01.
● 260
Description: In this project, an LED is connected to the Arduino Uno board and it is con-
trolled from the Android mobile phone using a Wi-Fi link.
Block Diagram: Figure 10.4 shows the block diagram of the project.
Circuit Diagram: The circuit diagram of the project is shown in Figure 10.5. The LED is
connected to port pins 8 of the Arduino UNO through current limiting resistors.
App Inventor Program: The design of the project is shown in Figure 10.6. The steps are
as follows:
● 261
• Click tab Connectivity and insert a Web component onto the Viewer
Figure 10.7 shows the block program of the project. The steps are:
• Initialize a variable called ip and set it to the IP address of the ESP-01 processor
(see later how to find the IP address of the ESP-01)
• Click LEDOn and select when LEDOn.Click do. This block will be activated
when Button LED ON is clicked.
• Click Web1 and select set Web1.Url to. Insert a Join block and enter the ip
address of the ESP-01 followed by the text LEDON. In this project, the HTTP GET
command 192.168.1.160/LEDON will send the text /LEDON to Arduino UNO
to turn ON the LED. At the same time, change the TextColor of this Button to
Red to indicate that the LED has been turned ON
• Repeat the above for the Button LED OFF. This time the HTTP GET command
192.168.1.160/LEDOFF will send the text /LEDOFF to turn OFF the LED
● 262
• Click Screen1 and select when Screen1.ErrorOccuurred do. This block will be
activated if an error is detected by the program. We will ignore any such errors.
Get the error messages and store them in TxtError. Such error messages will
not be visible.
Arduino UNO Program: Figure 10.9 shows the Arduino UNO program (ArduinoLED).
At the beginning of the program the software serial header is included in the program and
the RX and TX pins of the software UART are assigned to pins 6 and 7 respectively, and the
name of the serial port is set to wifi. Inside the setup routine, the serial UART port is set to
115200 which is the default Baud rate of the ESP-01. The remainder of the program is ex-
ecuted inside the loop. Here, the program checks if data has been received by the software
UART from the Android mobile phone. If so, the data is received by calling built-in function
readString(). The program then uses the built-in function indexOf() to find out whether
or not the received data contains the characters LEDON. The function returns the index of
the characters LEDON. If LEDON is not found in the received data, then -1 is returned by
the function.
● 263
Notice that the data received from the Android mobile phone when button LED ON is clicked
contains the following words (this is why we check if it contains the characters LEDON):
If characters LEDON is received then the LED is turned ON by calling function digital-
Write(LED, HIGH).
If on the other hand the characters LEDOFF is received then the LED is turned OFF by
calling function digitalWrite(LED, LOW).
Notice that HTTP success code 200 OK is sent to the Android mobile phone after a suc-
cessful operation.
/**********************************************************************
* WEB SERVER TO CONTROL an LED
* ============================
*
* This is a web server program. An LED is connected to the Arduino
* UNO. The project controls the LED from the Android mobile phone.
*
* File: ArduinoLED
* Author: Dogan Ibrahim
* Date: February 2020
*********************************************************************/
#include <SoftwareSerial.h> // Include serial
//
// Connect to local Wi-Fi router and become a server
//
void setup()
{
pinMode(LED, OUTPUT); // LED is output
wifi.begin(115200); // ESP-01 Baud rate
SendCmd("AT+RST"); // Reset ESP-01
delay(5000);
SendCmd("AT+CWMODE=1");
delay(3000);
SendCmd("AT+CIFSR");
delay(3000);
SendCmd("AT+CIPMUX=1");
delay(3000);
● 264
SendCmd("AT+CIPSERVER=1,80");
delay(3000);
}
void loop()
{
String received="";
//
// This function sends the command cmd to ESP-01
//
boolean SendCmd(String cmd)
{
wifi.println(cmd); // Send command
}
Figure 10.9 Arduino UNO program (ArduinoLED) of the project
● 265
• We now need to find the IP address of the ESP-01. Perhaps the easiest way to
find this is to use an app on our Android mobile phone to show all the devices
connected to our Wi-Fi router. The one used by the author was called Who Use
My WiFi? Network Tool by Amzwaru (see Figure 10.10), available on Android
Play Store.
• The ESP-01 processor is shown as Espressif Inc in the list (see Figure 10.11).
The author's IP address was 192.168.1.160 as shown in the Figure.
• Build the App Inventor program after entering the IP address of the ESP-01 pro-
cessor, and start the application on your Android mobile phone.
• Click LED ON and you should see that the LED will turn ON.
● 266
In the Arduino Uno program in Figure 10.9, we have used delays between the commands
sent to the ESP-01 processor. The exact amount of the delay required is not known and as
a result of this, the delay may be too short and the ESP-01 processor may not respond cor-
rectly. Figure 10.13 shows a modified program (ArduinoLED2) where the response codes
of the commands are checked and the function returns as soon as the correct response is
received.
/**********************************************************************
* WEB SERVER TO CONTROL an LED
* ============================
*
* This is a web server program. An LED is connected to the Arduino
* UNO. The project controls the LED from the Android mobile phone.
*
* In this version of the program the response codes from the ESP-01
* are checked
*
* File: ArduinoLED2
* Author: Dogan Ibrahim
* Date: February 2020
*********************************************************************/
#include <SoftwareSerial.h> // Include serial
#define TIMOUT 6000 // Timeout 6 secs
char ch;
int LED = 8; // LED port
SoftwareSerial wifi(6, 7); // RX, TX
//
// Connect to local Wi-Fi router and become a server
//
void setup()
{
pinMode(LED, OUTPUT); // LED is output
wifi.begin(115200); // ESP-01 Baud rate
● 267
void loop()
{
String received="";
//
// This function sends the command cmd to ESP-01. The return status of
// the command is checked (although not used here)
//
boolean SendCmd(String cmd, String ret)
{
wifi.println(cmd); // Send command
if(ChkReturnStatus(ret))
● 268
//
// This function checks the return status of the command which is usually
// OK or READY. If there is no response within the timeout period which is
// 5 seconds then a false is returned. If correct response is returned by
// ESP-01 then the function returns true
//
boolean ChkReturnStatus(String retword)
{
byte retword_length, cnt = 0;
long ExpectedTime;
retword_length = retword.length();
ExpectedTime = millis() + TIMOUT;
while(millis() < ExpectedTime)
{
if (wifi.available())
{
ch = wifi.read(); // Read a char
Description: In this project, a 4 channel relay module is connected to the Arduino UNO
and it is controlled from the Android mobile phone using Wi-Fi communication.
Block Diagram: Figure 10.14 shows the block diagram of the project.
● 269
Circuit Diagram: The circuit diagram of the project is shown in Figure 10.15 where the
relay module pins IN1, IN2, IN3, and IN4 are connected to pins 8, 9, 10, and 11 of Arduino
UNO respectively. An external +5V power supply is used to power the relay module.
App Inventor Program: The design of the project is shown in Figure 10.16. The steps
are as follows:
● 270
• Insert a WebViewer component onto the Viewer and unclick it to be not visible
Figure 10.17a and Figure 10.17b shows the block program of the project. The relay chan-
nels are controlled as follows
• Initialize a variable called ip and enter the IP address of your ESP-01 processor.
In this example, the IP address was 192.168.1.160
• Click RELAY1On and select when RELAY1On.Click do. This block will be acti-
vated when button RELAY1 ON is clicked.
● 271
• Click RELAY1On and set the button colour to red which clicked ON. Also, set the
button colour to black when clicked OFF.
● 272
Arduino UNO Program: Figure 10.19 shows the Arduino UNO program (Arduino4_Re-
lay). At the beginning of the program, inputs IN1, IN2, IN3 and IN4 of the relay are as-
signed to port numbers 8, 9, 10, and 11 respectively. Inside the setup routine, the relay
inputs are configured as outputs and all relay channels are deactivated. Also, the code to
connect the ESP-01 to Wi-Fi is included in this routine. The code inside the loop receives
the commands sent by the Android mobile phone and controls the relays accordingly. If
for example, the command contains the characters /on1 then RELAY1 is activated by the
statement digitalWrite(IN1, LOW) and so on for the other commands.
/**********************************************************************
* WEB SERVER TO CONTROL 4 Channel Relay
* =====================================
*
* This is a web server program. A 4 channel relay is connected to the
* Arduino UNO and it is controlled from the Android mobile phone.
*
* File: Arduino4_Relay
* Author: Dogan Ibrahim
* Date: February 2020
*********************************************************************/
#include <SoftwareSerial.h> // Include serial
#define TIMOUT 6000 // Timeout 6 secs
● 273
char ch;
int IN1 = 8; // Relay IN1
int IN2 = 9; // Relay IN2
int IN3 = 10; // Relay IN3
int IN4 = 11; // Relay IN4
//
// Connect to local Wi-Fi router and become a server
//
void setup()
{
pinMode(IN1, OUTPUT); // IN1 is output
pinMode(IN2, OUTPUT); // IN2 is output
pinMode(IN3, OUTPUT); // IN3 is output
pinMode(IN4, OUTPUT); // IN4 is output
void loop()
{
String received="";
● 274
//
// This function sends the command cmd to ESP-01. The return status of
// the command is checked (although not used here)
//
boolean SendCmd(String cmd, String ret)
{
wifi.println(cmd); // Send command
if(ChkReturnStatus(ret))
return true; // Check return status
}
//
// This function checks the return status of the command which is usually
// OK or READY. If there is no response within the timeout period which is
// 5 seconds then a false is returned. If correct response is returned by
// ESP-01 then the function returns true
//
boolean ChkReturnStatus(String retword)
{
byte retword_length, cnt = 0;
long ExpectedTime;
retword_length = retword.length();
ExpectedTime = millis() + TIMOUT;
while(millis() < ExpectedTime)
{
if (wifi.available())
{
ch = wifi.read(); // Read a char
● 275
• Build the App Inventor program after entering the IP address of the ESP-01 pro-
cessor, and start the application on your Android mobile phone.
• Click RELAY1 ON and you should hear a relay click and also the LED of RELAY1
will turn ON.
● 276
Description: In this project, a 4 channel relay module is connected to the Arduino UNO
and it is controlled by speech from an Android mobile phone. For simplicity, only 2 channels
are controlled in this program, but it can be extended to 4 channels very easily.
Block Diagram: The block diagram of the project is the same as in Figure 10.14.
Circuit Diagram: The circuit diagram of the project is the same as in Figure 10.15.
App Inventor Program: The design of the project is shown in Figure 10.21. The steps
are as follows:
• Insert a WebViewer component and unclick its visible box so that it is not visible
Figure 10.22 shows the block diagram of the project. The steps are as follows:
• Initialize 3 variables called ip, speech, and android. Load the ESP-01 proces-
sor IP address into ip and leave the other two variables blank. Variable speech
stores the text form of the speech command, and variable android stores the
command to be sent to the Android mobile phone.
• Click ButtonStart and select when ButtonStart.Click do. Join the call
SpeechRecognizer1.GetText block to this block. When the button is started
the user will be able to speak the command. This command will be stored in text
form in variable speech.
● 277
• Variable speech is compared with the spoken command. If for example, the spo-
ken command is heater on then variable android is loaded with the text /on1.
This text is then sent to the Android mobile phone by block call WebViewer1.
GoToUrl as shown in the Figure.
● 278
Arduino UNO Program: This program is the same as the one given in Figure 10.19.
To test the program:
• Build the App Inventor program after entering the IP address of the ESP-01 pro-
cessor, and start the application on your Android mobile phone.
• Click Start and speak the command heater on. You should hear a relay click and
also the LED of RELAY1 will turn ON.
Background Information: UDP and TCP are the two most commonly used protocols to
send and receive data over a Wi-Fi network. TCP is a reliable protocol that includes hand-
shaking 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 10.1 shows a comparison of the UDP and TCP type communications.
TCP 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
● 279
UDP and TCP 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. UDP is a connectionless protocol
and thus there is no need to make a connection to the destination node before a packet can
be sent to it. In this project, we will be using the UDP protocol to send commands from the
Android mobile phone to the Arduino UNO.
Block Diagram: The block diagram of the project is the same as in Figure 10.14.
Circuit Diagram: The circuit diagram of the project is the same as in Figure 10.5.
App Inventor Program: In this project, we need to use a UDP component. Unfortunately,
UDP is not a standard component, but luckily it is available from the following site:
https://community.thunkable.com/t/free-udp-client-extension/5831
copy the file co.com.dentritas.ClientUDP.aix (9.4KB) to a folder and then click Exten-
sions in App Inventor, Browse and select this file. You should see the component named
ClientUDP in your Extensions tab.
Figure 10.24 shows the design of the project. The steps are:
● 280
Figure 10.25 shows the block program of the project. The steps are:
• Initialize two variables with the names ip and port. ip is the ESP-01 processor
IP address and port is the port number we will be using in the communication.
In this project, the IP address of the ESP-01 processor is 192.168.1.160 and we
will be using port 5000.
• Click ClientUDP1 and select call ClientUDP1.Send. Fill in the ip address, port
number, broadcast (false), the message, and the timeout. Here, message LE-
DON# will be sent to the Arduino UNO to turn OFF the LED (# is used as the
terminator character). Set the timeout to 5000.
● 281
Arduino Uno Program: This program is based on sockets. Figure 10.27 shows the pro-
gram listing (Arduino_UDP). Inside the setup routine, the LED is configured as an output
and is turned OFF. The remainder of the setup routine establishes a connection to the Wi-
Fi router and makes a UDP connection to the Android mobile phone. Onside the program
loop data received from the Android mobile phone is stored in character array buf. If the
received data contains string LEDON then the LED is turned ON. If the received data con-
tains string LEDOFF then the LED is turned OFF. Notice that data is read using the built-in
function readBytesUntil(). In this project, the data is terminated with the # character.
/**********************************************************************
* UDP Based Control of an LED
* ============================
*
* In this project an LED is connected to the Arduino UNO. The LED is
* controlled from the Android mobile phone using UDP protocol based
* control.
*
* File: Arduino_UDP
* Author: Dogan Ibrahim
* Date: March 2020
*********************************************************************/
#include <SoftwareSerial.h> // Include serial
char buf[30];
int LED = 8; // LED
SoftwareSerial wifi(6, 7); // RX, TX
//
// Connect to local Wi-Fi router and become a server
//
void setup()
{
pinMode(LED, OUTPUT); // LED is output
digitalWrite(LED, LOW); // LED OFF
wifi.begin(115200); // ESP-01 Baud rate
wifi.setTimeout(3600000);
wifi.print("AT+RST\r\n");
delay(2000);
wifi.print("AT+CWMODE=1\r\n");
delay(3000);
wifi.print("AT+CWJAP=\"BTHomeSpot-XNH\",\"49347abseb\"\r\n");
delay(8000);
wifi.print("AT+CIPMUX=1\r\n");
● 282
delay(3000);
wifi.print("AT+CIFSR\r\n");
delay(3000);
wifi.print("AT+CIPSTART=\"UDP\",\"192.168.1.178\",0,5000,2\r\n");
delay(3000);
}
void loop()
{
for(int k=0; k<30; k++)buf[k]=0x0; // Clear buffer
wifi.readBytesUntil('#', buf, 15); // Wait for data
To test the project, compile and upload the Arduino UNO program, start the Android mobile
phone application, and click LED ON. You should see the LED turning ON.
Description: In this project, an analog sensor is connected to the Arduino UNO. The am-
bient temperature readings are sent to the Android mobile phone using the UDP protocol
and it is displayed on the Android screen.
Block Diagram: Figure 10.28 shows the block diagram of the project.
Circuit Diagram: The circuit diagram of the project is shown in Figure 10.29. An LM35DZ
type analog temperature sensor is connected to analog input A0 of the Arduino UNO.
● 283
App Inventor Program: In this project, we will be using a more sophisticated UDP com-
ponent known as UrsAI2UDPv31, developed by Ullis Roboter. Download the component
from the following web site:
http://bienonline.magix.net/public/android-AI2-UDP-en.html
At the time of writing this book, the component was named as:
de.UllisRoboterSeite.UrsAI2UDPv3.aix
Download the component and click Extensions to load it into your App Inventor.
Insert a UrsAI2UDPv31 component onto the Viewer. This is a hidden component and is
only visible outside the phone image.
● 284
Figure 10.31 shows the block program of the project. The steps are:
• Initialize a dummy variable and use blocks when Screen1.Initialize and call
UrsAI2UDPv31.StartListening to set the port number to 5000.
● 285
Arduino UNO Program: The Arduino UNO program (Arduino_TEMP) is shown in Figure
10.33. Inside the setup routine, the ESP-01 processor is connected to the local Wi-Fi router
and a UDP connection is set up on port 5000. Inside the main program loop, the analog
temperature is read and converted into degrees Celsius. The temperature is then converted
into a string format and stored in variable tempc. AT command AT+CIPSEND is used to
send the temperature readings to the Android mobile phone over the UDP link. The format
of this command is as follows:
AT+CIPSEND=n
Data
Where n is the length of the data to be sent. The data is sent every 5 seconds to the An-
droid mobile phone.
/**********************************************************************
* UDP Based Digital Thermometer
* =============================
*
* In this project a LM3%DZ type analog sensor chip is connected to analog
* input A0 of the Arduino UNO. The program reads the ambient temperature
* and sends to the Android mobile phone.
*
* File: Arduino_TEMP
* Author: Dogan Ibrahim
* Date: March 2020
*********************************************************************/
#include <SoftwareSerial.h> // Include serial
//
// Connect to local Wi-Fi router and become a server
//
void setup()
{
wifi.begin(115200); // ESP-01 Baud rate
wifi.setTimeout(3600000);
wifi.print("AT+RST\r\n");
delay(2000);
wifi.print("AT+CWMODE=1\r\n");
delay(3000);
wifi.print("AT+CWJAP=\"BTHomeSpot-XNH\",\"49345abaeb\"\r\n");
● 286
delay(8000);
wifi.print("AT+CIPMUX=1\r\n");
delay(3000);
wifi.print("AT+CIFSR\r\n");
delay(3000);
wifi.print("AT+CIPSTART=\"UDP\",\"192.168.1.178\",5000,5000,2\r\n");
delay(3000);
}
void loop()
{
val = analogRead(temp); // Read temperature
float mV = val * 5000.0 / 1024.0; // Convert to mV
float T = mV / 10.0; // COnvert to Celsius
tempc = String(T); // COnvert to string
tempc = tempc.substring(0,4); // Only 4 chars
l = tempc.length(); // Length
Dt = "AT+CIPSEND=" + String(l); // Send data to Android
wifi.println(Dt); //...
delay(1000); //
wifi.print(tempc); //...
delay(5000); // Wait for 5 seconds
}
Figure 10.33 Arduino UNO program listing (Arduino_TEMP)
An example run of the program on the Android mobile phone is shown in Figure 10.34.
● 287
Description: This project is very similar to the previous one, but here additionally the
current temperature is spoken by the Android mobile phone.
Block Diagram: The block diagram of the project is the same as in Figure 10.28.
Circuit Diagram: The circuit diagram of the project s the same as in Figure 10.29.
App Inventor Program: This project is named TEMP_SPEECH. It is the same as in Fig-
ure 10.30, except that here we have inserted a TextToSpeech component in addition to
the UrsAI2UDPv31 component.
Figure 10.35 shows the block program of the project. The program is the same as the
one in Figure 10.31 except that here we have added the block call TextToSpeech.Speak
message to speak the temperature.
Arduino UNO Program: The Arduino Uno program is the same as the one given in Figure
10.33 (Arduino_TEMP).
To test the project, compile and upload the Arduino UNO program, start the application on
the Android mobile phone and turn up the volume control. You should hear the temperature
spoken from the phone speakers.
● 288
10.9 Summary
In this chapter, we developed several projects for Arduino UNO using App Inventor. A local
Wi-Fi router was used in all of these projects to establish communication between the Ar-
duino UNO and Android mobile phone.
In the next chapter, we will develop App Inventor based projects using ESP32.
● 289
11.1 Overview
In the last chapter, we developed several projects for Arduino UNO using MIT App Inventor.
In this chapter, we will develop similar projects but this time using ESP32, more specifically
the ESP32 DevKitC development board which is based on the ESP32 processor. Note that
the QR codes given in the projects were valid only for 2 hours at the time they were creat-
ed, and they cannot be used to install the apps to your mobile phone. They are only given
here for completeness.
Currently, ESP32 DevKitC is one of the most popular development boards. In this book, all
ESP32 based projects use this development board. It is therefore important that we learn
the basic architecture and features of this board.
The board has two connectors located along each side of the board for GPIO, clock, and
power line interfaces. Each connector has 19 pins. The pin configuration is shown in Figure
11.2.
● 290
The board has a mini USB connector for connecting it to a PC. The board also receives its
power from the USB port. Standard +5V from the USB port is converted into +3.3V on
the board. Also, two buttons are provided on the board named EN and BOOT, having the
following functions:
EN: This is the reset button where pressing this button resets the board
BOOT: This is the download button. The board is normally in operation mode where the
button is not pressed. Pressing and holding down this button and at the same time pressing
the EN button starts the firmware download mode where firmware can be downloaded to
the processor through the USB serial port.
The pins on the ESP32 DevKitC board have multiple functions. Figure 11.3 shows the func-
tions of each pin.
● 291
Note that GPIO34, GPIO35, GPIO36, GPIO37, GPIO38, and GPIO39 ports are in-
put only and cannot be used as output ports (GPIO37 and GPIO38 are not avail-
able on the ESP32 board).
The board operates with a typical power supply of +3.3V, although the absolute maximum
is specified as +3.6V. It is recommended that the current capacity of each pin should not
exceed 6 mA, although the absolute maximum current capacity is specified as 12 mA. It
is therefore important to use current limiting resistors while driving external loads such
as LEDs. Depending upon the configuration the RF power consumption during reception is
around 80 mA and it can be more than 200 mA during a transmission.
Arduino IDE is one of the most commonly used development environments for micro-
controllers, especially for the Arduino family of microcontrollers. This IDE is easy to use,
supports many microcontrollers, and includes a very rich library of functions that make
the programming easier. Most electrical/electronic engineering students and people whose
hobbies are electronics are familiar with using the Arduino IDE. In this section, we will see
how to install the ESP32 processor into the Arduino IDE on a Windows PC. It is important to
note that using Arduino IDE has some limitations and all features of the ESP32 are unable
be programmed.
● 292
• 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 11.4. 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
• Click Tools -> Boards -> Board Managers window and search for ESP32 as
shown in Figure 11.5
• Click the Install button. You should see the installed message as shown in Figure
11.6. Close the window.
● 293
• We should now test the installation to make sure that all the necessary files have
been loaded.
• Plug in your ESP32 DevKitC to your PC and start the Arduino IDE
• Select the ESP32 DevKitC as: Tools -> Board ->ESP32 Dev Module as shown
in Figure 11.7.
If you have received no errors up to this point it means that you have successfully installed
the ESP32 development environment on your Arduino IDE.
Description: This is a simple project that controls an LED connected to the ESP32 DevKitC
from the Android mobile phone. This project aims to show how App Inventor can be used
with the ESP32 DevKitC processor.
Block Diagram: The block diagram of this project is shown in Figure 11.8.
● 294
Circuit Diagram: Figure 11.9 shows the circuit diagram of the project.
App Inventor Program: The design of the project is the same as in Project 1 in Chapter
6 (Project: LED) where two buttons are used: one to turn ON the LED and another one to
turn OFF the LED. If you have already designed this project, then install it on your Android
mobile phone using the given QR code in Figure 6.4.
ESP32 DevKitC Program: Figure 11.10 shows the ESP32 program (ESP32_LED) list-
ing, developed using the Arduino IDE. At the beginning of the program header file, Blue-
toothSerial is included in the program. Inside the setup routine, the LED is configured as
an output and it is turned OFF. Also, the Bluetooth is given the device name LEDBT. The
remainder of the program runs inside the loop. Here, the program waits to receive data
from the Android mobile phone. If the received data contains "1" (i.e. ASCII 49) then the
LED is turned ON. If on the other hand, the received data contains "0" (i.e. ASCII 48) then
the LED is turned OFF.
/**********************************************************************
* ESP32 DevKitC BLUETOOTH LED CONTROL
* ===================================
*
* In this project an LED is connected to the ESP32 DevKitC through a
* current limiting resistor. The LED is controlled from the Android
* mobile phone using a Bluetooth link.
*
* File: ESP32_LED
* Author: Dogan Ibrahim
● 295
//
// Initialize the LED as output and the BluetoothSerial
//
void setup()
{
pinMode(LED, OUTPUT); // LED is output
digitalWrite(LED, LOW); // LED OFF
BT.begin("LEDBT"); // Initialize
}
void loop()
{
if(BT.available()) // Data available?
{
rd = BT.readString(); // Read data
if(rd.indexOf("1") != -1) // Contains "1"?
digitalWrite(LED, HIGH); // LED ON
else if(rd.indexOf("0") != -1) // Contains "0"?
digitalWrite(LED, LOW); // LED OFF
}
}
• Set the board type to ESP32 Dev Module in your Arduino IDE
• Compile and upload the program to your ESP32 DevKitC (you may have to press
the BOOT button during the download process)
• Enable Bluetooth on your Android mobile phone and scan the nearby devices. You
should see the device LEDBT displayed. Click to pair with it (see Figure 11.11)
● 296
• Start the application on your Android mobile phone and click Connect. Select
device LEDBT by clicking on it as shown in Figure 11.12. Green Connected
message should be displayed.
To turn OFF the LED the user should speak: LED off
Block Diagram: The block diagram of this project is as shown in Figure 11.8.
Circuit Diagram: The circuit diagram of the project is as shown in Figure 11.9.
● 297
App Inventor Program: This program is the same as the one given in Project 3 Chapter
6.4 (program: LED_SPEECH). If you have already designed this project, then install it on
your Android mobile phone using the given QR code in Figure 6.12.
ESP32 DevKitC Program: The ESP32 DevKitC program is the same as the one given in
Figure 11.10 (program: ESP32_LED).
Testing the program (assuming that you have already paired the devices):
• Set the board type to ESP32 Dev Module in your Arduino IDE
• Compile and upload the program to your ESP32 DevKitC (you may have to press
the BOOT button during the download process)
• Start the application on your Android mobile phone and click Connect. Select
device LEDBT
• Click the Start button and allow audio. Speak the command when the micro-
phone is enabled (Figure 11.13). You should click the Start button again to send
another command.
● 298
Description: In this project a 4 channel relay module is connected to the ESP32 DevKitC
processor and the relays are controlled from the Android mobile phone.
Block Diagram: The block diagram of the project is shown in Figure 11.14.
Circuit Diagram: Figure 11.15 shows the circuit diagram of the project.
App Inventor Program: The App Inventor program is the same as the one given in Pro-
ject 2 in Chapter 9.6 (program: Arduino_Relay4). If you have already designed this pro-
ject, then install it on your Android mobile phone using the given QR code in Figure 9.13.
The relay contacts are controlled by sending the following commands from the Android
mobile phone:
● 299
ESP32 DevKitC Program: Figure 11.16 shows the ESP32 DevKitC program (ESP32-
Rel4). At the beginning of the program the inputs pins of the relay module IN1, IN2, IN3,
and IN4 are assigned to port pins 19, 18, 5, and 17 respectively. Inside the setup routine,
the relay pins are configured as outputs and all the channels are deactivated. Inside the
main program loop data is received from the Android mobile phone and the required relay
is activated or deactivated.
/**********************************************************************
* ESP32 DevKitC 4 Channel Relay Control
* =====================================
*
* In this project a 4 channel relay module is connected to the ESP32
* DevKitC. The relay channels are controlled from the Android mobile
* phone using a Bluetooth link.
*
* File: ESP32-Rel4
* Author: Dogan Ibrahim
* Date: March 2020
*********************************************************************/
#include"BluetoothSerial.h" // Include Bluetooth
BluetoothSerial BT;
//
// Initialize the Relay pins as outputs and the BluetoothSerial
//
void setup()
{
pinMode(IN1, OUTPUT); // IN1 is output
pinMode(IN2, OUTPUT); // IN2 is output
pinMode(IN3, OUTPUT); // IN3 is output
pinMode(IN4, OUTPUT); // IN4 is output
BT.begin("LEDBT"); // Initialize
}
● 300
void loop()
{
if(BT.available()) // Data available?
{
rd = BT.readString(); // Read data
11.7 Project 4 – C
ontrolling a 4 Channel Relay Module using Switch
Components - Bluetooth Communication
Description: In this project, a 4 channel relay module is connected to the ESP32 DevKitC
processor as in Project 3. But here, App Inventor Switch components are used to control
the relays instead of buttons.
Block Diagram: The block diagram of the project is as shown in Figure 11.14.
Circuit Diagram: The circuit diagram of the project is as shown in Figure 11.15.
App Inventor Program: The design is shown in Figure 11.17. The steps are:
● 301
Figure 11.18a and Figure 11.18b show the block program of the project. Notice that in this
project the relays are controlled with the same commands as in the previous project. e.g.
1on activates channel 1, 1off deactivates channel 1, etc. The steps are:
• Initialize the states of RELAY1 On, RELAY2 On, RELAY3 On, and RELAY4 On
to false when the program is started
• Insert blocks that control the Bluetooth as in the previous Bluetooth based pro-
jects
• Click RELAY1 and select when RELAY1.Changed do. This block will be execut-
ed when RELAY1 is clicked.
● 302
• Click RELAY1 and select RELAY1.On. If the state of RELAY1 is On, click Blue-
toothClient1 and insert block call BluetoothClient1.SendText to send text
1on to the ESP32 DevKitC processor to activate channel 1 of the relay; otherwise
send 1off to deactivate channel 1 of the relay
● 303
ESP32 DevKitC Program: The ESP32 program is exactly the same as the one given in
Figure 11.16 (ESP32-Rel4).
Figure 11.20 shows an example run of the program on the Android mobile phone where
channel 3 of the relay was activated.
Description: In this project, an analog temperature sensor chip is connected to the ESP32
DevKitC and the ambient temperature readings are sent to the Android mobile phone.
Background Information: In this project, the TMP36 analog temperature sensor chip
is used to get the ambient temperature. TMP36 temperature sensor chip is a 3-pin device
having the pin layout as shown in Figure 11.21. The device operates with a power supply in
the range 2.7V to 5.5V and can measure the temperature in the range -40ºC to +125ºC.
The output voltage of the device is proportional to the measured temperature and is given
by:
● 304
C = (V – 500) / 10
Where C is the measured temperature in ºC, V is the output voltage of the sensor chip in
mV. Thus, for example, an output voltage of 800mV corresponds to 30ºC and so on.
Block Diagram: The block diagram of the project is shown in Figure 11.22.
Circuit Diagram: Figure 11.23 shows the circuit diagram of the project. Two pins of the
TMP36 are connected to the +3.3V power supply and the ground. The output pin of the
TMP36 temperature sensor chip is connected to pin IO34 which is also the ADC1_6 of the
ESP32 DevKitC. The ADC is 12-bits wide and has a reference voltage of +3.3V.
App Inventor Program: The App Inventor program is the same as the one given in
Project 6, Chapter 9.10 (program: LM35DZ_APP). If you have done this project, simply
install on your Android mobile phone using the QR code given in Figure 9.35.
ESP32 DevKitC Program: Figure 11.24 shows the ESP32 DevKitC program (ESP32_
TMP36). At the beginning of the program, TMP36 is assigned to 34. Inside the program
loop, the temperature is read by calling built-in function analogRead(). The ambient tem-
● 305
perature is then calculated in degrees Celsius and it is sent to the Android mobile phone
every second. Figure 11.25 shows an example display on the Android mobile phone.
/**********************************************************************
* ESP32 DevKitC Ambient Temperature
* =================================
*
* In this project a TMP36 type analog temperature sensor chip is
* connected to the ESP32 DevKitC. The ambient temperature readings are
* sent to the Android mobile phone.
*
* File: ESP32_TMP36
* Author: Dogan Ibrahim
* Date: March 2020
*********************************************************************/
#include"BluetoothSerial.h" // Include Bluetooth
BluetoothSerial BT;
//
// Initialize the BluetoothSerial
//
void setup()
{
BT.begin("LEDBT"); // Initialize
}
void loop()
{
int Temp = analogRead(TMP36); // Read temperature
float mV = Temp * 3300.0 / 4096.0; // in mV
float Temperature = (mV - 500.0) / 10.0; // in Degrees Celsius
String dt = String(Temperature); // As a string
dt = dt.substring(0, 4);
BT.print(dt); // Send to Android
delay(1000); // WAit 1 second
}
● 306
11.9 Project 6 – D
isplaying the Ambient Light Level on LCD –
Bluetooth Communication
Description: In this project, an LCD is connected to the ESP32 DevKitC. The ambient light
level (in Lux) is read by the Android mobile phone and is sent to the ESP32 DevKitC to
display it on the LCD. The data is displayed both on the Android mobile phone and on the
LCD. In this project, an I2C type LCD is used.
GPIO ports 21 and 22 are available for use by the I2C bus interface on the ESP32 DevKitC,
where port 21 is the data line (SDA) and port 22 is the clock line (SCL). Figure 11.26 shows
the front and back of the I2C based LCD. Notice that the LCD has a small board mounted at
its back to control the I2C interface. The LCD contrast is adjusted through the small poten-
tiometer mounted on this board. A jumper is provided on this board to disable the backlight
if required.
● 307
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, where the GPIO
pins 21 and 22 are used for the SDA and SCL of the LCD respectively.
App Inventor Program: Figure 11.29 shows the App Inventor design. The steps are:
• Insert a Label with the Text set to AMBIENT LIGHT (Lux) on a Horizonta-
lArrangement
● 308
Figure 11.30 shows the block program of the project. The steps are:
• Click Screen and initialize TempClock Timer interval to 3 seconds so that data
is sent to the ESP32 DevKitC processor every 3 seconds. Also, enable the light
sensor as sown in the Figure.
• Insert blocks that control the Bluetooth as in the previous Bluetooth based pro-
jects
• Click TempClock and select when TempClock.Timer do. This block will send
the ambient light readings to the ESP32 DevKitC processor.
• Check if Bluetooth is connected and if so send the light level readings to the
ESP32 DevKitC by using block call BluetoothClient1.SendText. At the same
time, display the readings on the Android mobile phone.
● 309
ESP32 DevKitC Program: Figure 11.32 shows the ESP32 DevKitC program (program:
ESP32_Light). Before programming the ESP32 for the I2C LCD, it is necessary to down-
load and include the I2C LCD library in our Arduino IDE folder. The steps to do this are
given below:
https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library
• Click button Clone or download and copy all the files to the LiquidCrystal_
I2C folder.
• Start the Arduino IDE. Go to File -> Examples and you should see Liquid-
Crystal_I2C examples in the drop-down menu if the library has been installed
correctly.
At the beginning of the program, the LCD is initialized with address 0x27 and it is config-
ured for 16x2 operation. Inside the program, loop data is received from the Android mobile
phone and stored in variable rd. The heading Light Lvl (Lux) is displayed at the top row of
the LCD while the light level is displayed in the second row.
/**********************************************************************
* ESP32 DevKitC Display Ambient Light Level on LCD
* ================================================
*
* In this project an I2C type LCD is connected to the ESP32 DevKitC.
* The program receives the ambient light level (Lux) readings from the
* Android mobile phone and displays on the LCD.
*
* File: ESP32_Light
* Author: Dogan Ibrahim
* Date: March 2020
*********************************************************************/
● 310
String rd;
//
// Initialize the BluetoothSerial
//
void setup()
{
lcd.begin(); // Initialize LCD
lcd.backlight(); // Turn ON backlight
BT.begin("LEDBT"); // Initialize
}
void loop()
{
rd = " ";
if(BT.available())
{
rd = BT.readString(); // Read light level
lcd.clear(); // Clear screen
lcd.setCursor(0, 0); // Cursor at 0,0
lcd.print("Light Lvl (Lux)"); // Display heading
lcd.setCursor(0, 1); // Cursor at 0,1
lcd.print(rd); // Display light level
delay(1000);
}
}
Figure 11.32 ESP32 DevKitC program (ESP32_Light) of the project
Figure 11.33 shows the light level displayed on the Android mobile phone. The data dis-
played on the LCD is shown in Figure 11.34.
● 311
Description: In this project, LEDs are connected to the ESP32 DevKitC and it is controlled
from the Android mobile phone using UDP type communication. These LEDs can be re-
placed by a relay and the project can be used to control any kind of electrical equipment
connected to the ESP32 DevKitC.
Block Diagram: The block diagram of the project is shown in Figure 11.35.
● 312
Circuit Diagram: Figure 11.36 shows the circuit diagram of the project. The LED is con-
nected to port IO23 through 330 Ohm current limiting resistor.
App Inventor Program: The App Inventor program is the same as the one given in Pro-
ject 4, Chapter 10.6. If you have already developed this project, just install using the QR
code given in Figure 10.26 (program: LED_UDP). Please note that you will need to find
the IP address of the ESP32 DevKitC before you can use it in Wi-Fi-based projects. You can
use the method given for the ESP-01 in Chapter 10.3. In this project, the IP address of the
ESP32 DevKitC was 192.168.1.156. You will need to set the IP address correctly in Figure
10.25 before you install the program on your Android mobile phone.
in Figure 11.37. The ESP32 DevKitC includes on-chip Wi-Fi connectivity and this makes it
easy to use the processor in Wi-Fi-based applications. At the beginning of the program,
the required Wi-Fi header files are included in the program. ssid and password are set to
the network name and password of the Wi-Fi router. Inside the setup routine, the LED port
is configured as an output and the LED is turned OFF. Then, function Connect_WiFi() is
called to make a connection to the Wi-Fi router. The function that connects to Wi-Fi is as
follows:
void Connect_WiFi()
{
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED)
{
delay(1000);
}
}
After a successful connection, a UDP port is set up by calling udp.begin(Port) where the
Port is set to 5000. The remainder of the program runs in the program loop. Inside this loop
data is received from the Android mobile phone over the UDP link and this data is decoded.
If the data is LEDON then the LED is turned ON. If on the other hand, the received data is
LEDOFF then the LED is turned OFF.
● 313
/**********************************************************************
* ESP32 DevKitC LED Control Using UDP
* ===================================
*
* In this project an LED is connected to the ESP32 DevKitC and it is
* controlled from the Android mobile phone using UDP communication.
*
* File: ESP32_UDP
* Author: Dogan Ibrahim
* Date: March 2020
*********************************************************************/
#include "WiFi.h"
#include <WiFiUdp.h>
#define LED 23
WiFiUDP udp;
//
// Use local port 5000
//
const int Port = 5000;
char Packet[80];
//
// Local Wi-Fi name and password
//
const char* ssid = "BTHomeSpot-XNH";
const char* password = "49348abjseb";
//
// This function connects the ESP32 Devkitc to the local Wi-Fi
// network. The network name and passwors are as specifed earlier
//
void Connect_WiFi()
{
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED)
{
delay(1000);
}
}
//
// Configure the LED as outputs and turn OFF at the beginning
// Connect to the local Wi-Fi. Also, UDP is started in local port
//
void setup()
● 314
{
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
Connect_WiFi();
udp.begin(Port);
}
//
// This is the main program loop. Inside the main program we read
// UDP packets and then control the LED as requested. The format
// of the control commands are:
//
// LEDON# turn ON LED (# is ifnored)
// LEDOFF# turn OFF LED (# is ignored)
//
// Any other commands are simply ignored by the program
//
void loop()
{
int PacketSize = udp.parsePacket();
if(PacketSize)
{
udp.read(Packet, PacketSize);
Description: This project is the same as Project 6, Chapter 10.8, except that here the
temperature is read by the ESP32 DevKitC and is sent to the Android mobile phone where
it is spoken on the speaker.
● 315
Block Diagram: The block diagram of the project is shown in Figure 11.38.
Circuit Diagram: The circuit diagram of the project is the same as shown in Figure 11.23
where the LM35 temperature sensor is connected to port pin IO34 of the ESP32 DevKitC.
App Inventor Program: The App Inventor program is the same as the one given in Pro-
ject 6, Chapter 10.8. If you have already developed this project, just install using the QR
code given in Figure 10.36 (program: TEMP_SPEECH).
ESP32 DevKitC Program: Figure 11.39 shows the ESP32 DevKitC program (ESP32_
SPEECH). At the beginning of the program, the necessary Wi-Fi files are included in the
program and analog sensor LM35 is assigned to port pin 34. Remote port is set to 5000, and
the remote IP address (IP address of the Android mobile phone) is set to 192.168.1.178
(you will have to send your IP address). Inside the setup routine, a connection is made to
the Wi-Fi router. The remainder of the program runs inside the loop. Here, the temper-
ature is read as an analog value and stored in variable val. This value is then converted
into millivolts and divided by 10 to find the actual temperature in degrees centigrade. After
converting the reading into a string, a UDP packet is formed and the temperature reading
is sent to the Android mobile phone where it is displayed on the screen (Figure 11.40) as
well as spoken on the speaker.
/**********************************************************************
* ESP32 Speaking Thermometer
* ==========================
*
* In this project an LM35 type analog temperature sensor is connected
* to ESP32 DevKitC. The processor reads the temperature snd sends over
* a UDP link to the Android mobile phone where the temperature reading
* is spoken through its speaker.
● 316
*
* File: ESP32_SPEECH
* Author: Dogan Ibrahim
* Date: March 2020
*********************************************************************/
#include "WiFi.h"
#include <WiFiUdp.h>
int val, temp= 34;
String tempc;
WiFiUDP udp;
//
// Use local port 5000
//
const int Port = 5000;
unsigned int remote_port = 5000;
IPAddress remote_IP = IPAddress(192,168,1,178);
char Packet[80];
//
// Local Wi-Fi name and password
//
const char* ssid = "BTHomeSpot-XNH";
const char* password = "49342abdayb";
//
// This function connects the ESP32 Devkitc to the local Wi-Fi
// network. The network name and passwors are as specifed earlier
//
void Connect_WiFi()
{
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED)
{
delay(1000);
}
}
//
// Connect to the Wi-Fi
//
void setup()
{
Connect_WiFi();
● 317
udp.begin(Port);
}
//
// This is the main program loop. Here, we read the ambient temperature
// adn send it to the Android mobile phone over UDP link
//
void loop()
{
val = analogRead(temp); // Read the temp
float mV = val * 5000.0 / 4096.0; // Convert to mV
float T = mV / 10.0; // COnvert to Celsius
tempc = String(T); // COnvert to string
tempc = tempc.substring(0,4); // Only 4 chars
Description: This project is very similar to Project 8, but here the temperature readings
are saved in a file with time stamping. The time is taken from the Android mobile phone.
The readings can be displayed by clicking a button.
Block Diagram: The block diagram of the project is as shown in Figure 11.38.
● 318
Circuit Diagram: The circuit diagram of the project is as shown in Figure 11.23.
App Inventor Program: The App Inventor program uses components UrsAI2UDPv31
(see Project 5, Chapter 10.7), File (under tab Storage) and Clock (under tab Sensors).
The steps are as follows (see Figure 11.41):
• Create a TextBox named TextBox1, set the FontSize to 18, Height 40%, and
MultiLine ticked. Clear fields Hint and Text
• Insert components UrsAI2UDPv31, File, and Clock. Make sure that the Clock
TimerInterval is set to 1000ms in the properties.
Figure 11.42 shows the block program of the project. The steps are:
● 319
When the screen is initialized, configure the UDP client to listen on port 5000.
When data is received, display this data on TextBox TxtTemperature. Also, click File1
and select call File1.AppendToFile. Here, we use a Join block and insert the temperature
reading, current hours, minutes, and seconds. In this project, the filename is set to Temps.
txt
• Click ButtonSave and select when ButtonSave.Click do. This block will display
the saved data on the screen. Click File1 and select call File1.ReadFrom and
enter the filename where the data has been saved
• Click File1 and select when File1.GotText. This block will be executed when
data is read from the file. Display the data in TextBox1.
• Insert a block to update the time every second. click when Clock1.Timer do
end set variable timenow to call Clock1.Now
● 320
ESP32 DevKitC Program: The ESP32 program is the same as the one given in Figure
11.39 (ESP32_SPEECH), except that the delay at the end of the program is changed to
every 10 seconds (program: ESP32_SPEECH_2).
Figure 11.44 shows an example output on the Android mobile phone. Notice that clicking
button Saved Data displays the saved data in TextBox1.
11.13 Summary
In this last chapter, we developed several projects using the ESP32 DevKitC processor and
App Inventor. Some projects were based on Bluetooth while others used a Wi-Fi link. Read-
ers should find it very easy to modify these projects to suit their own applications.
● 321
Appendix A • Exercises
Chapter 1
1. Explain the differences between the text based programming languages and
visual programming languages.
2. What are the advantages and disadvantages of block based programming lan-
guages compared to text based languages.
3. What type of programming language is MIT App Inventor?
4. What type of programming language is Pascal?
5. What type of programming language is Python?
Chapter 2
1. Explain how the MIT App Inventor software package can be started.
2. Explain the various items in the startup screen of the MIT App Inventor.
3. Explain the basic steps required to develop a program using the MIT App Inven-
tor.
4. Explain the functions of various menu items in the MIT App Inventor screen.
5. What are the differences between the Designer and the Blocks menus?
6. Explain the various methods that a develop MIT App Inventor application can be
tested. Which is the preferred method? Why?
7. Explain how to save a developed application in MIT App Inventor.
8. Explain how an external application can be downloaded into MIT App Inventor.
9. Explain why the Emulator is a useful tool. Under what circumstances should you
prefer to use the Emulator?
Chapter 3
1. Develop a simple MIT App Inventor project to display an image when a button is
clicked. Install this project on your mobile phone and test it.
2. Repeat exercise 14 but this time use the Emulator to test your application.
3. Develop an MIT App Inventor application to translate a text written in German
into English. Test your application using the emulator.
4. Develop an application with two buttons named A and B. When A is clicked the
mobile phone should speak the word Hello, and when B is clicked it should speak
the word Computer.
5. Develop an MIT App Inventor application to receive your speech, convert it into
French and then display it in a TextBox.
6. Develop an MIT App Inventor application to receive a telephone number from
you in the form of a speech and then dial this number.
7. Develop a clock application on your mobile phone using the MIT App Inventor.
The application should display the current date and time.
8. Develop a clock application on your mobile phone using the MIT App Inventor
where the date and time can be changed.
9. Develop an MIT App Inventor application to receive your speech in English and
display it in text form.
● 322
Chapter 4
1. Develop an MIT App Inventor application to calculate the area and volume of a
cylinder, given its radius and height.
2. Develop an MIT App Inventor application to display a table of squares of num-
bers from 1 to 10 in steps of 1.
3. Develop an MIT App Inventor application to calculate and display the sum of
numbers from 1 to 10.
4. Develop an MIT App Inventor application to display the trigonometric function
cosine as the angle changes from 0 to 45 degrees.
5. Develop an MIT App Inventor application co convert degrees Fahrenheit to de-
grees Celsius. Test your program by giving some known values.
6. Develop an MIT App Inventor application to convert metres, centimetres, and
millimetres into yards and foot. Test your program by giving some known values
7. Develop an MIT App Inventor program to receive a number and display its
squate and square root.
Chapter 5
1. Give the basic specifications of the Raspberry Pi 4 computer.
2. Explain how the Raspberry Pi 4 computer command line can be accessed re-
motely.
3. Explain how the desktop can be accessed remotely.
4. Explain the various methods that a Python 3 program can be executed on the
Raspberry Pi 4. Which is the preferred method?
5. What is Thonny? Explain how it can be used to develop a program.
6. Explain how you can save and run file in Thonny.
7. Explain how the debugger can be used in Thonny.
8. Write a Python program to display a table of squares of numbers from 1 to 10
9. Write a Python program to get a number from the keyboard and then to display
the square root of this number.
10. Write a Python program to display the trigonometric sine and cosine for the
angles 45º to 90º in steps of 5º.
Chapter 6
1. Assume that two LEDs are connected to the ports of a Raspberry Pi 4 computer
through current limiting resistors. Develop an MIT App Inventor application
that will control these LEDs by speech commands given at your mobile phone
(hint: use Bluetooth communication between the mobile phone and the Rasp-
berry Pi 4 computer).
2. Develop an MIT App Inventor application to read the acceleration in the X di-
rection from your mobile phone. Send this reading to the Raspberry Pi 4 com-
puter and display it on an LCD using Bluetooth communication.
3. It is assumed that an LED is connected to one of the ports of the Arduino UNO
computer through a current limiting resistor. Develop an MIT App Inventor ap-
plication with a slider component such that moving the slider arm will change
the brightness of the LED. Use Bluetooth communication.
4. Assume that a relay is connected to port pin 8 of the Arduino UNO. Develop an
● 323
MIT App Inventor application that will control the relay from the mobile phone.
Use Bluetooth communication.
5. Assume that a relay is connected to the Arduino UNO. Develop an MIT App
Inventor program to control the relay from your mobile phone by speech com-
mands.
6. Explain what a web server is and how it works.
7. Explain the differences between UDP and TCP based communication. Which
method would you choose to send important messages?
8. Give examples of where TCP and UDP are used.
9. It is required to develop a chat program over a Wi-Fi link. Explain whether you
would choose to use TCP or UDP.
10. A bank wishes to send confidential data to a customer. Explain whether the
UDP or the TCP should be used.
Chapter 7
1. Explain what a web server is and how it works.
2. Explain what is required to develop a web server application.
3. Develop a project to send the ambient temperature to mobile phone.
4. Repeat Exercises in Chapter 6 using Wi-Fi instead of Bluetooth.
Chapter 8
1. Explain what Node-RED is.
2. What are the advantages of using the Node-RED?
3. Explain how UDP can be used with Node-RED.
4. Develop a web server based Node-RED program to control 4 LEDs.
5. Develop a web server based application to control a relay.
6. Repeat Exercises in Chapter 6 using Node-RED.
Chapter 9
1. Explain how the Arduino Uno can be used in Bluetooth based applications.
2. Explain why you may need to use a module such as the HC-06.
3. Explain the differences between HC-05 and HC-06.
4. Explain the advantages and disadvantages of using Bluetooth instead of Wi-Fi.
5. It is required to control a relay remotely from another room of your home us-
ing the Arduino Uno. Explain whether you would choose Bluetooth or Wi-Fi for
communication.
6. Repeat Exercises in Chapter 6 using an Arduino Uno with Bluetooth communi-
cation.
Chapter 10
1. Explain how Wi-Fi can be used with Wi-Fi.
2. What are the basic specifications of the ESP01 processor?
3. Explain how you can connect the ESP-01 processor to the Arduino Uno.
4. Explain the basic AT commands of the ESP-01.
5. How would you send data over the UDP link using the ESP-01?
6. How would you send data over the TCP link using the ESP-01?
● 324
7. What other Wi-Fi modules can you use instead of the ESP-01 to give Wi-Fi con-
nectivity to an Arduino Uno? What are the advantages and disadvantages of
using the ESP-01?
8. Repeat Exercises in Chapter 6 using Arduino with Wi-Fi communication.
Chapter 11
1. Explain the basic features of the ESP32 DevKitC development board. How does
it compare with the Arduino UNO?
2. Explain the steps of how programs can be developed using the ESP32 DevKitC
development board.
3. Assume that a unipolar stepper motor is connected to the ESP32 DevKitC
through a motor driver module. Develop an MIT App Inventor program to move
the motor shaft by the required number of degrees.
4. Assume that a BME280 type temperature, pressure, humidity sensor is con-
nected to the ESP32 DevKitC. Develop and MIT App Inventor program to read
these three parameters and then send them to a mobile phone where they will
be displayed.
5. Develop a program using the MIT App Inventor to control four LEDs connected
to the ESP32 DevKitC.
6. A relay is connected to the ESP32 DevKitC. Develop an MIT App Inventor based
program to control the relay from your mobile phone by speech.
Appendix B
1. Explain the advantages of using MIT App Inventor offline.
2. What are the disadvantages of using the MIT App Inventor offline instead of
online?
3. Explain the steps necessary to install and use the MIT App Inventor offline.
4. Give an example project of using the MIT App Inventor offline.
Appendix D
1. Explain how an Extension component can be downloaded to the MIT App Inven-
tor.
2. What are the advantages of using Extension components in MIT App Inventor?
3. Explain where you can find Extension components for the MIT App Inventor.
● 325
B.1 Overview
In this book, we have learned how to use the MIT App Inventor to create many projects.
All these projects have been created while working online with the App Inventor. There are
some situations however when the Internet may not be available and we may want to use
the App Inventor. Fortunately, an offline version of App Inventor, known as App Inven-
tor Ultimate is available which can be used to develop App Inventor projects offline, i.e.
without having to connect to the Internet. The offline version also has the advantage that
there is no code size limit and as a result, it allows very large projects to be created. In this
Appendix, we will see how to install and use the offline version of the App Inventor.
http://sourceforge.net/projects/ai2u/files/
• Click on the latest version. e.g. ai2u 4.6 (see Figure B.1)
• Click on Installer
● 326
• Double click to install file AI2Starter46.exe. Then, double click to install file
AI2U 64bit v4.6.exe. Make sure you click the option to create a Desktop icon.
• Click Start at the bottom left of your computer and click on file App Inventor 2
Server. You will see 3 windows opening.
• Open your web browser and enter: localhost:8888. You should see the wel-
come message as shown in Figure B.3
• You should see the familiar App Inventor screen as shown in Figure B.4. Now you
are working offline and you can turn OFF the Internet if you wish.
• Click Start new project at the top left-hand side to start working on a new
project
Figure B.4 App Inventor screen (only part of the screen is shown)
• We can use either the built-in Emulator or wired USB connection while working
offline (after clicking Connect in the App Inventor top menu).
● 327
Notice that you should have an icon named App Inventor 2 Ultimate on your Desktop.
You should click this icon and then open your browser and enter localhost:8888 to start
the App Inventor offline.
● 328
● 329
There are some applications where you may need a component but it may not be available
in the Palette provided by the MIT App Inventor. There are many web sites where users can
download Extension components to use in their projects. Some of these extensions are free
of charge while some cost some money.
https://puravidaapps.com/extensions.php
https://community.thunkable.com/t/index-of-available-extensions/2680
● 330
Appendix E •
• 4 x LED
• 4 x 470 Ohm resistor
• 1 x 330 Ohm resistor
• 1 x 1K resistor
• 1 x 2K resistor
• 1 x 100 Ohm resistor
• 1 x small DC motor
• 1 x DHT11 sensor
• 1 x small 1N4148 diode
• 1 x 4-way relay module (Elegoo)
• 1 x HC-06 Bluetooth module
• 1 x parallel LCD
• 1 x I2C LCD
• 1 x LM35DZ sensor chip
• 1 x small stepper motor (28BYJ-48)
• 1 x stepper motor driver board (ULN2003 based)
• 1 x ESP-01 processor
• 1 x NPN transistor
• 6 x F-M jumper wires
• 6 x M-M jumper wires
• 1 x small breadboard
Processors used
• Raspberry Pi 4
• Arduino UNO
• ESP32 DevKitC
● 331
Index
A Extensions 330
Acceleration 65
AI2 Companion 17, 20 F
aiStarter 25 Fixed telephone number 56
Arduino Uno 201 Formatting 35
Full-step mode 254
B
Bell sound 28 G
Bipolar stepper 249 Global positioning system 70
Blocks 15 GPIO 122
Bluetooth 129, 203, 294 GPIO library 123
Boot 291 GPS 70
Buster 106
Button 32 H
Half-step mode 254
C HC-05 203
Chronograph 81 HC-06 203
Command mode 115 H135ciconfig
Command prompt 114 HDMI 103
Contact list 58 Humidity 160, 189
Counter 84
CPU fan 105 I
CSI port 103 I2C 308
I2C LCD 307
D Images 43
Date 75 Import project 31
DC motor 155 Interrupt 125
Designer 15
Desktop 108 L
DHT11 161, 234 Label 32
Dice 93 LCD 307
Digital thermometer 283 Light level 68
DSI port 103 LM35DZ 229
Loading programs 329
E
Emulator 24 M
EN 291 Map 72
English to German 42 Motor shaft 250
ESP-01 259 Motor driver 251
ESP32 290 Multiple LEDs 145, 152
ESP32 DevKitC 290
Etcher 107 N
Ethernet 103 Nano 115
Export project 31 Node-RED 194
● 332
O TCP 279
Offline 326 Telephone number 55
ON-OFF control 239 Temperature 160, 189, 228
Temperature control 239
P TextBox 32
Parallel interface 122 Text editor 115
Password protection 169 Text To Speech 37
Play 77 Thonny 119
PoE port 103 TightVNC 113
Pin numbering 123 Time 75
Procedures 100 Time table 98
Putty 110 TMP36 305
Python 114 Trash 31
PWM 156 Trigonometric function 96
Q U
Quiz 94 UDP 279, 283, 288
ULN2003 251
R Unipolar stepper 248
RAM 103 USB keyboard 104
Random number 93 USB port 103
Raspberry Pi 4 102
Record 77 V
Relay 181, 207, 214 VNC 110
Remote access 112 VNC server 112
RPM 255
W
Weather 234
S Web server 177, 181, 194
Save 31 Wi-Fi 174, 312
Scratch 13
SendMessage 47 Q
Sending text 221 QR code 17
Share 32
SMS 47, 50 Y
Sound output 138, 152 YandexTranslate 34
Speech command 140
Speech control 277
Speech recognizer 79
Speed control 155
SSH 110
StarLogo 15
Stepper motor 248
T
Taking picture 59
● 333
Dogan Ibrahim
Projects
MIT App Inventor Projects
This book is about developing apps for Android and iOS compatible
mobile devices using the MIT App Inventor online development
environment. MIT App Inventor projects can be in either standalone
●
mode or use an external processor. In standalone mode, the
developed application runs only on the mobile device (e.g. Android
or iOS). In external processor-based applications, the mobile device
All projects presented in this book have been developed using the
MIT App Inventor visual programming language. There is no need
to write any text-based programs. All projects are compatible with
Android and iOS-based mobile devices. Full program listings for
all projects as well as detailed program descriptions are given in
Elektor International Media the book. Users should be able to use the projects as they are
presented, modifying them to suit their own needs.
Dogan Ibrahim
www.elektor.com
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE
RN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
SIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHAR
RN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●