MIT App Inventor Projects [1 ed.] 9781907920899, 1907920897

This book is about developing apps for Android compatible mobile devices using the MIT App Inventor online development e

398 128 48MB

English Pages 333 [334] Year 2020

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

MIT App Inventor Projects [1 ed.]
 9781907920899, 1907920897

Table of contents :
MIT App Inventer Projects
Contents
Preface
Chapter
1 • Introduction
2 • Setting up the MIT App Inventor
3 • Simple MIT App Inventor projects
4 • MIT App Inventor projects using mathematical & logical operations
5 • Raspberry Pi 4 – specifications – setup – installing the operating system
6• Raspberry Pi Bluetooth based projects using the MIT App Inventor
7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor
8 • Raspberry Pi Node-Red based projects using MIT App Inventor
9 • Arduino Uno Bluetooth based projects using MIT App Inventor
10 • Arduino Wi-Fi based projects using MIT App Inventor
11 • ESP32 based projects using the MIT App Inventor
Appendix
A • Exercises
B • Using the MIT App Inventor offline
C • Loading the programs from the book website
D • MIT App Inventor extension components
E • List of components used in the book
Index

Citation preview

MIT App Inventor Projects

Elektor International Media

www.elektor.com

The projects developed in this book include: • • • • • •

Using the text-to-speech component Intonating a received SMS message Sending SMS messages Making telephone calls using a contacts list Using the GPS and Pin-pointing our location on a map Speech recognition and speech translation to another language • Controlling multiple relays by speech commands • Projects for the Raspberry Pi, ESP32 and Arduino using Bluetooth and Wi-Fi • MIT APP Inventor and Node-RED projects for the Raspberry Pi

MIT App Inventor Projects

MIT App Inventor Projects

ISBN 978-1-907920-89-9

In this book, many tested and fully working projects are given both in standalone mode and using an external processor. Full design steps, block programs, circuit diagrams, QR codes and full program listings are given for all projects.

50+ Apps with Raspberry Pi, ESP32 and Arduino



Prof. Dr. Dogan Ibrahim has a BSc. in Electronic Engineering, an MSc. in Automatic Control Engineering, and a Ph.D. in Digital Signal Processing. He worked in many industrial organisations before returning to academia. Prof. Ibrahim is the author of over 60 technical books and over 200 technical articles on microcontrollers, microprocessors, and related fields. He is a Chartered Electrical Engineer and a Fellow of the Institution of Engineering Technology.

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 communicates with an external microcontroller-based processor, such as Raspberry Pi, Arduino, ESP8266, ESP32, etc.

Dogan Ibrahim

50+ Apps with Raspberry Pi, ESP32 and Arduino

The book is unique in that it is currently the only book that teaches how to develop projects using Wi-Fi and Node-RED with MIT App Inventor. The book is aimed at students, hobbyists, and anyone interested in developing apps for mobile devices. 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 the book. Users should be able to use the projects as they are presented, modifying them to suit their own needs.

LEARN DESIGN SHARE

Dogan Ibrahim 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 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 ●

Cover MIT App Inventer UK 200311.indd Alle pagina's

03-04-20 10:25

MIT App Inventor Projects 50+ Android and iOS Apps with Rasberry Pi, ESP32 and Arduino

● Dogan Ibrahim

LEARN DESIGN SHARE

MIT App Inventer UK 200311.indd 3

03-04-20 10:37



This is an Elektor Publication. Elektor is the media brand of

Elektor International Media B.V. 78 York Street, London W1H 1DP, UK Phone: (+44) (0)20 7692 8344



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..



British Library Cataloguing in Publication Data



ISBN 978-1-907920-89-9

A catalogue record for this book is available from the British Library

© Copyright 2020: Elektor International Media b.v. Prepress Production: D-Vision, Julian van den Berg First published in the United Kingdom 2020

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

LEARN DESIGN SHARE

MIT App Inventer UK 200311.indd 4

03-04-20 10:37

Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Chapter 1 • Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.1 Text-Based Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.2 Block-Based Visual Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.3 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Chapter 2 • Setting up the MIT App Inventor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.2 Setting Up the App Inventor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Chapter 3 • Simple MIT App Inventor projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 3.2 Starting App Inventor and the Startup Screen . . . . . . . . . . . . . . . . . . . . . . . . . . 26 3.3 Project 1 – Using a Button to Generate Sound . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3.4 Saving the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3.5 Deleting a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 3.6 Sharing a Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.7 Project 2 – Using a Button, a Label, and Text Boxes – Language Translation . . . . . 32 3.8 Project 3 – Formatting the Layout of the Components – Language Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 3.9 Project 4 – Text to Speech – Fixed Text Message . . . . . . . . . . . . . . . . . . . . . . . . 37 3.10 Project 5 – Text to Speech – Any Text Message . . . . . . . . . . . . . . . . . . . . . . . . 39 3.11 Project 6 – Text to Speech – English to German . . . . . . . . . . . . . . . . . . . . . . . . 42 3.12 Project 7 – Using Images – Learning Elementary English . . . . . . . . . . . . . . . . . . 43 3.13 Project 8 – Speaking a Received SMS Message . . . . . . . . . . . . . . . . . . . . . . . . . 47 3.14 Project 9 – Sending SMS Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 3.15 Project 10 – R  eading a Message and Sending a Reply Message Automatically when Busy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 3.16 Project 11 – Display the Received SMS Message . . . . . . . . . . . . . . . . . . . . . . . . 53 3.17 Project 12 – Calling a Fixed Telephone Number . . . . . . . . . . . . . . . . . . . . . . . . 55 3.18 Project 13 – Calling to Several Fixed Telephone Numbers . . . . . . . . . . . . . . . . . 56 3.19 Project 14 – Calling from the Contacts List . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 3.20 Project 15 – Taking Pictures with the Camera . . . . . . . . . . . . . . . . . . . . . . . . . . 59

●5

MIT App Inventer UK 200311.indd 5

03-04-20 10:37

MIT App Inventor Projects 3.21 Project 16 – A Basic Piano . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 3.22 Project 17 – Acceleration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 3.23 Project 18 – Light Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 3.24 Project 19 – Global Positioning System – Latitude, Longitude, Altitude, and Speed 70 3.25 Project 20 – Pinpointing Your Location on a Map . . . . . . . . . . . . . . . . . . . . . . . . 72 3.26 Project 21 – Display/Set Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 3.27 Project 22 – Record/Play Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 3.28 Project 23 – Speech Recognizer – Translate Speech to Another Language . . . . . . 79 3.29 Project 24 – Chronograph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 3.30 Project 25 – Seconds Down Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 3.31 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Chapter 4 • M  IT App Inventor projects using mathematical & logical operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.2 Project 1 – Area of a Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.3 Project 2 – Areas of Various Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 4.4 Project 3 – Roots of a Quadratic Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 4.5 Project 4 – Random Numbers – Dice Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . 93 4.6 Project 5 – Quiz - Learning Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 4.7 Project 6 – Table of Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 4.8 Project 7 – Multiplication Time Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 4.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Chapter 5 • R  aspberry Pi 4 – specifications – setup – installing the operating system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 5.2 Parts of Raspberry Pi 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 5.3 Requirements of Raspberry Pi 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 5.3.1 Setup Option 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 5.3.2 Setup Option 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 5.4 Installing the Raspberry Pi Operating System . . . . . . . . . . . . . . . . . . . . . . . . . . 106 5.4.1 Raspbian Buster Installation Steps on Raspberry Pi 4 . . . . . . . . . . . . . . . . . . . 106 5.5 Remote Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

●6

MIT App Inventer UK 200311.indd 6

03-04-20 10:37

 5.6 Using Putty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 5.6.1 Configuring the Putty . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 5.7 Remote Access of the Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 5.8 Using the Python Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 5.8.1 Method 1 – Interactively from Command Prompt . . . . . . . . . . . . . . . . . . . . . . 114 5.8.2 Method 2 – Create a Python File in Command Mode . . . . . . . . . . . . . . . . . . . . 115 5.8.3 Method 3 – Create a Python File in GUI mode – Using the Thonny . . . . . . . . . . 119 5.9 Which Method? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 5.10 Accessing Raspberry Pi 4 Hardware and Peripheral Devices from Python . . . . . . 121 5.10.1 GPIO – Parallel Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 5.10.2 The GPIO Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 5.11 Example Project Accessing the External World . . . . . . . . . . . . . . . . . . . . . . . . 126 Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 6.2 Project 1 – Controlling an LED from Android Mobile Phone . . . . . . . . . . . . . . . . . 129 6.3 Project 2 – Sound Output while Controlling an LED . . . . . . . . . . . . . . . . . . . . . . 138 6.4 Project 3 – Controlling an LED with Speech Commands . . . . . . . . . . . . . . . . . . . 140 6.5 Project 4 – Controlling Multiple LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 6.7 Project 6 – DC Motor Speed Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 6.8 Project 7 – Sending Temperature and Humidity to Android Device . . . . . . . . . . . 160 6.9 Project 8 – Password Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 6.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 7.2 Project 1 – Getting and Displaying the Local Wi-Fi Parameters . . . . . . . . . . . . . . 174 7.3 Project 2 – Web Server to Control an LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 7.4 Project 3 – Web Server to Control Multiple Relays . . . . . . . . . . . . . . . . . . . . . . . 181 7.5 Project 4 – Sending Ambient Temperature and Humidity to Android Mobile Phone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 7.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

●7

MIT App Inventer UK 200311.indd 7

03-04-20 10:37

MIT App Inventor Projects Chapter 8 • R  aspberry Pi Node-Red based projects using MIT App Inventor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 8.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 8.2 Project 1 – Controlling an LED – Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . 194 8.3 Project 2 – Controlling 4 Relays – Web Server . . . . . . . . . . . . . . . . . . . . . . . . . 196 8.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 Chapter 9 • A  rduino Uno Bluetooth based projects using MIT App Inventor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 9.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 9.2 Arduino Uno Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 9.3 Arduino Uno Program Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 9.4 Bluetooth for Arduino Uno . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 9.5 Project 1 - Controlling an LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 9.6 Project 2 - Controlling a 4 Channel Relay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207 9.7 Project 3 - Controlling a 4 Channel Relay with Sound Output . . . . . . . . . . . . . . . 214 9.8 Project 4 - Controlling a 4 Channel Relay with Speech . . . . . . . . . . . . . . . . . . . . 216 9.9 Project 5 – Sending Text to Arduino UNO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 9.10 Project 6 – Sending the Ambient Temperature to Android Mobile Phone . . . . . . . 228 9.11 Project 7 – Weather Watch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 9.12 Project 8 – ON-OFF Temperature Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 9.13 Project 9 – Modified ON-OFF Temperature Control . . . . . . . . . . . . . . . . . . . . . 246 9.14 Project 10 – Controlling a Stepper Motor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 9.15 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor . . . . . . . . . . 259 10.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 10.2 Arduino Uno Wi-Fi Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 10.3 Project 1 – Controlling an LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 10.4 Project 2 – Controlling a 4 Channel Relay Module . . . . . . . . . . . . . . . . . . . . . . 269 10.5 Project 3 – Speech Control of a 4 Channel Relay Module . . . . . . . . . . . . . . . . . 277 10.6 Project 4 – UDP Based Control – LED Control . . . . . . . . . . . . . . . . . . . . . . . . . 279 10.7 Project 5 – UDP Based Control – Digital Thermometer . . . . . . . . . . . . . . . . . . . 283 10.8 Project 6 – UDP Based Control – Speaking Thermometer . . . . . . . . . . . . . . . . . 288

●8

MIT App Inventer UK 200311.indd 8

03-04-20 10:37

 10.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 Chapter 11 • ESP32 based projects using the MIT App Inventor . . . . . . . . . . . . . 290 11.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 11.2 ESP32 DevKitC Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 11.3 Arduino IDE for The ESP32 DevKitC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292 11.3.1 Installing the Arduino IDE for the ESP32 DevKitC . . . . . . . . . . . . . . . . . . . . . 292 11.4 Project 1 – Controlling an LED – Bluetooth Communication . . . . . . . . . . . . . . . 294 11.5 Project 2 – Speech Control of an LED – Bluetooth Communication . . . . . . . . . . 297 11.7 Project 4 – Controlling a 4 Channel Relay Module using Switch Components - Bluetooth Communication . . . . . . . . . . . . . . . . . . . . 301 11.9 Project 6 – Displaying the Ambient Light Level on LCD – Bluetooth Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 11.10 Project 7 – Controlling an LED – Wi-Fi Communication . . . . . . . . . . . . . . . . . 312 11.11 Project 8 – Speaking Thermometer – Wi-Fi Communication . . . . . . . . . . . . . . 315 11.12 Project 9 – Saving the Temperature Data – Wi-Fi Communication . . . . . . . . . . 318 11.13 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Appendix A • Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Appendix B • Using the MIT App Inventor offline . . . . . . . . . . . . . . . . . . . . . . . . . 326 B.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 B.2 Installing the App Inventor Ultimate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 Appendix C • Loading the programs from the book website . . . . . . . . . . . . . . . . 329 C.1 File Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 C.2 Loading MIT App Inventor Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 C.3 Loading Android UNO Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 C.4 Loading ESP32 DevKitC Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 Appendix D • MIT App Inventor extension components . . . . . . . . . . . . . . . . . . . . 330 Appendix E • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 List of components used in the book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 Processors used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332

●9

MIT App Inventer UK 200311.indd 9

03-04-20 10:37

MIT App Inventor Projects

● 10

MIT App Inventer UK 200311.indd 10

03-04-20 10:37

Preface

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 smartphones 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 knowledge 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 tablets 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 secondary 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 developed on a mobile device to display ambient temperature and humidity readings. The development 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 standalone 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 programs 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 processors to save you the time of typing them.

● 11

MIT App Inventer UK 200311.indd 11

03-04-20 10:37

MIT App Inventor Projects

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. Prof Dr Dogan Ibrahim London, 2020

● 12

MIT App Inventer UK 200311.indd 12

03-04-20 10:37

Chapter 1 • Introduction

Chapter 1 • Introduction 1.1 Text-Based Programming Traditionally computer programming has been text-based where the programmer writes sets of instructions in text form. These instructions are then compiled and turned into a binary form that can be understood by a computer. There are many text-based programming languages in use today, such as Basic, C, Pascal, etc. Text-based coding has traditionally been used in teaching the concepts of programming. When we look at the text-based programming languages, we notice that they are designed by engineers, for engineers. This makes coding difficult and learners have to spend many long times of training to learn to program efficiently. For several decades many people have tried to address this problem and designed various programming languages to make the task of programming easier. Most of these programming languages have been text-based. In the last decade, programming languages such as Visual Basic, Visual C++, and Visual C# have been popular. Although these languages are text-based they provide a graphical user interface (GUI) type interface where users can place boxes, labels, buttons, sliders, etc on the screen to make the end product more user-friendly. The code under these programming languages is still text-based where the user is expected to write the code to control the components placed on the screen. 1.2 Block-Based Visual Programming In recent years there has been an increase in the development and use of block-based visual programming tools as the solution to the above problem. The idea here is that the programmer is given a set of visual blocks and all that is required is to connect these building blocks in a logical way to create the required application program. Block-based programming has been introduced to children event at the primary education level and recent surveys show that children at an early age develop interesting applications. Block-based programming is currently used all over the world and it is estimated that over 50 million users actively use block coding. 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 joining 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 programming 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 introductory computer programming language in many primary and secondary schools. After gaining 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

MIT App Inventer UK 200311.indd 13

03-04-20 10:37

MIT App Inventor Projects

Figure 1.1 Scratch development environment Many people claim that the block-based visual programming tool does not teach the principles 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 associate 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 blockbased 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 using 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

MIT App Inventer UK 200311.indd 14

03-04-20 10:37

Chapter 1 • Introduction

started by the 8th of July, 2019). The final program is compatible with both operating systems 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.

Figure 1.2 MIT App Inventor components 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 project 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 required blocks on the mobile phone image.

● 15

MIT App Inventer UK 200311.indd 15

03-04-20 10:37

MIT App Inventor Projects

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.

Figure 1.3 Design of the project 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

MIT App Inventer UK 200311.indd 16

03-04-20 10:37

Chapter 1 • Introduction

Figure 1.4 Block program of the example 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

Figure 1.5 QR code of the application 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 application 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.

Figure 1.6 Testing the application MIT App Inventor projects can either be in standalone mode, or they 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 communicates

● 17

MIT App Inventer UK 200311.indd 17

03-04-20 10:37

MIT App Inventor Projects

with an external microcontroller-based processor, such as Raspberry Pi, Arduino, ESP8266, ESP32, etc. In this book, many tested and fully working projects have been developed both in standalone 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 programs of the external processor-based projects can be uploaded to the appropriate external processor to save you the time of typing them.

● 18

MIT App Inventer UK 200311.indd 18

03-04-20 10:37

Chapter 2 • Setting up the MIT App Inventor

Chapter 2 • Setting up the MIT App Inventor 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: A Computer and Operating System: • Macintosh (with Intel processor): Mac OS X 10.5 or higher • Windows: Windows XP, Windows Vista, Windows 7 or higher • GNU/Linux: Ubuntu 8 or higher, Debian 5 or higher (Note: GNU/Linux live development is only supported for WiFi connections between computer and Android device.) Internet Access and Internet Browser: • Mozilla Firefox 3.6 or higher • Apple Safari 5.0 or higher • Google Chrome 4.0 or higher • Microsoft Internet Explorer is not supported Android Compatible Phone or Tablet: • Android Operating System 2.3 ("Gingerbread") or higher 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. 2.2 Setting Up the App Inventor Option 1 - Using an Android Device with Wi-Fi This is the recommended option where software is developed on a PC and then uploaded (installed) to an Android device using Wi-Fi for testing (see Figure 2.1).

● 19

MIT App Inventer UK 200311.indd 19

03-04-20 10:37

MIT App Inventor Projects

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.

Figure 2.3 Click Connect and then AI Companion • Wait until the project is compiled.

● 20

MIT App Inventer UK 200311.indd 20

03-04-20 10:37

Chapter 2 • Setting up the MIT App Inventor

• A dialog with a QR code will be displayed on your PC screen as shown in Figure 2.4

Figure 2.4 The QR code • 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 instructions to install the project. • You can now test your project on the Android device 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. Option 2 - Using an Android Device With Direct Connection to the PC In this option, it is assumed that there is no Wi-Fi link. The Android device is connected to the PC using a suitable USB cable as shown in Figure 2.5.

Figure 2.5 Option 2 – Connect the Android device to the PC

● 21

MIT App Inventer UK 200311.indd 21

03-04-20 10:37

MIT App Inventor Projects

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 • Download the installer from the link:

appinv.us/aisetup_windows

• Locate the file MIT_Appinventor_Tools_2.3.0_win_setup.exe in your Downloads file • Open the file and click through the steps to install the file. It is recommendable 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-Appinventor and you'll need to launch it manually. You can launch it from the command line with /usr/google/appinventor/commands-for-Appinventor/aiStarter)

Figure 2.6 aiStarter startup window • We now have to enable USB Debugging on the Android device. Go to Settings, then System, and enable both the Developer options and USB debugging (see Figure 2.7). USB debugging is normally on the same page but under the heading DEBUGGING. You may find that the Developer Options are hidden (especially on Android 4.2 and newer) by default. If this is the case, go to Settings and About phone, and tap Build number 7 times. Then return to the previous screen to find and enable Developer options, including USB Debugging.

● 22

MIT App Inventer UK 200311.indd 22

03-04-20 10:37

Chapter 2 • Setting up the MIT App Inventor

Figure 2.7 Enable the Developer options • 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 transferring files, but not as sending pictures). You may get the message saying Allow USB Debugging?. Press OK. • Go to the Connection Test Page (appinventor.mit.edu/test.html) to make sure that the connection is ok. You should see the window as in Figure 2.8 after a successful connection.

Figure 2.8 Successful connection between Android and the PC • Once you complete your project and there is a successful USB connection between the computer and Android device, you should click Connect and then USB to upload your project to the Android device.

● 23

MIT App Inventer UK 200311.indd 23

03-04-20 10:37

MIT App Inventor Projects

Option 3 - Using the Emulator Without an Android Device In this option, it is assumed that the user has no Android devices. The application is built on a computer and then emulated using a virtual Android mobile phone which is displayed on the screen, as shown in Figure 2.9 (see link: https://appinventor.mit.edu/explore/ai2/ setup-emulator)

Figure 2.9 Using the Emulator without an Android device You will have to install software on your computer before the emulator can be used. The steps are: • Download the installer from the link:

appinv.us/aisetup_windows

• Locate the file MIT_Appinventor_Tools_2.3.0_win_setup.exe in your Downloads file • 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 Emulator as shown in Figure 2.10

● 24

MIT App Inventer UK 200311.indd 24

03-04-20 10:37

Chapter 2 • Setting up the MIT App Inventor

Figure 2.10 Start the emulator • 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.

Figure 2.11 Emulator connecting message • You should see a virtual Android mobile phone displayed with the screen changing until the project screen is displayed, as shown in Figure 2.12.

Figure 2.12 Displaying the virtual Android phone 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 different 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

MIT App Inventer UK 200311.indd 25

03-04-20 10:37

MIT App Inventor Projects

Chapter 3 • Simple MIT App Inventor projects 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 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. 3.2 Starting App Inventor and the Startup Screen You should use Firefox or Google Chrome for App Inventor project development since Microsoft Internet Explorer is not currently supported. You should create a google email account if you do not already have one. There are several ways that you can start App Inventor: • Enter the words MIT App Inventor to the Google search engine and click to start the project • Enter the following link to your web browser:

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. The Startup Screen Figure 3.1 shows the App Inventor startup screen. The middle part of the screen is the Viewer section which is the working space and it shows the layout of a mobile phone. On the left-hand side, you will see a Palette with many components that you can drag to the Viewer. The Palettes are under different categories, such as User Interface, Layout, Media, Drawing, and Animation, etc. On the right-hand side of the screen, we have the Properties section, where the properties of the components (e.g. colour, shape, behaviour, etc) can be configured. On the top part of the screen, we have several menu options. File is used to create a new file, Connect is used to connect to the MIT AI2 Companion apps, or the Emulator, or an Android device using a USB cable. A list of the user projects can be displayed by clicking My Projects. Two very important menu options are the Designer and Blocks. Option Designer is selected when we wish to develop a new project by placing various components onto the Viewer. The default screen when App Inventor is started is the Designer screen. Option Blocks is selected when we wish to develop visual programs to control the components laid on the Viewer. App Inventor programs are in the form of visual blocks that are interconnected (e.g. snapped together) to accomplish a task. The user does not need to have any text-based programming skills to use App Inventor. This will become clearer when we develop projects.

● 26

MIT App Inventer UK 200311.indd 26

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

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 lefthand 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 Inventor. It is assumed that the mobile phone is connected to the same Wi-Fi router as the laptop. 3.3 Project 1 – Using a Button to Generate Sound 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

MIT App Inventer UK 200311.indd 27

03-04-20 10:37

MIT App Inventor Projects

Aim: This project aims to show how a button can be used together with a sound clip. Steps: The steps to develop the project are given below: • Start App Inventor and click Create Apps! • Login by entering your email address and password • Click Start new project • Give a name to your project, e.g. BellSound and click OK • You will be presented with the Designer menu • 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 required changes are shown): FontBold: tick Text: Click to sound • Figure 3.3 shows the screen so far

Figure 3.3 Place a button onto the Viewer • 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

MIT App Inventer UK 200311.indd 28

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

named 96521_kleinhirn2000_reception-bell1.mp3 is used from the site https://freesound.org/people/Werra/sounds/78565/. This generates a short bell sound. Click to download the file in a folder. • 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 Button1 from the Palette on the left-hand side • 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

Figure 3.4 Click on when Button1 Click do • Click Sound1 on the left-hand side and select call Sound1.Play • Join call Sound1.Play with the when Button1.Click do as shown in Figure 3.5

Figure 3.5 Join the two blocks 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

MIT App Inventer UK 200311.indd 29

03-04-20 10:37

MIT App Inventor Projects

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 Android device • You should hear the bell sound when you click the button on your mobile phone.

Figure 3.6 The QR code of the project You may want to use the emulator if you do not have an Android device. The steps are as follows: • Click to start program aiStarter o your computer • Click Connect followed by Emulator and wait until the emulator is connected as shown in Figure 3.7

● 30

MIT App Inventer UK 200311.indd 30

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.7 Running the emulator • 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 3.4 Saving the Project Although the projects are automatically saved by App Inventor, there are many cases where we may want to save the project files externally, for example on different computers or flash drives. Projects have extensions .aia. For example, Project 1 developed in the previous section has the name BellSensor.aia. A project can be saved as follows: • Click My Projects • Click Export selected project (.aia) to my computer • 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 • Option Import project (.aia) from my computer imports a saved project to App Inventor 3.5 Deleting a Project You can delete a project by first moving it to the Trash and then deleting the Trash: • Click My Projects and then Move to Trash

● 31

MIT App Inventer UK 200311.indd 31

03-04-20 10:37

MIT App Inventor Projects

• Click View Trash, select the project and click Delete From Trash 3.6 Sharing a Project You can share your project in an executable form (.apk) that can be installed on an Android device, or in source code form (.aia) that can be loaded into App Inventor. Sharing the Executable Form The steps to share a project are as follows: • Click Build and then App (save .apk to my computer) • A window will pop up to show that the download has begun • 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 Sharing the Source Code The source code of the project can be saved as described in section 3.4 above. You can send the .aia file to your friends so that they can import it to their App Inventor programs 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. Steps: The steps to develop the project are given below: • Start App Inventor and click Create Apps! • Login by entering your email address and password • Click Start new project and give it a name, e.g. Translate • 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 SourceText, and tick box FontBold. Clear box Hint

● 32

MIT App Inventer UK 200311.indd 32

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• Click and drag a Button to the Viewer, and configure it as follows: 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.

Figure 3.8 Design of the project Now, we have to select the Blocks menu and do the visual programming part of the project. 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 Figure 3.9

● 33

MIT App Inventer UK 200311.indd 33

03-04-20 10:37

MIT App Inventor Projects

Figure 3.9 Join the two blocks • 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)

Figure 3.10 Enter en-de inside the Text 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 YandexTranslate1.GotTranslation do • Click DestText from the left-hand side and select set DestText.Text to • Click on translation on the block when YandexTranslate1.GotTranslation do and select get translation • Join the blocks as shown in Figure 3.11

Figure 3.11 Join the blocks This completes the design of the visual program. We should now compile and upload our project to the Android mobile phone. The steps are as in the previous project. i.e. Click Build and scan the QR code (Figure 3.12).

● 34

MIT App Inventer UK 200311.indd 34

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.12 The QR code of the project Figure 3.13 shows an example run of the program on an Android mobile phone where the English word large is translated into German.

Figure 3.13 Translating English word large 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. Steps: The steps to develop the project are given below: • Click Start new project and give it a name, e.g. Translate2 • Click Layout on the left-hand side and click, drag and drop HorizontalArrangement to the Viewer, and configure it as follows: AlignHorizontal: Center:3 AlignVertical: Center:2 Height: 5 percent Width: Fill parent

● 35

MIT App Inventer UK 200311.indd 35

03-04-20 10:37

MIT App Inventor Projects

• Place a Label on the HorizontalArrangement and configure it as follows: FontBold: ticked FontSize: 20 Text: English to German • You should now see the Label at the center of HorizontalArrangement as shown in Figure 3.14.

Figure 3.14 Label at the center of HorizontalArrangement • Place another HorizontalArrangement under the first one and configure it as follows: AlignHorizontal: Center:3 AlignVertical: Center:2 Height: 10 percent Width: Fill parent • Place a Label on the second HorizontalArrangement and set its FontSize to 14, and Text to Word to be translated: • Place a TextBox named SourceText next to the Label and configure it as in the previous project (i.e. FontBold ticked, FontSize 14, Hint and Text fields cleared). Figure 3.15 shows the layout so far

Figure 3.15 The layout so far • Place another HorizontalArrangement onto the Viewer with the following configuration: AlignHorizontal: Center:3 AlignVertical: Center:2 Height: 10 percent Width: Fill parent

● 36

MIT App Inventer UK 200311.indd 36

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• 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.16 The QR code of the project Figure 3.17 shows an example run of the program on an Android mobile phone where the English word book is translated into German.

Figure 3.17 Translating English word large into German 3.9 Project 4 – Text to Speech – Fixed Text Message 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. Steps: The steps to develop the project are given below: • Start a new project and name it as TTS • Place a HorizontalArrangement onto the Viewer and configure it as follows: AlignHorizontal: Center:3 AlignVertical: Center:2 Height: 5 percent Width: Fill parent

● 37

MIT App Inventer UK 200311.indd 37

03-04-20 10:37

MIT App Inventor Projects

• Place a Label on the HorizontalArrangement and configure it as follows: FontBold: ticked Text: Text To Speech • Place another HorizontalArrangement onto the Viewer and configure as follows: AlignHorizontal: Center:3 AlignVertical: Center:2 Height: 10 percent Width: Fill parent • Place a Button on the HorizontalArrangement and configure it as follows: 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 Figure 3.18 shows the completed design of the project.

Figure 3.18 Design of the project Now we have to do the Block programming. The steps are as follows: • Click Blocks • Click Button1 on the left-hand side and select when Button1.Click do • Click TextToSpeech on the left-hand side and select call TextToSpeech.Speak and join the two 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

MIT App Inventer UK 200311.indd 38

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

The final Block program is shown in Figure 3.19

Figure 3.19 Block program of the project 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.

Figure 3.20 The QR code of the project

Figure 3.21 The Android screen 3.10 Project 5 – Text to Speech – Any Text Message 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. Steps: The steps to develop the project are given below: • Start a new project and name it as TTS2 • Place a HorizontalArrangement onto the Viewer and configure it as follows: AlignHorizontal: Center:3 AlignVertical: Center:2

● 39

MIT App Inventer UK 200311.indd 39

03-04-20 10:37

MIT App Inventor Projects

Height: 5 percent Width: Fill parent • Place a Label on the HorizontalArrangement and configure it as follows: FontBold: ticked Text: Text To Speech • Place another HorizontalArrangement onto the Viewer and configure as follows: AlignHorizontal: Left:1 AlignVertical: Center:2 Height: 10 percent Width: Fill parent • Place a Label on the HorizontalArrangement and configure it as follows: FontBold: ticked FontSize: 20 Text: Text: • Place a TextBox on the HorizontalArrangement and configure it as follows: FontBold: ticked Hint: cleared Text: cleared • Place another HorizontalArrangement onto the Viewer and configure as follows: AlignHorizontal: Center:3 AlignVertical: Center:2 Height: 10 percent Width: Fill parent • Place a Button on the HorizontalArrangement and configure it as follows: FontBold: ticked FontSize: 20 Text: Click to Listen • Place a TextToSpeech on the previous HorizontalArrangement

● 40

MIT App Inventer UK 200311.indd 40

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.22 shows the final design of the phone image.

Figure 3.22 Final design on the phone image Now we have to do the Block programming. The steps are as follows: • Click Blocks • Click Button1 on the left-hand side and select when Button1.Click do • Click TextToSpeech on the left-hand side and select call TextToSpeech.Speak and join the two blocks • Click TextBox1 on the left-hand side and select TextBox1.Text. Join this block to the end of the previous block • The final Block program is shown in Figure 3.23

Figure 3.23 Block program of the project 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.

Figure 3.24 The QR code of the project

● 41

MIT App Inventer UK 200311.indd 41

03-04-20 10:37

MIT App Inventor Projects

Figure 3.25 The Android screen 3.11 Project 6 – Text to Speech – English to German 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 Figure 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. • Click TextBox1 at the left hand side and select TextBox1.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 YandexTranslate1.GotTranslation do • Click TextToSpeech1 at the left hand side and select call TextToSpeech1. Speak message

● 42

MIT App Inventer UK 200311.indd 42

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• Click on translation block when YandexTranslate1.GotTranslation do and select get translation • Join the blocks as shown in Figure 3.26

Figure 3.26 Join the blocks Build the program to get the QR code as shown in Figure 3.27. Scan and install the program on your Android device. Enter a text in English, click the button to listen to the text in German.

Figure 3.27 The QR code of the project 3.12 Project 7 – Using Images – Learning Elementary English 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 actions can be taken when these images are clicked. In this project, we will be using images of 4 objects for demonstration purposes. The number 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. Steps: The steps to develop the project are given below: • Start a new project and name it as Images • Place a HorizontalArrangement onto the Viewer and configure it as follows:

● 43

MIT App Inventer UK 200311.indd 43

03-04-20 10:37

MIT App Inventor Projects

AlignHorizontal: Center: 3 AlignVertical: Center: 2 Height: 20 percent Width: Fill parent • Place a Button (Button1) on the HorizontalArrangement and configure as follows: Height: 15 percent Width: 20 percent Text: clear • Click Upload File and browse and click on the apple image. Go to the Properties on the right-hand side for Button1, click Image, and select apple.jpg. You should see an apple image displayed on the screen • Place a Button (Button2) on the HorizontalArrangement and configure as follows: Height: 15 percent Width: 20 percent Text: clear • Click Upload File and browse and click on the banana image. Go to the Properties on the right-hand side for Button2, click Image, and select banana.jpg. You should see a banana image displayed on the screen

• Place a Button (Button3) on the HorizontalArrangement and configure as follows: Height: 15 percent Width: 20 percent Text: clear • Click Upload File and browse and click on the balloon image. Go to the Properties on the right-hand side for Button3, click Image, and select baloon.jpg. You should see a balloon image displayed on the screen • Place a Button (Button4) on the HorizontalArrangement and configure as follows: Height: 15 percent Width: 25 percent Text: clear

● 44

MIT App Inventer UK 200311.indd 44

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• 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 This completes the design of the project as shown in Figure 3.28.

Figure 3.28 Design of the project Now we have to do the Block programming. The steps are as follows: • Click Blocks • Click Button1 on the left-hand side and select when Button1.Click do • Click TextToSpeech on the left-hand side and select call TextToSpeech.Speak and join the two blocks • Click Text under Built-in and join it to the blocks. Set the text inside this block to This is an apple • Click Button2 on the left-hand side and select when Button2.Click do • Click TextToSpeech on the left-hand side and select call TextToSpeech.Speak and join the two blocks • Click Text under Built-in and join it to the blocks. Set the text inside this block to This is a banana • Click Button3 on the left-hand side and select when Button3.Click do • Click TextToSpeech on the left-hand side and select call TextToSpeech.Speak and join the two blocks • Click Text under Built-in and join it to the blocks. Set the text inside this block to This is a balloon

● 45

MIT App Inventer UK 200311.indd 45

03-04-20 10:37

MIT App Inventor Projects

• Click Button4 on the left-hand side and select when Button4.Click do • Click TextToSpeech on the left-hand side and select call TextToSpeech.Speak and join the two blocks • Click Text under Built-in and join it to the blocks. Set the text inside this block to This is a car Figure 3.29 shows the completed Block program of the project.

Figure 3.29 Block program of the project 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.

Figure 3.30 The QR code of the project Figure 3.31 shows the images displayed on an Android mobile phone.

● 46

MIT App Inventer UK 200311.indd 46

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.31 Images displayed on an Android phone 3 .13 Project 8 – Speaking a Received SMS Message 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. Steps: The steps to develop the project are given below: • Start a new project and name it as MyMails • 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

MIT App Inventer UK 200311.indd 47

03-04-20 10:37

MIT App Inventor Projects

• 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 This completes the design of the project as shown in Figure 3.32.

Figure 3.32 Design of the project 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. The steps are as follows: • Click Blocks • Click Button1 on the left-hand side and select when Button1.Click do • Click Texting1 on the left-hand side and select set Texting1.ReceivingEnabled to • Click Math under Built-in and select the first block (the number block). Enter number 2 into this block and join the blocks • Click TextToSpeech1 and select set TextToSpeech1.Speechrate to • 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.

Figure 3.33 Initializing components Texting and TextToSpeech

● 48

MIT App Inventer UK 200311.indd 48

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

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 Texting1 and select when Texting1.MessageReceived • Click TextToSpeech1 and select call TextToSpeech1.Speak Message. Join the two blocks • Click and drag block Join in Text under Built-in • 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 • Insert another Join block, click on number in when Texting1.MessageReceived and join the block get number to block Join • Insert another Join block, click on messageText in when Texting1.MessageReceived and join the block get messageText to block Join The block program of the project is complete as shown in Figure 3.34. When a new message 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.

Figure 3.34 Complete block program of the project 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

MIT App Inventer UK 200311.indd 49

03-04-20 10:37

MIT App Inventor Projects

Figure 3.35 The QR code of the project 3.14 Project 9 – Sending SMS Messages 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: • Start a new project and name it as SendSMS • 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 Label and a TextBox. Set the Text of the Label to Number:, and the name of the TextBox to TxtNumber. Clear the Hint field of the TextBox. This text box will receive the phone number of the person where we wish to send the SMS to • Insert another HorizontalArrangement and drop a Label and a TextBox. Set the Text of the Label to Message:, and the name of the TextBox to TxtMessage. Clear the Hint field of the TextBox. This text box will receive the message we wish to send • Insert another HorizontalArrangement and drop a Button. Set the Text of the Button to Click to Send, and its FontColor to Red • Drag and drop a Texting component from the Social tab This completes the design of the project as shown in Figure 3.36.

Figure 3.36 Design of the project

● 50

MIT App Inventer UK 200311.indd 50

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

We now have to create the blocks to send SMS messages. The steps are as follows: • Drop a block when Button1.Click do • Click Texting1 and select set Texting1.PhoneNumber to • Click TxtNumber and select TxtNumber.Text and join to the previous block • Click Texting1 and select set Texting1.Message to • Click TxtMessage and select TxtMessage.Text and join to the previous blocks • Click Texting1 and select call Texting1.SendMessageDirect 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.

Figure 3.37 Complete block program of the project 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.38 The QR code of the project Figure 3.39 shows the Android phone screen running the project.

Figure 3.39 Android phone screen

● 51

MIT App Inventer UK 200311.indd 51

03-04-20 10:37

MIT App Inventor Projects

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 message 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: • Start a new project and name it as BusySMS • Place a HorizontalArrangement onto the Viewer and insert a Label onto this, set the Text of this label to Read SMS and Reply Busy • Place another HorizontalArrangement onto the Viewer and insert a Button onto this, set the Text of this Button to Click to Start • Drag and drop a TextToSpeech and a Texting component. These are not shown on the phone image This completes the design of the project as shown in Figure 3.40.

Figure 3.40 Design of the project 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.PhoneNumber to • The message Sorry, I am busy now, I will reply later is stored in block set Texting1.Message to

● 52

MIT App Inventer UK 200311.indd 52

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• Texting block call Texting1.SendMessageDirect is used to reply to the sender 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.

Figure 3.41 The QR code of the project 3.16 Project 11 – Display the Received SMS Message 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: • Start a new project and name it as DisplaySMS • Place 3 HorizontalArrangements as shown in Figure 3.42. Drop a Label and TextBox on the last two HorizontalArrangements. Set the name of the first TextBox to TxtNumber, and the second one to TxtMessage respectively. These will display the phone number of the sender and the message received. • Place a Texting on the Viewer as before

Figure 3.42 Design of the project

● 53

MIT App Inventer UK 200311.indd 53

03-04-20 10:37

MIT App Inventor Projects

The steps to design the Block program are as follows: • 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 • Click Texting and select when Texting1.MessageReceived do • Click TxtNumber and select set TxtNumber.Text to • Click number when Texting1.MessageReceived do and join as in Figure 3.43 • Click TxtMessage and select set TxtMessage.Text to • Click messageText on when Texting1.MessageReceived do and join as shown in Figure 3.43

Figure 3.43 Block program of the project Build the program to get the QR code as shown in Figure 3.44. Scan and install the program 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.44 The QR code of the project Figure 3.45 shows a message received on the Android mobile phone (part of the phone number is masked for security).

● 54

MIT App Inventer UK 200311.indd 54

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.45 Message received on the Android mobile phone 3.17 Project 12 – Calling a Fixed Telephone Number 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: • Start a new project and name it as CallOne • Place 2 HorizontalArrangements as shown in Figure 3.46. Drop a Label on the first HorizontalArrangement and a Button on the second HorizontalArrangement. Set the Text of the Label to CALL TO NUMBER: 07860295594, and set the Text of the Button to CLICK TO CALL. • 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.

Figure 3.46 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 Button1 and select block when Button1.Click do • Click PhoneCall1 and select set PhoneCall1.PhoneNumber to • Click the top text block under Built-in and join the blocks as shown in Figure 3.47.

● 55

MIT App Inventer UK 200311.indd 55

03-04-20 10:37

MIT App Inventor Projects

• Insert the required phone number inside the text box • Click PhoneCall and select call PhoneCall1.MakePhoneCallDirect This completes the block program of the project. Notice that there are two blocks for making 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.

Figure 3.47 Block program of the project 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.

Figure 3.48 The QR code of the project 3.18 Project 13 – Calling to Several Fixed Telephone Numbers 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. The steps are as follows: • Start a new project and name it as CallSeveral • Click Screen1 and change its Text to Family Calls • Place 3 HorizontalArrangements and drop 3 Buttons on these HorizontalArrangements as shown in Figure 3.49. Name the buttons as ButtonMother, ButtonFather, and ButtonSister • Drop a PhoneCall component onto the Viewer

● 56

MIT App Inventer UK 200311.indd 56

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.49 Design of the project 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 telephone 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.

Figure 3.50 Block program of the project 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.51 The QR code of the project Figure 3.52 shows a snapshot of the application on the Android mobile phone.

● 57

MIT App Inventer UK 200311.indd 57

03-04-20 10:37

MIT App Inventor Projects

Figure 3.52 Snapshot of the program 3.19 Project 14 – Calling from the Contacts List 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. In this application, we will be using the new component called PhoneNumberPicker in addition to the component PhoneCall, both under the Social tab. The steps are as follows: • Start a new project and name it as CallContacts • Click Screen1 and change its Text to Contacts • Insert a HorizontalArrangements component onto the Viewer • Click Social and insert a PhoneNumberPicker component onto the HorizontalArrangement. Change the Text of this component to Pick a Number • Click Social and insert a PhoneCall component onto the phone image. This will not be visible as was described earlier The design of the project is complete and is shown in Figure 3.53.

Figure 3.53 Design of the project The block program is shown in Figure 3.54 and the steps are as follows:

● 58

MIT App Inventer UK 200311.indd 58

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• Click component PhoneNumberPicker1 on the left-hand side and select when PhoneNumberPicker1.After Picking do. Clicking this button will open the contacts list on our Android mobile phone. • Click PhoneCall1 on the left-hand side and select set PhoneCall1.PhoneNumber to • Click PhoneCall1 and select PhoneNumberPicker1.PhoneNumber. The picked phone number will be loaded into block PhoneCall1. • Click PhoneCall1 and select call PhoneCall1.MakePhoneCallDirect so that the selected number can be dialed

Figure 3.54 Block program of the project 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.

Figure 3.55 The QR code of the project 3.20 Project 15 – Taking Pictures with the Camera 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. The steps are as follows: • Insert a Button on a HorizontalArrangement and set its Text to Click to Take a Picture

● 59

MIT App Inventer UK 200311.indd 59

03-04-20 10:37

MIT App Inventor Projects

• 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 Viewer. Both of these components are not visible Figure 3.56 shows the design of the project on the phone image.

Figure 3.56 Design of the project The block program is shown in Figure 3.57 and the steps are as follows: • Click Button1 and select when Button1.Click do • Click Camera1 and select call Camera1.TakePicture • 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 Camera1 and select when Camer1.AfterPicture do • Click Image1 and select set Image1.Picture to • Click image on when Camer1.AfterPicture do and join to the previous block as shown in Figure 3.57 • Click TextToSpeech1 and select call TextToSpeech1.Speak message • Click Text under Built-in and select the first block. Enter text The photo has been taken successfully

● 60

MIT App Inventer UK 200311.indd 60

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.57 Block program of the project Build the program to get the QR code as shown in Figure 3.58. Scan and install the program 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.58 The QR code of the project 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.

Figure 3.59 Snapshot of the Android mobile phone screen 3.21 Project 16 – A Basic Piano 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

MIT App Inventer UK 200311.indd 61

03-04-20 10:37

MIT App Inventor Projects

In this application, we will be using two new components called Sound and Player. Component 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). The steps are as follows: • Create a new project and name it as Piano • Insert a HorizontalArrangement and set its AlignHorizontal to Center: 3 and AlignVertical to Center: 2. • Insert 8 buttons on the HorizontalArrangement and set their texts to musical notes, BackgroundColor to black and TextColor to white. The buttons should have the following texts and names: 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. The completed design is shown in Figure 3.60.

● 62

MIT App Inventer UK 200311.indd 62

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.60 Design of the project

Figure 3.61 Musical note files 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. The steps are: • Click Screen1 and select when Screen1.Initialize do. This block will be activated when the application is started on the Android device • Click Sound1 and select set Sound1.MinimumInterval to

● 63

MIT App Inventer UK 200311.indd 63

03-04-20 10:37

MIT App Inventor Projects

• 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 selected musical note • Repeat for the other 7 musical notes as shown in Figure 3.62.

Figure 3.62 Block program of the project 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.

Figure 3.63 The QR code of the project

● 64

MIT App Inventer UK 200311.indd 64

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.64 shows a snapshot of the Android phone with the application running.

Figure 3.64 Snapshot of the Android mobile phone screen 3.22 Project 17 – Acceleration Description: Android compatible devices have built-in accelerometer modules. In this project, 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. In this application, we will be using the component called AccelerometerSensor under the Sensors tab. The steps are as follows: • Create a new project called Acceleration • Insert 4 HorizontalArrangement blocks and insert 8 labels on these blocks, 2 on each HorizontalArrangement. Name and configure the labels as follows:

● 65

MIT App Inventer UK 200311.indd 65

03-04-20 10:37

MIT App Inventor Projects



Left-Label Text

Right-Label

Right-Label Text

HorizontalArrangement1 Label1

Left-Label

X-direction:

LblX

X

HorizontalArrangement2

Y-direction

LblY

Y

HorizontalArrangement3 Label3

Z-direction

LblZ

Z

HorizontalArrangement4

Acc Magnitude

LblMagnitude

M

Label 2 Label6

• Click Sensors and drop an AccelerometerSensor on the Viewer. This is a hidden component. Figure 3.65 shows the design of the project.

Figure 3.65 Design of the project 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 • Click AccelerometerSensor1 and select when AccelerometerSensor1.AcceleratiobChanged do. This block will be activated when the acceleration in any direction changes. i.e. when the Android device is moved or shaken • Click LblX and select set LblX.Text to • Click xAccel on when AccelerometerSensor1.AcceleratiobChanged do and join the previous block as shown in Figure 3.66. • Repeat for LblY and LblZ • We now have the acceleration in all three dimensions. The next step is to calculate the magnitude of the acceleration • Click Variables and select set-to, insert name global M to • Click Math and insert the addition block • Click Math and insert two multiplication blocks

● 66

MIT App Inventer UK 200311.indd 66

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• Insert LblX.Text and LblY.Text as shown in the figure • Click Variables and select set-to, insert name global M to • Click Math and insert the addition block • Click Variables and select get, change the name to global M • Click Math and add a multiplication block • Insert LblZ.Text as shown in the figure • Click LblMagnitude and enter set LblMagnitude.Text to • Click Math and insert square root • Click Variables and insert get, insert global M • 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)

Figure 3.66 Block program of the project 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.

Figure 3.67 The QR code of the project

● 67

MIT App Inventer UK 200311.indd 67

03-04-20 10:37

MIT App Inventor Projects

Figure 3.68 Snapshot of the Android mobile phone screen 3.23 Project 18 – Light Level Description: Android mobile devices have built-in light level sensors. This project measures 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 Inventor projects. This project uses the LightSensor component under the Sensors tab. • Create a new project called LightLevel • Insert two Horizontal Arrangement blocks as shown in Figure 3.69. Insert a Label with the Text set to Light Level (lux): and a TextBox named TxtLight onto the top HorizontalArrangement. The measured light level will be shown by this TextBox • Insert a Label named LblHint onto the bottom HorizontalArrangement. Clear the Text field of this label. This label will not be visible on the phone image and it will display whether or not the light level is enough to study. • Click the Sensors tab and insert the component LightSensor onto the Viewer. This is a hidden component.

Figure 3.69 Design of the project

● 68

MIT App Inventer UK 200311.indd 68

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

The block program is shown in Figure 3.70. The steps are as follows: • Click LightSensor1 and select when LightSensor1.LightChanged do • Click TxtLight and select set TxtLight.Text to • Click on lux on the block when LightSensor1.LightChanged do and join block get lux as shown in the figure • Click on Control under Built-in and select the if-then block • Click on the if-then block to display the else option as well • Click TxtLight and select TxtLight.Text • 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 LblHint and select set LblHint.Text to • 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 LblHint and select set LblHint.Text to • Click Text and insert the first block to enter text. Enter text Light Level good to study

Figure 3.70 Block program of the project 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

MIT App Inventer UK 200311.indd 69

03-04-20 10:37

MIT App Inventor Projects

Figure 3.71 The QR code of the project Figure 3.72 shows an example display on the Android mobile phone.

Figure 3.72 Snapshot of the Android mobile phone screen 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 addition to the latitude, longitude, and altitude, we can also extract the speed of travel and the name of the provider (e.g. GPS). • Create a new project called Location • Insert 5 Horizontal Arrangement blocks as shown in Figure 3.73. Insert the following labels and textboxes on these HorizontalArrangements: Label Latitude: Longitude: Altitude: Speed: Provider:

TextBox TxtLatitude TxtLongitude TxtAltitude TxtSpeed TxtProvider

● 70

MIT App Inventer UK 200311.indd 70

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• Click the Sensors tab and insert a LocationSensor component onto the Viewer. This is a hidden component.

Figure 3.73 Design of the project The block program is shown in Figure 3.74. The steps are as follows: • Click LocationSensor1 and select when LocationSensor1.LocationChanged do • Click on LocationSensor1 and select set LocationSensor1.TimeInterval to • 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) • Click on TxtLatitude and select set TxtLatitude.Text to • Click on latitude on the block when LocationSensor1.LocationChanged do and join with the previous blocks as shown in the figure • Repeat the above steps for the longitude, altitude, and speed • Click on TxtProvider and select set TxtProvider.Text to • Click on LocationSensor and select LocationSensor1.ProviderName. This is the name of the location provider (e.g. GPS)

Figure 3.74 Block program of the project

● 71

MIT App Inventer UK 200311.indd 71

03-04-20 10:37

MIT App Inventor Projects

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 provider is displayed as GPS.

Figure 3.75 The QR code of the project Figure 3.76 shows an example display on the Android mobile phone.

Figure 3.76 Snapshot of the Android mobile phone screen 3.25 Project 20 – Pinpointing Your Location on a Map 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

MIT App Inventer UK 200311.indd 72

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

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 steps are as follows: • Create a new project called map • Insert two HorizontalArrangements and enter labels and textboxes to display the latitude and the longitude as in the previous project (see Figure 3.77). • Insert a HorizontalArrangement and insert a Button, set its Text to Click to Display Map • Insert a LocationSensor component as before • Click User Interface, drag and drop a WebViewer component

Figure 3.77 Design of the project 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 increase the connectors to four

● 73

MIT App Inventer UK 200311.indd 73

03-04-20 10:37

MIT App Inventor Projects

• Insert a Text block and enter the text https://www.google.com/maps/ search/?api=1&query= • We now have to add the latitude to the URL. Click TxtLatitude and select TxtLatitude.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 display 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

Figure 3.78 Block program of the project 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

Figure 3.79 The QR code of the project

● 74

MIT App Inventer UK 200311.indd 74

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.80 shows an example display on the Android mobile phone.

Figure 3.80 Snapshot of the Android mobile phone screen 3.26 Project 21 – Display/Set Time Description: This project displays and/or sets the current time Aim: This project aims to show how the current time can be displayed and set if required using App Inventor. This project uses a component called TimePicker. The steps are: • Create a new project and name it as Time • Insert a Horizontal Arrangement • Click component TimePicker under User Interface and place it on the HorizontalArrangement (see Figure 3.81) • Configure the TimePicker1 as follows:

● 75

MIT App Inventer UK 200311.indd 75

03-04-20 10:37

MIT App Inventor Projects

FontBold: ticked FontSize: 20 Text: DISPLAY/SET TIME

Figure 3.81 Design of the project The block program is shown in Figure 3.82. The steps are: • Click TimePicker1 and select when TimePicker1.AfterTimeSet do • Click TimePicker1 and select call TimePicker1.LaunchPicker and join with the other block as shown in the figure

Figure 3.82 Block program of the project 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.

Figure 3.83 The QR code of the project

● 76

MIT App Inventer UK 200311.indd 76

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.84 Snapshot of the Android mobile phone screen Note: The DatePicker component can be used to display/set the current date 3.27 Project 22 – Record/Play Sound 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: • Create a new project and name it as RecordPlay • Insert 3 HorizontalArrangements and insert 4 buttons (Figure 3.85) with the following configurations:

Button Name

FontBold

FontSize

Button Text



ButtonStart

ticked

20

START RECORDING



ButtonStop

ticked

20

STOP RECORDING



ButtonStartPlay

ticked

20

START PLAY



ButtonStopPlay

ticked

20

STOP PLAY

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 ButtonStop is clicked and the colour of ButtonStart changes back to black. Clicking ButtonStartPlay starts playing the recorded sound and the button colour changes to green. Clicking ButtonStopPlay stops playing the recorded sound and the ButtonStartPlay colour changes back to black.

● 77

MIT App Inventer UK 200311.indd 77

03-04-20 10:37

MIT App Inventor Projects

• Click the Media tab and insert components Player and SoundRecorder. Both of these components are hidden

Figure 3.85 Design of the project 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 recording. 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 recorded 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.

Figure 3.86 Block program of the project 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

MIT App Inventer UK 200311.indd 78

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• Click Permissions • Click Storage • Locate apps RecordPlay and enable it 3.28 Project 23 – Speech Recognizer – Translate Speech to Another Language 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 The steps are: • Create a new project and name it as Speech • Insert two HorizontalArrangements (Figure 3.87) and two Buttons on them. When ButtonStart is clicked the user will be expected to speak in English where the speech is recorded internally. Clicking the ButtonTranslate will translate the speech into German and play it on the android device's speaker.

Figure 3.87 Design of the project

● 79

MIT App Inventer UK 200311.indd 79

03-04-20 10:37

MIT App Inventor Projects

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. • Click ButtonStart and select when ButtonStart1.Click do • Click SpeechRecognizer1 and select call SpeechRecognizer1.GetText. The spoken message will be received by component SpeechRecognizer1 • At the end of the speech we have to store the spoken message. Click SpeechRecognizer1 and select when SpeechRecognizer1.AfterGettingText 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 • Click YandexTranslate1 and select when YandexTranslate1.RequestTranslation. set the languageToTranslateTo to German (i.e. de) and the textToTranslate to speech • Now, we have to get the translated message and speak it through the speaker. Click YandexTranslate1 and select when YandexTranslate1.GetTranslation do • Copy the translated message into variable trans • Click TextToSpeech1 and select when TextToSpeech1.Language to and set it to English (i.e. en) • Click TextToSpeech and select call TextToSpeech1.Speak and set the message to variable trans so that the contents of trans is spoken

● 80

MIT App Inventer UK 200311.indd 80

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.88 Block program of the project 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.

Figure 3.89 The QR code of the project 3.29 Project 24 – Chronograph 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

MIT App Inventer UK 200311.indd 81

03-04-20 10:37

MIT App Inventor Projects

The steps are: • Create a new project and name it as Chronograph • Insert 4 HorizontalArrangements (Figure 3.90) on the Viewer. Insert the following components on these HorizontalArrangements: Component FontBold FontSize Name

Text

Label

TIME(secs): Black

ticked

20

Label1

FontColor

TextBox

ticked

20

ButtonStart START

Green

TextBox

ticked

20

ButtonStop STOP

Red

TextBox

ticked

20

ButtonClear CLEAR

Blue

• Click Sensor tab and insert a Clock component. This component is not visible

Figure 3.90 Design of the project 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 • Click Logic under Built-in and select false • 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 • Click TxtSecs and select set TextSecs.Text to

● 82

MIT App Inventer UK 200311.indd 82

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

• 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

Figure 3.91 Block program of the project 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.

Figure 3.92 The QR code of the project Figure 3.93 shows a snapshot of the application on an Android mobile phone.

Figure 3.93 Snapshot of the application on Android mobile phone

● 83

MIT App Inventer UK 200311.indd 83

03-04-20 10:37

MIT App Inventor Projects

3.30 Project 25 – Seconds Down Counter 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 The steps are: • Create a new project and name it as CountDown • Insert two HorizontalArrangements (Figure 3.94) on the Viewer. Insert a Label with its Text set to Starting Count (secs): and a TextBox named TxtSecs. User enters the initial value of the count into this TextBox • Insert a Button named ButtonStart onto the second HorizontalArrangement • Click Media tab and insert a Sound component. Also, click Sensors tab and insert a Clock component

Figure 3.94 Design of the project Figure 3.95 shows the block program of the project. The steps are: • Disable the timer as in the previous project • Start the timer when ButtonStart is clicked as in the previous project • Decrement the value of TxtSecs.Text every second • 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 display an image when the count terminates)

● 84

MIT App Inventer UK 200311.indd 84

03-04-20 10:37

Chapter 3 • Simple MIT App Inventor projects

Figure 3.95 Block program of the project Build the program to get the QR code as shown in Figure 3.96. Scan and install the program 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.96 The QR code of the project Figure 3.97 shows a snapshot of the application on the Android mobile phone.

Figure 3.97 Snapshot of the application on 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

MIT App Inventer UK 200311.indd 85

03-04-20 10:37

MIT App Inventor Projects

Chapter 4 • MIT App Inventor projects using mathematical & logical operations 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 Inventor. 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. 4.2 Project 1 – Area of a Triangle 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: • Create a project and name it Triangle • In this project, the base (TxtBase), height (TxtHeight), and the area (TxtArea) of the triangle are configured as TextBoxes as shown in Figure 4.1

Figure 4.1 Design of the project 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

MIT App Inventer UK 200311.indd 86

03-04-20 10:37

Chapter 4 • MIT App Inventor projects using mathematical & logical operations

Figure 4.2 Block program of the project

Figure 4.3 Creating a multiplication block with 3 inputs Figure 4.4 shows the QR code for this project.

Figure 4.4 QR code of the project Figure 4.5 shows a snapshot of the Android mobile running the application.

Figure 4.5 Snapshot of the Android screen

● 87

MIT App Inventer UK 200311.indd 87

03-04-20 10:37

MIT App Inventor Projects

4.3 Project 2 – Areas of Various Shapes 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 TextBoxes on the screen. Aim: This project aims to show how checkboxes can be used in App Inventor based projects. The following data is required to be entered for each shape: Square: Rectangle: Triangle:

one side (a) Area = a x a two sides (a and b) Area = a x b base (b) and height (h) Area = b x h / 2

The Steps are as follows: • Create a new project and name it as Areas • Insert the following components on the Viewer (see Figure 4.6): Component Name FontBold FontSize Text Checkbox ChkSquare ticked 20 Square Label Label3 ticked 20 a= TxtBox TxtSquarea ticked 14 Checkbox Checkrectangle ticked 20 Rectangle Label Label4 ticked 20 a= TextBox TxtRectanglea ticked 14 Label Label5 ticked 20 b= TextBox TxtRectangleb ticked 14 Checkbox ChkTriangle ticked 20 Triangle Label Label6 ticked 20 b= TextBox TxtTriangleb ticked 14 Label Label7 ticked 20 h= TextBox TxtTriangleh ticked 14 Label Label2 ticked 20 AREA TextBox TxtArea ticked 14 Button ButtonClear ticked 20 CLICK TO CLEAR

● 88

MIT App Inventer UK 200311.indd 88

03-04-20 10:37

Chapter 4 • MIT App Inventor projects using mathematical & logical operations

Figure 4.6 Design of the project 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 • Repeat for the rectangle and triangle as shown in Figure 4.6 • When the button CLICK TO CLEAR is clicked, we want to clear all the checkboxes 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

Figure 4.7 Block program of the project 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

MIT App Inventer UK 200311.indd 89

03-04-20 10:37

MIT App Inventor Projects

Figure 4.8 QR code of the application

Figure 4.9 Example snapshot on the Android mobile phone 4.4 Project 3 – Roots of a Quadratic Equation 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 formula:

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. The steps are: • Create a new project and name it as Quadratic • Insert a TableArrangement having 4 columns and 3 rows and enter the following components on it (Figure 4.10):

● 90

MIT App Inventer UK 200311.indd 90

03-04-20 10:37

Chapter 4 • MIT App Inventor projects using mathematical & logical operations

Component Name

FontBold FontSize

Text

Label

Label1

ticked

14

Enter a:

TextBox

Txta

ticked

14

Label

Label2

ticked

14

TextBox

Txtb

ticked

14

Label

Label3

ticked

14

TextBox

Txtc

ticked

14

Button

ButtonCalc ticked

Width 20%

Enter b: 20%

Enter c:

20

20%

Calculate

• Insert 3 HorizontalArrangements with the following components: Component Name

FontBold FontSize Text

Label

Label4 ticked 14

TextBox

TxtRoot1 ticked 14

Label

Label5 ticked 14

TextBox

TxtRoot2 ticked 14

Button

ButtonClear ticked

14

Root1: Root2: CLEAR

Figure 4.10 Design of the project 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 . If det is greater than or equal to 0 then the equation det to be equal to has real roots.

• Set TxtRoot1.Text to one of the roots of the equation. i.e.

• Set TxtRoot2.Text to the second root of the equation. i.e. • If det is less than 0 then the equation has complex roots and the message Complex roots is displayed in TxtRoot1 and TxtRoot2.

● 91

MIT App Inventer UK 200311.indd 91

03-04-20 10:37

MIT App Inventor Projects

• When the TxtClear button (Clear) is clicked, clear all the TextBoxes as shown in Figure 4.11.

Figure 4.11 Block program of the project 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.

Figure 4.12 QR code of the project

Figure 4.13 Sample run of the program

● 92

MIT App Inventer UK 200311.indd 92

03-04-20 10:37

Chapter 4 • MIT App Inventor projects using mathematical & logical operations

4.5 Project 4 – Random Numbers – Dice Numbers 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 Inventor. 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.

Figure 4.14 Dice image The steps are: • Create a new project and name it as Dice • Insert a HorizontalArrangement and insert two TextBoxes on it with the names TxtDice1 and TxtDice2 (Figure 4.15) • Click the Sensors tab and insert an AccelerometerSensor component on the viewer. • Upload the image dice.jpg. Click Screen1 and click on Icon. Select image dice. jpg. This image identifies the application.

Figure 4.15 Design of the project

● 93

MIT App Inventer UK 200311.indd 93

03-04-20 10:37

MIT App Inventor Projects

Figure 4.16 shows the block program of the project. The steps are: • Click AccelerometerSensor1 and select when AccelerometerSensor1. Shaking do. This block will be activated when the device is shaken • Click TxtDice1 and select set TxtDice1.Text to • 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

Figure 4.16 Block program of the project 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.

Figure 4.17 QR code of the project

Figure 4.18 Sample run of the program 4.6 Project 5 – Quiz - Learning Multiplication 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 answer 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

MIT App Inventer UK 200311.indd 94

03-04-20 10:37

Chapter 4 • MIT App Inventor projects using mathematical & logical operations

The design of the project is shown in Figure 4.19. Three HorizontalArrangments are inserted on the Viewer with the following components: Component Name

FontBold FontSize Text

Button

ButtonStart ticked

Label

LabelQuiz ticked 20

20

Start Quiz

TextBox TxtAnswer ticked 20 Button

ButtonAnswer ticked

20

Answer

Button

ButtonClear ticked

20

Clear

Label

LabelCheck ticked 22

Check

Figure 4.19 Design of the project Figure 4.20 shows the block program of the project. The steps are: • Create a new project and name it as Quiz • Initialize 3 variables called no1, no2, and no3. no1 and no2 will store the multiplier and the multiplicand, and no3 will store the result of the multiplication • When ButtonStart (Start button) is clicked we generate two random numbers between 1 and 100 and store them in no1 and no2 respectively • The result is stored in variable no3 • LabelQuiz.Text is set to the string: no1xno2= • 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

MIT App Inventer UK 200311.indd 95

03-04-20 10:37

MIT App Inventor Projects

Figure 4.20 Block program of the project The QR code of the project is shown in Figure 4.21. An example run of the program is shown in Figure 4.22.

Figure 4.21 Q code of the project

Figure 4.22 Example run of the project 4.7 Project 6 – Table of Trigonometric Functions Description: In this project the trigonometric functions sine, cosine, and tangent are displayed 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 The steps are: • Create a new project called Trig • Insert a HorizontalArrangement with the following configuration (Figure 4.23):

● 96

MIT App Inventer UK 200311.indd 96

03-04-20 10:37

Chapter 4 • MIT App Inventor projects using mathematical & logical operations

AlignHorizontal: Center: 3 AlignVertical: Top: 1 Height: 30 percent Width: Fill parent • Insert 3 Labels named LabelSine, LabelCosine, LabelTangent with their Texts set to SIN COS and TAN respectively. Separate these labels with unused labels having widths 2 percent. • Insert a Button called ButtonStart on a new HorizontalArrangement. Clicking this button will display the table of trigonometric functions

Figure 4.23 Design of the project Figure 4.24 shows the block program of the project. The steps are: • Initialize 3 variables called tablesine, tablecosine, and tabletangent as shown in Figure 4.24. These are the headings of the table elements. • When ButtonStart (Click to Start) is clicked, insert a loop by clicking Control under Built-in and select for each number from 0 to 45 by 5. The loop variable number will have the values 0, 5, 10, 15, ….., 45 • Set variable tablesine to trigonometric sin. Notice that a table is obtained by adding the previous values of tablesine and adding a new-line character (\n) at the end of each record • Repeat for cosine and tangent • Display the sine table in LabelSine.Text Repeat for cosine and tangent

● 97

MIT App Inventer UK 200311.indd 97

03-04-20 10:37

MIT App Inventor Projects

Figure 4.24 Block program of the project Figure 4.25 shows the QR code of the project. A sample run of the program is shown in Figure 4.26.

Figure 4.25 QR code of the project

Figure 4.26 Sample run of the project 4.8 Project 7 – Multiplication Time Tables 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

MIT App Inventer UK 200311.indd 98

03-04-20 10:37

Chapter 4 • MIT App Inventor projects using mathematical & logical operations

• Create a new project and name it as times • Insert a HorizontalArrangement and insert the following components on it (Figure 4.27): Component

Name

FontBold FontSize Text

Label

Label1

ticked

TxtBox

TxtTablefor ticked

20

Table for:

20

Button

ButtonStart ticked

20

Start

Button

ButtonClear ticked

20

Clear

• Insert a Label named TxtTable with its FontBold ticked and FontSize set to 20. This Label will store the time table elements

Figure 4.27 Design of the project Figure 4.28 shows the block program of the project. The steps are: • Initialize 3 variables called multiplier, multtable, and result. • Insert a block that will be activated when ButtonStart is clicked. Store the required 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 • Copy multtable to TxtTable.Text so that it is displayed on the screen • Insert a block that will be activated when ButtonClear is clicked. Clear TxtTablefor.Text and TxtTable.Text when this button is clicked

● 99

MIT App Inventer UK 200311.indd 99

03-04-20 10:37

MIT App Inventor Projects

Figure 4.28 Block program of the project Figure 4.29 shows the QR code of the project. A sample run of the program is shown in Figure 4.30.

Figure 4.29 QR code of the project

Figure 4.30 Sample run of the project 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 Procedures block under Built-in. As an example, the block program given in Figure 4.28 can be

● 100

MIT App Inventer UK 200311.indd 100

03-04-20 10:37

Chapter 4 • MIT App Inventor projects using mathematical & logical operations

modified such that the sections of the program after the loop can be executed as a procedure. 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 • Join the second group of blocks to block to Times do. • The first group of blocks now calls procedure Times which is the second group of blocks

Figure 4.31 Block program using a procedure 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

MIT App Inventer UK 200311.indd 101

03-04-20 10:37

MIT App Inventor Projects

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system 5.1 Overview Raspberry Pi has recently become one of the most popular and powerful single-board computers 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. 5.2 Parts of Raspberry Pi 4 Just like its earlier versions, Raspberry Pi 4 is a single-board computer having the following basic specifications: • 1.5GHz 64-bit quad-core CPU • 1GB, 2GB, or 4GB RAM • 2.4GHZ and 5.0GHz IEEE 802.11ac Wi-Fi • Bluetooth 5.0 BLE • Gigabit Ethernet • 2 x USB 3.0, 2 x USB 2.0 and 1 x USB-C ports • 2 x micro-HDMI ports for dual display, supporting up to 4K resolution • DSI display and CSI camera ports • micro SD card slot for the operating system and data storage • 4-pole stereo audio and composite video port • 40-pin GPIO header • Power over Ethernet (PoE) enabled with the PoE HAT • OpenGL ES 3.0 graphics Figure 5.1 shows a Raspberry Pi 4 board with its major components identified.

Figure 5.1 Raspberry Pi 4 board

● 102

MIT App Inventer UK 200311.indd 102

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

A brief description of the various components on the board is given below: Processor: the processor is enclosed in a metal cap and it is based on Broadcom BCM2711B0, which consists of a Cortex A-72 core, operating at 1.5GHz. RAM: There are 3 versions of Raspberry Pi 4 depending on the amount of DDR4 RAM required: 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 composite video interface. Headphones can be connected to this port. External amplifier devices 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 network 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. 5.3 Requirements of Raspberry Pi 4 As listed below, several external devices are required before the Raspberry Pi can be used: • Power supply • Micro SD card • Operating system software

● 103

MIT App Inventer UK 200311.indd 103

03-04-20 10:37

MIT App Inventor Projects

• USB keyboard and mouse • A micro HDMI cable to receive sound and video signals • HDMI compatible display or TV (you may also need to have micro HDMI to DVI-D or VGA adapters. A 3.5mm TRRS type cable and plug will be required if you will be using an old TV with composite video) 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 adapter to provide power from an external source.

Figure 5.2 Official Raspberry Pi 4 power supply 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 operating 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 interface, 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

MIT App Inventer UK 200311.indd 104

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

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%.

Figure 5.3 Raspberry Pi 4 CPU fan 5.3.1 Setup Option 1 As shown in Figure 5.4, in this option various devices are connected directly to the Raspberry Pi 4. Depending on what type of display monitor we have, we can use an HDMI display, VGA monitor, DVI-D monitor, or TV. Notice that depending on the external USB devices used, you can use either the USB 2.0 or the USB 3.0 ports.

Figure 5.4 Raspberry Pi 4 setup - option 1

● 105

MIT App Inventer UK 200311.indd 105

03-04-20 10:37

MIT App Inventor Projects

5.3.2 Setup Option 2 In this option, shown in Figure 5.5, a powered hub is used to connect the USB devices.

Figure 5.5 Raspberry Pi 4 setup – option 2 5.4 Installing the Raspberry Pi Operating System 5.4.1 Raspbian Buster Installation Steps on Raspberry Pi 4 Raspbian Buster is the latest operating system of the Raspberry Pi 4. This section gives the steps for installing this operating system on a new blank SD card, ready to use with your Raspberry Pi 4. You will need a micro SD card with a capacity of at least 8GB (16 GB is even better) before installing the new operating system on it. The steps to install the Raspbian Buster are as follows: • 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

MIT App Inventer UK 200311.indd 106

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

Figure 5.6 Raspbian Buster download page • 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/

Figure 5.7 Download Etcher • Double click to Open Etcher, and click Select image. Select the Raspbian Buster file you just downloaded.

● 107

MIT App Inventer UK 200311.indd 107

03-04-20 10:37

MIT App Inventor Projects

• Click Select target and select the micro SD card • Click Flash (see Figure 5.8). This may take several minutes, wait until it is finished. The program will then validate and unmount the micro SD card. You can remove your micro SD card after it is unmounted.

Figure 5.8 Click Flash to flash the disk image • 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 adapter cable for mini HDMI to standard HDMI conversion), connect a USB keyboard, and power up the Raspberry Pi. • You will see the startup menu displayed on the monitor. Click Next to get started. • Select the Wi-Fi network and enter the password of your Wi-Fi router • Click on the Wi-Fi icon at the top right-hand side of the screen and note the Wireless 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

MIT App Inventer UK 200311.indd 108

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

Figure 5.9 Raspberry Pi 4 desktop 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 Android apps called Who's On My Wi-Fi – Network Scanner by Magdalm is used to show how the IP address of your Raspberry Pi can be displayed. Running this program will display the Raspberry Pi Wireless IP address under the heading Raspberry Pi Trading Ltd. In addition to the IP address, other parameters such as the MAC address, gateway address, IP mask, etc are all displayed by this program. 5.5 Remote Access It is much easier to access the Raspberry Pi remotely over the Internet, for example using a PC rather than connecting a keyboard, mouse, and display to it. Before being able to access the Raspberry Pi remotely, we have to enable the SSH and the VNC by entering the following command at a terminal session: pi$raspberrypi:~ $ sudo raspi-config Go to the configuration menu and select Interface Options. Go down to P2 SSH (see Figure 5.10) and enable SSH. Click to exit the menu.

● 109

MIT App Inventer UK 200311.indd 109

03-04-20 10:37

MIT App Inventor Projects

Figure 5.10 Enable SSH 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: pi$raspberrypi:~ $ sudo raspi-config Go to the configuration menu and select Interface Options. Go down to P3 VNC and enable VNC. Click 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. 5.6 Using Putty Putty is a communications program that is used to create a connection between your PC and the Raspberry Pi. This connection uses a secure protocol called SSH (Secure Shell). Putty doesn't need to be installed as it can just be stored in any folder of your choice and run from there. Putty can be downloaded from the following web site:

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

MIT App Inventer UK 200311.indd 110

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

Figure 5.11 Putty startup screen

Figure 5.12 Click Yes to accept You will be prompted to enter the username and password. Notice that the default username and password are:

username: password:

pi 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 although not graphical programs.

● 111

MIT App Inventer UK 200311.indd 111

03-04-20 10:37

MIT App Inventor Projects

5.6.1 Configuring the Putty By default, the Putty screen background is black with white foreground characters. In this book, we used a white background with black foreground characters, with the character size set to 12 points bold. The steps to configure the Putty with these settings are given below. Notice that in this example these settings are saved with the name RPI4 so that they can be recalled whenever the Putty is re-started: • Restart Putty • Select SSH and enter the Raspberry Pi IP address • Click Colours under Window • 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 5.7 Remote Access of the Desktop You can control your Raspberry Pi via Putty, and run programs on it from your Windows PC. This, however, will not work with graphical programs because Windows doesn't know how to represent the display. As a result of this, for example, we cannot run any graphical programs in the Desktop mode. We can get around this problem using some extra software. Two popular software packages used for this purpose are: VNC (Virtual Network Connection), and Xming. Here, we shall be learning how to use the VNC. Installing and Using VNC VNC consists of two parts: VNC Server and the VNC Viewer. VNC Server runs on the Raspberry Pi, and the VNC Viewer runs on the PC. VNC server is already installed on your Raspberry Pi. You can start the server by entering the following command in the command mode: pi$raspberrypi:~ $ vncserver :1

● 112

MIT App Inventer UK 200311.indd 112

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

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 TightVNC 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.

Figure 5.13 Start the TightVNC and enter the IP address Figure 5.14 shows the Raspberry Pi Desktop displayed on the PC screen.

Figure 5.14 Raspberry Pi Desktop on the PC screen

● 113

MIT App Inventer UK 200311.indd 113

03-04-20 10:37

MIT App Inventor Projects

5.8 Using the Python Programming Language Two versions of the Python language are distributed with the Raspberry Pi at the time of writing this book: Version 2 and 3. The actual version numbers can be displayed by entering the command python --version as shown in Figure 5.15. The display shows that the two versions are 2.7.16 and 3.7.3. The advantage of using Python 3 is that most of the new libraries are being developed for Python 3. Some of the Python 2.7 libraries are not compatible with Python 3.7. Python 3.7 has improved integer division, better Unicode support. Additionally, version 3.7 has better error handling and improved GUI support. In this book, we will be using Python 3 in all of the Raspberry Pi-based projects.

Figure 5.15 Displaying the Python versions 5.8.1 Method 1 – Interactively from Command Prompt In this method, we will log in to our Raspberry Pi 4 using the SSH and then create and run our program interactively. This method is excellent for small programs. The steps are as follows: • Login to the Raspberry Pi 4 using SSH • At the command prompt enter python3. You should see the Python command mode which is identified by three characters >>> • Type the program:

print ("Hello From Raspberry Pi 4")

• The required text will be displayed interactively on the screen as shown in Figure 5.16

Figure 5.16 Running a program interactively • Enter Cntrl+X to exit Python 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

MIT App Inventer UK 200311.indd 114

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

5.8.2 Method 2 – Create a Python File in Command Mode In this method, we will log in to our Raspberry Pi 4 using the SSH as before and then create a Python file. A Python file is simply a text file with the extension .py. We can use a text editor, e.g. the nano text editor to create our file. In this example, a file called hello.py is created using the nano text editor. Figure 5.17 shows the contents of file hello.py. This figure also shows how to run the file from the command line. Notice that the program is run by entering the command:

pi@raspberrypi:~ $ python3 hello.py

Figure 5.17 Running a Python file Some notes are given in this section on using the nano text editor. Using the nano Text Editor Start the nano text editor by entering the word nano, followed by the filename you wish to create or modify. An example is given below where a new file called first.txt is created:

pi@raspberrypi ~ $ nano first.txt

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+W: Search for a word Ctrl+V: Move to next page Ctrl+Y: Move to the previous page Ctrl+K: Cut the current row of txt Ctrl+R: Read file Ctrl+U: Paste the text you previously cut Ctrl+J: Justify Ctrl+\: Search and replace text

● 115

MIT App Inventer UK 200311.indd 115

03-04-20 10:37

MIT App Inventor Projects

Ctrl+C: Display the current column and row position Ctrl+G: Get detailed help on using the nano Ctrl+-:

Go to specified line and column position

Ctrl+O: Save (write out) the file currently open Ctrl+X: Exit nano

Figure 5.18 nano text editor screen Now, type the following text as shown in Figure 5.19: nano is a simple and yet powerful text editor. This simple text example demonstrates how to use nano. This is the last line of the example.

Figure 5.19 Sample text

● 116

MIT App Inventer UK 200311.indd 116

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

The use of nano is now demonstrated with the following steps: Step 1: Go the beginning of the file by moving the cursor. 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).

Figure 5.20 searching word simple 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.

Figure 5.21 Cutting the first line 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

MIT App Inventer UK 200311.indd 117

03-04-20 10:37

MIT App Inventor Projects

Figure 5.22 Paste the line cut previously 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).

Figure 5.23 Displaying row and column position of a word 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.

Figure 5.24 Displaying the help page

● 118

MIT App Inventer UK 200311.indd 118

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

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.

Figure 5.25 Replacing text 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. Step 9: Display the contents of the file: pi@raspberrypi ~ $ cat first.txt This simple text file demonstrates how to use nano. Nano is a simple and yet powerful text editor This is the last line of the example. 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: • Connect to your Raspberry Pi using the VNC Viewer • Click to open the Applications menu on Desktop • Click Programming and then click Thonny Python IDE (see Figure 5.26)

● 119

MIT App Inventer UK 200311.indd 119

03-04-20 10:37

MIT App Inventor Projects

Figure 5.26 Select Python programming environment • Type in your program as shown in Figure 5.27 and save it e.g. with the name hello2

Figure 5.27 Type in your program • 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.

Figure 5.28 Run the program 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

MIT App Inventer UK 200311.indd 120

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

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, select, 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. 5.9 Which Method? The choice of a method depends upon the size and complexity of a program. Small programs or small code to test an idea can be run interactively without creating a program file. Larger programs can be created as Python files and then they can run either in the command mode or in the GUI mode. Using Thonny has the advantage that the program takes care of the correct indentation of Python programs. Additionally, Thonny offers a debug utility which can be extremely useful during program development and testing. 5.10 Accessing Raspberry Pi 4 Hardware and Peripheral Devices from Python All versions of Raspberry Pi hardware include a connector for connecting external devices, such as sensors, LEDs, actuators, etc. In this section, we will look at how external devices connected to Raspberry Pi can be accessed from Python. There are many project-based books on using Python to access peripheral devices connected 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: • Raspberry Pi 3 Basic to Advanced Projects (Elektor publication) • Motor Control Projects with Arduino and Raspberry Pi (Elektor publication) • Camera Projects Book: 39 Experiments with Raspberry Pi and Arduino (Elektor publication) • Hardware Projects for Raspberry Pi (Elektor publication) • Raspberry Pi Advanced Programming (Elektor publication) Before going into the details of the hardware interface, it is worthwhile to look at the Raspberry Pi 4 GPIO connector. This is a 40-pin dual-in-line 2.54mm wide connector as shown in Figure 5.29.

● 121

MIT App Inventer UK 200311.indd 121

03-04-20 10:37

MIT App Inventor Projects

Figure 5.29 Raspberry Pi GPIO connector 5.10.1 GPIO – Parallel Interface When the GPIO connector is at the far side of the board, the pins at the bottom, starting from the left of the connector are numbered as 1, 3, 5, 7, and so on, while the ones at the top are numbered as 2, 4, 6, 8 and so on. The GPIO provides 26 general purpose bi-directional I/O pins. Some of the pins have multiple 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 respectively. 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

MIT App Inventer UK 200311.indd 122

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

5.10.2 The GPIO Library The GPIO library is called RPi.GPIO and it should already be installed on your Raspberry Pi 4. This library must be included at the beginning of your Python programs if you will be using the GPIO functions. The statement to include this library is:

import RPi.GPIO as GPIO

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):

pi@raspberrypi: ~ $ sudo apt-get update pi@raspberrypi: ~$ sudo apt-get install python-dev pi@raspberrypi: ~$ sudo apt-get install python-rpi.gpio

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 numbering, 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. Channel (I/O port 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

MIT App Inventer UK 200311.indd 123

03-04-20 10:37

MIT App Inventor Projects

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:

GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

For pull-up:

GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_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: To wait for a rising edge:

GPIO.wait_for_edge(channel, GPIO.RISING)

To wait for a falling edge:

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. For example, to add rising event detection to an input pin:

GPIO.add_event_detect(channel, GPIO.RISING)

● 124

MIT App Inventer UK 200311.indd 124

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

We can check whether or not the event occurred by the following statement: If GPIO.event_detected(channel): …………………………… …………………………… Event detection can be removed by the following statement: GPIO.remove_event_detect(channel) We can also use interrupt facilities (or callbacks) to detect events. Here, the event is handled 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 handling code is the function named MyHandler: GPIO.add_event_detect(channel, GPIO.RISING, callback=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

MIT App Inventer UK 200311.indd 125

03-04-20 10:37

MIT App Inventor Projects

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@

GPIO.add_event_callback(channel, MyHandler, bouncetime=10)

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):

GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH)

To send data to an output port pin we can use the following statement:

GPIO.output(channel, value)

Where value can be 0 (or GPIO.LOW, or False), or 1 (or GPIO.HIGH, or True) 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() 5.11 Example Project Accessing the External World A simple example project is given in this section which shows how an LED connected to one of the Raspberry Pi GPIO ports can be flashed every second. This project aims to show how an LED can be connected to a GPIO port and how the GPIO library can be used to control this LED. 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 general, 3mA should give enough visible light for small LEDs. Because the output voltage of

● 126

MIT App Inventer UK 200311.indd 126

03-04-20 10:37

Chapter 5 • Raspberry Pi 4 – specifications – setup – installing the operating system

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.

Figure 5.30 LED connected to pin GPIO 2 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 configured 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

MIT App Inventer UK 200311.indd 127

03-04-20 10:37

MIT App Inventor Projects

GPIO.setmode(GPIO.BCM)

# set BCM pin numbering

GPIO.setup(2, GPIO.OUT)

# configure GPIO 2 as output

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.31 LED.py Program listing 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).

Figure 5.32 Circuit built on a breadboard 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 chapter 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

MIT App Inventer UK 200311.indd 128

03-04-20 10:37

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

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: • Title of the project • Description • Background information (if necessary) • Block diagram • Circuit diagram • App Inventor application • Python 3 program • Suggestions for future work (if necessary) 6.2 Project 1 – Controlling an LED from Android Mobile Phone 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. Block Diagram: Figure 6.1 shows the project block diagram.

Figure 6.1 Project block diagram 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

MIT App Inventer UK 200311.indd 129

03-04-20 10:37

MIT App Inventor Projects

The steps are as follows (see Figure 6.2). Full details of the component configurations will be given in this project: • Create a new project and name it as LED • Click Screen1 and change its Title to BLUETOOTH • Insert a HorizontalArrangement with the following configuration: AlignHorizontal: Center: 3 AlignVertical: Center: 2 BackgroundColor: Orange Height: 10 percent Width: Fill parent Image: none Visible: ticked • Insert a Label onto the HorizontalArrangement. This label is the heading of the project. Configure the Label as follows: Name: Label1 FontBold: ticked FontSize: 25 Height: Automatic Width: Automatic Text: LED CONTROLLER TextColor: Blue • Insert a HorizontalArrangement with the following configuration: AlignHorizontal: Center: 3 AlignVertical: Center: 2 BackgroundColor: Yellow Height: 10 percent Width: Fill parent Image: none Visible: ticked • Insert two buttons on this HorizontalArrangement. These buttons will be used to turn the LED ON and OFF when clicked. Configure the buttons as follows: First Button: Name: ButtonON BackgroundColor: Default FontBold: ticked

● 130

MIT App Inventer UK 200311.indd 130

03-04-20 10:37

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

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 • Insert a VerticalArrangement with the following configuration: 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 connection status as Connected or Disconnected: Name: LblStatus FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Text: Status TextColor: None

● 131

MIT App Inventer UK 200311.indd 131

03-04-20 10:37

MIT App Inventor Projects

• 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 Bluetooth connection then the button text colour will change to red, and number 49 (character

● 132

MIT App Inventer UK 200311.indd 132

03-04-20 10:37

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

"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. The steps are as follows: • Click ListPicker1 and select when ListPicker1.BeforePicking do • Click ListPicker1 and select set ListPicker1.Elements to • Click BluetoothClient1 and select BluetoothClient1.AddressesandNames. Bluetooth names and addresses reachable by the Android device will be displayed on the screen for you to select the Raspberry Pi • Click ListPicker1 and select when ListPicker1.AfterPicking do • Click Control under Built-in and insert an if-then block • Click BluetoothClient1 and select call BluetoothClient1.Connect address • Click ListPicker1 and select ListPicker1.Selection. • Click ListPicker1 and select set ListPicker1.Selection to • Click Bluetooth1.Client1 and select BluetoothClient1.AddressesandNames. At this point, the Bluetooth name and address selected by the user are used to make a connection to the Raspberry Pi • We now insert a Clock block so that the Bluetooth connection is checked periodically. 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 activated. 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 corresponds to ASCII character "1"

● 133

MIT App Inventer UK 200311.indd 133

03-04-20 10:37

MIT App Inventor Projects

• When the user clicks button LED OFF, block when ButtonOFF.Click do is activated. 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 corresponds to ASCII character "0"

Figure 6.3 Block program of the project Build the program. The QR code of the program is shown in Figure 6.4.

Figure 6.4 QR code of the program

● 134

MIT App Inventer UK 200311.indd 134

03-04-20 10:37

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

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:

pi@raspberrypi:~ $ sudo apt-get install bluetooth libbluetooth-dev pi@raspberrypi:~ $ sudo python3 -m pip install pybluez

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: sudo nano /etc/systemd/system/dbus-org.bluez.service • Add –C at the end of the ExecStart= line. Also add another line after the ExecStart line. The final two lines should look like: ExecStart=/usr/lib/bluetooth/bluetoothd -C ExecStartPost=/usr/bin/sdptool add SP • Exit and save the file by entering Ctrl+X followed by Y • Reboot your Raspberry Pi: pi@raspberrypi:~ $ sudo reboot 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:

pi@raspberrypi:~ $ hciconfig | grep "BD Address"

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 equivalent ASCII characters (utf-8 is the default encoding and decoding parameter in Python 3):

● 135

MIT App Inventer UK 200311.indd 135

03-04-20 10:37

MIT App Inventor Projects

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': GPIO.output(LED, 0)

# 0 received # LED OFF

except KeyboardInterrupt: # Keyboard interrupt client.close()

# Close

s.close() #--------------------------------------------------------------# #

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

MIT App Inventer UK 200311.indd 136

03-04-20 10:37

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

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: while True:

# Do forever

data = client.recv(1024)

# Receive data

if data.decode('utf-8') == "1":

# 1 received

GPIO.output(LED, 1) elif data.decode('utf-8') == '0': GPIO.output(LED, 0)

# LED ON # 0 received # LED OFF

except KeyboardInterrupt: client.close()

# Close

s.close()

Figure 6.5 Python program (blut.py) of the project The steps to test the project are as follows: • Make sure that Bluetooth is enabled on your Android mobile phone • 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 password, enter 1234 • Run your program either inside Thonny or from the command line as: pi@raspberrypi:~ $ python3 blut.py • 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

MIT App Inventer UK 200311.indd 137

03-04-20 10:37

MIT App Inventor Projects

Figure 6.6 List of reachable Bluetooth devices • You should now see the Connected message as in Figure 6.7.

Figure 6.7 Connected message • 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. 6.3 Project 2 – Sound Output while Controlling an LED 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 TextToSpeech component of App Inventor: Select Raspberry Pi Bluetooth name and address – Sounded when Connect is clicked

LED turned ON – Sounded when LED ON button is clicked LED turned OFF – Sounded when LED OFF button is clicked

● 138

MIT App Inventer UK 200311.indd 138

03-04-20 10:37

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

The Python program remains the same, but the following modifications are required to App Inventor: Modifications in Designer: • The new program is named LED_SOUND • Click the Media tab and insert component TextToSpeech onto the Viewer. This is a hidden component Modifications in Blocks (see Figure 6.8): • Click TextToSpeech1 and select call TextToSpeech1.Speak message. Join this block to when ListPicker1.BeforePicking do as shown in the Figure • 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 Connect is clicked • Click TextToSpeech1 and select call TextToSpeech1.Speak message. Join this block to when ButtonON.Click do as shown in the Figure • Set the text to LED turned ON • Click TextToSpeech1 and select call TextToSpeech1.Speak message. Join this block to when ButtonOFF.Click do as shown in the Figure • Set the text to LED turned OFF

● 139

MIT App Inventer UK 200311.indd 139

03-04-20 10:37

MIT App Inventor Projects

Figure 6.8 Block program of the project 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.

Figure 6.9 QR code of the project 6.4 Project 3 – Controlling an LED with Speech Commands Description: This project is similar to Project 1, but here the LED is controlled by speech commands, spoken to the Android mobile phone.

● 140

MIT App Inventer UK 200311.indd 140

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

The following are the valid speech commands:

LED ON LED OFF

The Python program remains the same, but both the Designer and Blocks parts of App Inventor program require changes. The steps are as follows (see Figure 6.10): • Create a new program and name it as LED_SPEECH • Change the name of the title to LED CONTROL WITH SPEECH • Insert a Button on a HorizontalArrangement with the following specifications. Clicking this button will start the speech recognizer on the Android mobile phone so that commands can be spoken: Name: ButtonStart BackgroundColor: Default FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Image: none Text: Start TextColor: White • Insert a VerticalArrangement as in the previous project. 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 connection status as Connected or Disconnected: 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

MIT App Inventer UK 200311.indd 141

03-04-20 10:38

MIT App Inventor Projects

Name: ListPicker1 BackgroundColor: default FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Image: None ItemBackgroundColor: Default ItemTextColor: Default Text: Connect TextColor: White • Insert a Label on the VerticalArrangement with the following settings. This label will display the speech commands given by the user: 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 Viewer. This component will recognize the spoken commands.

● 142

MIT App Inventer UK 200311.indd 142

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

Figure 6.10 Design of the project 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 recognizer so that the spoken commands can be received • Click SpeechRecognizer1 and select call SpeechRecognizer1.GetText. This block will receive the text of the spoken command • Click SpeechRecognizer1 and select when Speechrecognizer1.AfterGettingText do. This block will be activated automatically when the spoken command is terminated. First of all, we check to make sure that the Bluetooth connection has already been established • Variable result on Speechrecognizer1 block stores the spoken message in text form. If this message is equal to LED on (notice that although we speak LED ON, this is converted into LED on in text form) then we send number 49 (character "1") to Raspberry Pi to request the LED to be turned ON. • 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

MIT App Inventer UK 200311.indd 143

03-04-20 10:38

MIT App Inventor Projects

Figure 6.11 Block program of the project Figure 6.12 shows the QR code of the project. The steps to test the project are as follows: • Make sure that Bluetooth is enabled on your Android mobile phone • 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 password, enter 1234 • Run your program either inside Thonny or from the command line as: pi@raspberrypi:~ $ python3 blut.py • 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

MIT App Inventer UK 200311.indd 144

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

Figure 6.12 QR code of the project 6.5 Project 4 – Controlling Multiple LEDs 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) Button Clicked Command sent to Raspberry Pi LED1 ON 11 LED1 OFF 10 LED2 ON 21 LED2 OFF 20 LED3 ON 31 LED3 OFF 30 LED4 ON 41 LED4 OFF 40 Block Diagram: Figure 6.13 shows the block diagram of the project.

Figure 6.13 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: LED LED1 LED2 LED3 LED4

GPIO port GPIO 2 GPIO 3 GPIO 4 GPIO 17

● 145

MIT App Inventer UK 200311.indd 145

03-04-20 10:38

MIT App Inventor Projects

Figure 6.14 Circuit diagram of the project App Inventor Application: Figure 6.15 shows the design of the project. Clicking the Connect 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. The steps are as follows: • Create a new project called MULTIPLE_LED • Insert a HorizontalArrangement and insert a Label with its Text set to 4 LED CONTROLLER • Insert a VerticalArrangement as before and insert a ListPicker on it with its Text set to Connect. Also, insert a Label named LblStatus which should be set to be not visible. • Insert a TableArrangement and then insert 8 buttons on it. The configuration of one of the buttons is given below (other buttons have similar configurations, but different names and Text fields): Name: LED1ON BackgroundColor: Blue FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Image: none Shape: oval Text: LED1 ON TextColor: White

● 146

MIT App Inventer UK 200311.indd 146

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

• 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. • Insert a BluetoothClient component and a Clock component as in the previous projects

Figure 6.15 Design of the project 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 procedure. 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. • Insert a block to check if the Bluetooth connection is valid • 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

MIT App Inventer UK 200311.indd 147

03-04-20 10:38

MIT App Inventor Projects

• Click BluetoothClient1 and select call BluetoothClient1.SentText and set the text to "11" so that the string "11" will be sent to Raspberry Pi to turn ON LED1 • 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")

Figure 6.16a Block program of the project

● 148

MIT App Inventer UK 200311.indd 148

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

Figure 6.16b cont… The QR code of the project is shown in Figure 6.17.

Figure 6.17 QR code of the project Python Program: The Python program (blut4.py) for the Raspberry Pi is shown in Figure 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

MIT App Inventer UK 200311.indd 149

03-04-20 10:38

MIT App Inventor Projects

# # 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: while True:

# Do forever

data = client.recv(1024)

# Receive data

if data.decode('utf-8') == "11":

# 11 received

GPIO.output(LED1, 1) elif data.decode('utf-8') == "10": GPIO.output(LED1, 0) elif data.decode('utf-8') == "21":

# LED1 ON # 10 received # LED1 OFF # 21 received

● 150

MIT App Inventer UK 200311.indd 150

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

GPIO.output(LED2, 1) elif data.decode('utf-8') == "20": GPIO.output(LED2, 0) elif data.decode('utf-8') == "31": GPIO.output(LED3, 1) elif data.decode('utf-8') == "30": GPIO.output(LED3, 0) elif data.decode('utf-8') == "41": GPIO.output(LED4, 1) elif data.decode('utf-8') == "40": GPIO.output(LED4, 0)

# LED2 ON # 20 received # LED2 OFF # 31 received # LED3 ON # 30 received # LED3 OFF # 41 received # LED4 ON # 40 received # LED4 OFF

except KeyboardInterrupt: client.close()

# Close

s.close()

Figure 6.18 Python program (blut4.py) of the project The steps to test the program are: • Make sure that Bluetooth is enabled on your Android mobile phone • 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 password, enter 1234 • Run your program either inside Thonny or from the command line as: pi@raspberrypi:~ $ python3 blut4.py • 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

MIT App Inventer UK 200311.indd 151

03-04-20 10:38

MIT App Inventor Projects

Figure 6.19 Turning LED2 ON 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. 6.6 Project 5 – Controlling Multiple LEDs – Adding Sound Output 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: • Create a new project and name it as LED4_SOUND • Click Media and insert a TextToSpeech component on the Viewer 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

MIT App Inventer UK 200311.indd 152

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

Figure 6.20a Modified blocks

● 153

MIT App Inventer UK 200311.indd 153

03-04-20 10:38

MIT App Inventor Projects

Figure 6.20b cont… 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.

Figure 6.21 QR code of the project

● 154

MIT App Inventer UK 200311.indd 154

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

Figure 6.22 shows the circuit built on a breadboard and connections made to Raspberry Pi using jumper wires.

Figure 6.22 Circuit built on a breadboard 6.7 Project 6 – DC Motor Speed Control Description: In this project, a small DC motor is connected to one of the Raspberry Pi GPIO ports through a transistor driver circuit. The speed of the motor is controlled from an Android mobile phone using a slider component. 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

MIT App Inventer UK 200311.indd 155

03-04-20 10:38

MIT App Inventor Projects

Figure 6.23 PWM waveforms 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 Bluetooth 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.

Figure 6.24 Block diagram of the project Circuit Diagram: The circuit diagram of the project is shown in Figure 6.25. An NPN transistor switch is used to drive the DC motor since the output current of the Raspberry Pi is not enough to drive a motor.

Figure 6.25 Circuit diagram of the project

● 156

MIT App Inventer UK 200311.indd 156

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

App Inventor Application: In this project, we will use a slider component on our Android mobile phone to change the required duty cycle. The steps are as follows (see Figure 6.26): • Create a new project and name it as Motor • Insert a HorizontalArrangement, insert a Label on it and set the title to MOTOR CONTROLLER • Insert another HorizontalArrangement. Click the User Interface tab and insert 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 • Insert a VerticalArrangement, a LblStatus, and a ListPicker as in the previous projects • Insert a BluetoothClient component and a Clock component as in the previous projects

Figure 6.26 Design of the project

● 157

MIT App Inventer UK 200311.indd 157

03-04-20 10:38

MIT App Inventor Projects

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 BluetoothClient1 and select BluetoothClient1.SendText and insert block get thumbPosition to this block as shown in the figure. At this point, the slider position will be sent to Raspberry Pi over the Bluetooth connection as a string having a value "0" to "100". • Click LblDuty and select set LblDuty.Text to. Set its text to display the slider position, followed by symbol %.

Figure 6.27 Block program of the project The QR code of the project is shown in Figure 6.28.

Figure 6.28 QR code of the project 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 program. 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

MIT App Inventer UK 200311.indd 158

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

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

pwm = GPIO.PWM(MOTOR, 100)

# PWM with f=100Hz

pwm.start(DC) # # 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

MIT App Inventer UK 200311.indd 159

03-04-20 10:38

MIT App Inventor Projects

# # The duty cycle is between 0 and 100 # try: while True:

# Do forever

data = client.recv(1024) # Receive data DCSTR = data.decode('utf-8') # Get Duty Cycle DC = int(DCSTR) # Convert to integer pwm.ChangeDutyCycle(DC) # Change Duty Cycle except KeyboardInterrupt: client.close() # Close s.close()

Figure 6.29 Python program (motor.py) of the project The steps to test the program are as follows: • 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 connection 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.

Figure 6.30 Snapshot of a sample run 6.8 Project 7 – Sending Temperature and Humidity to Android Device Description: In this project, a temperature and humidity sensor module is connected to a Raspberry Pi. The Raspberry Pi sends the ambient temperature and humidity measurements every 10 seconds to the Android mobile phone where they are displayed on the screen

● 160

MIT App Inventer UK 200311.indd 160

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

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

Figure 6.31 DHT11 temperature and humidity sensor Block Diagram: Figure 6.32 shows the block diagram of the project.

Figure 6.32 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.

Figure 6.33 Circuit diagram of the project

● 161

MIT App Inventer UK 200311.indd 161

03-04-20 10:38

MIT App Inventor Projects

App Inventor Application: The steps are as follows (see Figure 6.34). • Create a new project and name it as DHT11 • Click Screen1 and change its Title to BLUETOOTH • Insert a HorizontalArrangement with the following configuration: AlignHorizontal: Center: 3 AlignVertical: Center: 2 BackgroundColor: Orange Height: 10 percent Width: Fill parent Image: none Visible: ticked • Insert a Label onto the HorizontalArrangement. This label is the heading of the project. Configure the Label as follows: Name: Label1 FontBold: ticked FontSize: 25 Height: Automatic Width: Automatic Text: TEMPERATURE & HUMIDITY TextColor: Blue • Insert a VerticalArrangement with the following configuration: 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

MIT App Inventer UK 200311.indd 162

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

Height: Automatic Width: Automatic Text: Status TextColor: None • Insert a Button on the VerticalArrangement. This button will be used to disconnect the Bluetooth link. Configure the button as follows: Name: ButtonDisconnect FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Image: None Shape: rounded Text: Disconnect TextColor: Red • Insert a ListPicker on the VerticalArrangement. 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 • Insert a HorizontalArrangement with the following configuration: AlignHorizontal: Center: 3 AlignVertical: Center: 2 BackgroundColor: Yellow Height: 10 percent Width: Fill parent Image: none

● 163

MIT App Inventer UK 200311.indd 163

03-04-20 10:38

MIT App Inventor Projects

• Insert a Label on the HorizotalArrangement with the following configuration: Name: Label2 BackgroundColor: None FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Text: Temperature (C): TextColor: Red • Insert a TextBox on the HorizontalArrangement with the following configuration. This TextBox will display the temperature: Name: TxtTemperature BackgroundColor: default FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: 20 percent Hint: blank TextColor: default • Insert a HorzontalArrangement with the BackgroundColor set to Blue • Insert a Label on this HorizontalArrangement with the following configuration: Name: Label3 BackgroundColor: None FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Text: Humidity (%): TextColor: White • Insert a TextBox on the HorizontalArrangement with the following configuration. This TextBox will display the humidity: Name: TxtHumidity BackgroundColor: default FontBold: ticked

● 164

MIT App Inventer UK 200311.indd 164

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

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.34 Design of the project 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 • Click ButtonDisconnect and select when ButtonDisconnect.Click do. This block will be activated when the user clicks to disconnect the Bluetooth link. • Click BluetoothClient1 and select call BluetoothClient1.Disconnect. Join the two blocks as shown in the Figure.

● 165

MIT App Inventer UK 200311.indd 165

03-04-20 10:38

MIT App Inventor Projects

• Click THclock and select when THClock.Timer do. This block will be called periodically 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 • Set variable TH to call BluetoothClient1.ReceiveText and set the numberOf Bytes to 5. This is because Raspberry Pi will send the temperature and humidity as 2 bytes each, separated with a comma (i.e. 5 bytes in total). e.g. 19,65 where the temperature is 19ºC and the humidity is 65%

• 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 extract 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

Figure 6.35 Block program of the project

● 166

MIT App Inventer UK 200311.indd 166

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

The QR code of the project is shown in Figure 6.36.

Figure 6.36 QR code of the project

Python Program: Before writing the Python program we have to install the Adafruit DHT11 library to our Raspberry Pi. Enter the following command: pi@raspberrypi:~ $ sudo pip3 install Adafruit_DHT 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

MIT App Inventer UK 200311.indd 167

03-04-20 10:38

MIT App Inventor Projects

import RPi.GPIO as GPIO # import GPIO library import Adafruit_DHT # import DHT11 library GPIO.setwarnings(False) # disable warnings GPIO.setmode(GPIO.BCM) # set BCM pin numbering sensor = Adafruit_DHT.DHT11 pin = 2 # # 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: while True: # Do forever humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) temp = int(temperature) if temp < 10: # If less than 10 datat = "0" + str(temp) # Add 0 else: datat = str(temp) datah = str(int(humidity)) # Humidity as string datat=datat+","+datah # Combine temp and hum datas = datat.encode('utf-8') # Encode the data client.send(datas) # Send the data time.sleep(5) # Waut 5 seconds except KeyboardInterrupt: client.close() # Close s.close()

Figure 6.37 Python program (dht11.py) of the project 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 humidity readings should then be displayed on the Android mobile phone as shown in Figure 6.38.

● 168

MIT App Inventer UK 200311.indd 168

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

Figure 6.38 Displaying temperature and humidity on Android mobile phone 6.9 Project 8 – Password Protection 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): For the first screen: • Create a new project and name it as Password • Insert a TableArrangement and configure it as follows: Columns: 3 Height: 20 percent Width: Fill parent Rows: 2 • Insert a Label and set its Text to Username: • Insert a TextBox and configure it as follows:

● 169

MIT App Inventer UK 200311.indd 169

03-04-20 10:38

MIT App Inventor Projects

Name: TxtUsername BackgroundColor: default FontBold: ticked FontSize: 20 Height: Automatic Width: Automatic Hint: blank TextColor: Default • Insert a Label and set its Text to Password: Name: TxtPassword BackgroundColor: default FontBold: ticked FontSize: 20 Height: Automatic Width: Automatic Hint: blank TextColor: Default • Insert a HorizontalArrangement and then insert a Button on it with the following configuration: Name: ButtonLogin BackgroundColor: Blue FontBold: ticked FontSize: 20 Height: Automatic Width: Automatic Text: Login TextColor: White • Insert a Label under the HorizontalArrangement with the following configuration. This label will display the login status. This label is not visible when the application starts: Name: LblStatus BackgroundColor: None FontBold: ticked FontSize: 20 Height: Automatic Width: Automatic Text: test TextColor: Default Visible: not ticked

● 170

MIT App Inventer UK 200311.indd 170

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

Figure 6.39 Design of Screen1 For the second screen: • Click Add Screen and give the second screen the name LED • You should see a blank new screen. • Insert a HorizontalArrangement and insert a Label on it with the Title This is the second screen… as shown in Figure 6.40

Figure 6.40 Design of second screen • 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 password. 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 password • Set the LblStatus to be visible • Insert an if-then block and extend it to if-then-else. • If TxtUsername.Text is not equal to the correct username or TxtPassword. Text is not equal to the correct password, then display message Invalid username and password on LblStatus. Clear both TextBoxes for the next attempt.

● 171

MIT App Inventer UK 200311.indd 171

03-04-20 10:38

MIT App Inventor Projects

• If the correct username and password are entered, then display the message Successful login… and then click Control under Built-in and select open another screen screenName and set it to string LED so that the second screen will be displayed when the correct username and password are entered.

Figure 6.41 Block program of the project The QR code of the project is shown in Figure 6.42.

Figure 6.42 QR code of the project An example run of the project is shown in Figure 6.43

Figure 6.43 Example run of the project Notice that you could have used a PasswordTextBox instead of an ordinary TextBox to hide the password entered by the user.

● 172

MIT App Inventer UK 200311.indd 172

03-04-20 10:38

Chapter 6• Raspberry Pi Bluetooth based projects using the MIT App Inventor

6.10 Summary In this chapter, we developed several hardware projects using the Bluetooth link to establish 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

MIT App Inventer UK 200311.indd 173

03-04-20 10:38

MIT App Inventor Projects

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor 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. 7.2 Project 1 – Getting and Displaying the Local Wi-Fi Parameters 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): • Create a new project and name it as WIFI_TEST • Insert a VerticalArrangement with the following configuration: 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

MIT App Inventer UK 200311.indd 174

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

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

MIT App Inventer UK 200311.indd 175

03-04-20 10:38

MIT App Inventor Projects

Figure 7.1 Design of the project 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 • Click ButtonConnect and select when ButtonConnect.Click do. This block will be executed when button Connect is clicked • Click on TaifunWiFi1 and select call TaifunWiFi1.ConnectSSID and join blocks ssid and password to this block as shown in the figure. This block will establish a connection to the local Wi-Fi router • 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 • Clicking Button Disconnect disconnects from the Wi-Fi

● 176

MIT App Inventer UK 200311.indd 176

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

Figure 7.2 Block program of the project 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.

Figure 7.3 QR code of the project

Figure 7.4 Example run of the project on Android mobile phone 7.3 Project 2 – Web Server to Control an LED 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. Block Diagram: The block diagram of the project is as in Figure 6.1.

● 177

MIT App Inventer UK 200311.indd 177

03-04-20 10:38

MIT App Inventor Projects

Circuit Diagram: The circuit diagram of the project is as in Figure 5.30 App Inventor Application: This project uses the component Web to communicate with the Raspberry Pi over a web server interface. The steps are (see Figure 7.5): • Create a new project and name it as WEB_LED • Insert a HorizontalArrangement and insert a Label on it with its Text set to LED CONTROLLER • Insert another HorizontalArrangement • Insert two buttons on the HorizontalArrangement with the names ButtonON and ButtonOFF, with their texts set to LED ON and LED OFF respectively • Click the Connectivity tab and insert a Web component on the Viewer. This is a hidden component.

Figure 7.5 Design of the project

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 Raspberry Pi • Click ButtonON and select when ButtonON.Click do. This block will be executed when button LED ON is clicked. • Click on Web1 and select set Web1.Url to. • 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

MIT App Inventer UK 200311.indd 178

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

• 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

Figure 7.6 Block program of the project The QR code of the project is shown in Figure 7.7.

Figure 7.7 QR code of the project

Python Program: Python program is based on Flask which is a simple micro-framework written in Python for Python. It is free of charge and can be used to create a web server on Raspberry Pi to control GPIO ports over the Internet. The nice thing about Flask is that it does not require special tools or libraries, and has no database or any other third party libraries. 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:

pi@raspberrypi:~ $ sudo apt-get install python-flask

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 parameters 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

MIT App Inventer UK 200311.indd 179

03-04-20 10:38

MIT App Inventor Projects

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 #-----------------------------------------------------------from flask import Flask,render_template import RPi.GPIO as GPIO 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("//") 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')

Figure 7.8 Python program (webled.py) of the project To test the project, start Python program on your Raspberry Pi either through Thonny or from the command line as:

pi@raspberrypi:~ $ sudo python3 webled.py

● 180

MIT App Inventer UK 200311.indd 180

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

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.

Figure 7.9 Flask startup statements

Figure 7.10 Statements displayed on the Raspberry Pi PC screen 7.4 Project 3 – Web Server to Control Multiple Relays 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 remove this jumper and connect an external power supply (e.g. +5V) to pin JD-VCC.

● 181

MIT App Inventer UK 200311.indd 181

03-04-20 10:38

MIT App Inventor Projects

Figure 7.11 4-channel relay board Block Diagram: Figure 7.12 shows the block diagram of the project.

Figure 7.12 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

MIT App Inventer UK 200311.indd 182

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

Figure 7.13 Circuit diagram of the project 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): • Create a new project and name it as Relay • Insert a HorizontalArrangement and insert a Label on it with its Text set to RELAY CONTROLLER • Insert a TableArrangement with 4 columns and 4 rows, Height set to 40 percent, and Width set to Fill parent.

• Insert 8 Buttons on the TableArrangement with the following configuration: Button Name

BackgroundColor

FontBold

FontSize

Text

TextColor

Relay1ON

Yellow

ticked

20

RELAY1 ON

Default

Relay1OFF

Yellow

ticked

20

RELAY1 OFF

Default

Relay2ON

Yellow

ticked

20

RELAY2 ON

Default

Relay2OFF

Yellow

ticked

20

RELAY2 OFF

Default

Relay3ON

Yellow

ticked

20

RELAY3 ON

Default

Relay3OFF

Yellow

ticked

20

RELAY3 OFF

Default

Relay4ON

Yellow

ticked

20

RELAY4 ON

Default

Relay4OFF

Yellow

ticked

20

RELAY4 OFF

Default



• Click tab Connectivity and insert the hidden Web component on the Viewer.

● 183

MIT App Inventer UK 200311.indd 183

03-04-20 10:38

MIT App Inventor Projects

Figure 7.14 Design of the project 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: To To To To To To To To

turn turn turn turn turn turn turn turn

ON channel 1 OFF channel 1 ON channel 2 OFF channel 2 ON channel 3 OFF channel 3 ON channel 4 OFF channel 4

htttp:/192.168.1.202/RELAY/on1 htttp:/192.168.1.202/RELAY/off1 htttp:/192.168.1.202/RELAY/on2 htttp:/192.168.1.202/RELAY/off2 htttp:/192.168.1.202/RELAY/on3 htttp:/192.168.1.202/RELAY/off3 htttp:/192.168.1.202/RELAY/on4 htttp:/192.168.1.202/RELAY/off4

The steps are: • Initialize a variable called RaspberryPi and enter the IP address of your Raspberry 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 activated 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

MIT App Inventer UK 200311.indd 184

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

• 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.

Figure 7.15a Block program of the project

● 185

MIT App Inventer UK 200311.indd 185

03-04-20 10:38

MIT App Inventor Projects

Figure 7.15b cont… The QR code of the project is shown in Figure 7.16.

Figure 7.16 QR code of the project Python Program: The Python program (relay4.py) is shown in Figure 7.17. At the beginning 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 deactivated if a logic 1 is sent). The commands received from the Android mobile phone are then checked and the relays are controlled as follows: RELAY1 on1 off1

activate channel 1 of the relay deactivate channel 1 of the relay

RELAY2 on2 off2

activate channel 2 of the relay deactivate channel 2 of the relay

RELAY3 on3 off3

activate channel 3 of the relay deactivate channel 3 of the relay

RELAY4 on4 off4

activate channel 4 of the relay deactivate channel 4 of the relay

● 186

MIT App Inventer UK 200311.indd 186

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

A relay channel is activated by the statement: GPIO.output(actuator, GPIO.LOW), where the actuator is the selected relay. Similarly, a relay channel is deactivated by the statement: GPIO.output(actuator, GPIO.HIGH) #------------------------------------------------------------#

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 #-----------------------------------------------------------from flask import Flask,render_template import RPi.GPIO as GPIO 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

MIT App Inventer UK 200311.indd 187

03-04-20 10:38

MIT App Inventor Projects

@app.route("//") 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')

Figure 7.17 Python program (relay4.py) of the project To test the project, start the Python program either from Thonny or from the command line as follows:

pi@raspberry:~ $ sudo python3 relay4.py

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

MIT App Inventer UK 200311.indd 188

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

Figure 7.18 Example run on the Android mobile phone

Figure 7.19 Circuit built using jumper wires 7.5 Project 4 – S  ending Ambient Temperature and Humidity to Android Mobile Phone Description: In this project, a temperature and humidity sensor module is connected to Raspberry Pi. A webserver approach is used to send the ambient temperature and humidity readings to the Android mobile phone. Clicking a button on the Android mobile phone sends the temperature and humidity readings where they are displayed on the screen. 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. The steps are (see Figure 7.20) as follows: • Create a new project and name it as DHT11web • Insert a HorizontalArrangement and insert a Label with its Text set to TEMPERATURE & HUMIDITY

● 189

MIT App Inventer UK 200311.indd 189

03-04-20 10:38

MIT App Inventor Projects

• Insert a HorizontalArrangement and insert a Label and a TextBox on it. Set the Text of the Label to Temperature (C):. Set the name of the TextBox to TxtTemperature. This TextBox will display the ambient temperature • Insert a HorizontalArrangement and insert a Label and a TextBox on it. Set the Text of the Label to Humidity (%):. Set the name of the TextBox to TxtHumidity. This TextBox will display the ambient humidity • Insert a HorizontalArrangement and insert a Button on it. Set the name of the Button to ButtonClick and its Text to Get T, H. Clicking this button will request the temperature and humidity readings from the Raspberry Pi and display them in the TextBoxes. • Click tab Connectivity and insert a Web component on the Viewer

Figure 7.20 Design of the project Figure 7.21 shows the block program of the project. The steps are: • Initialize a variable called TH to empty string. • Initialize a variable called RaspberryPi and load the IP address of your Raspberry 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

MIT App Inventer UK 200311.indd 190

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

• 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. • Set variable TH to get responseContent which is data sent by the Raspberry Pi • The received data is a string in the form tt,hh where tt and hh are the temperature and humidity values respectively in string format, separated by a comma. Extract the first two characters (temperature) and store them in TxtTemperature.Text • Extract the two characters starting from position 4 (humidity) and store in TxtHumidity.Text

Figure 7.21 Block program of the project The QR code of the project is shown in Figure 7.22.

Figure 7.22 QR code of the project 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

MIT App Inventer UK 200311.indd 191

03-04-20 10:38

MIT App Inventor Projects

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')

Figure 7.23 Python program (temphum.py) of the project ● 192

MIT App Inventer UK 200311.indd 192

03-04-20 10:38

Chapter 7 • Raspberry Pi Wi-Fi based projects using the MIT App Inventor

To test the program, start the Python program either using Thonny or from the command line as:

pi@raspberrypi:~ $ sudo python3 temphum.py

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.

Figure 7.24 Example display on the Android mobile phone 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 Raspberry Pi projects.

● 193

MIT App Inventer UK 200311.indd 193

03-04-20 10:38

MIT App Inventor Projects

Chapter 8 • Raspberry Pi Node-Red based projects using MIT App Inventor 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 communication 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. 8.2 Project 1 – Controlling an LED – Web Server 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. Block Diagram: The block diagram of the project is as in Figure 6.1. 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.

Figure 8.1 Block program of the project

● 194

MIT App Inventer UK 200311.indd 194

03-04-20 10:38

Chapter 8 • Raspberry Pi Node-Red based projects using MIT App Inventor

The QR code of the project is shown in Figure 8.2.

Figure 8.2 QR code of the project Node-RED flow program: Start Node-RED on your Raspberry Pi by entering:

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.

Figure 8.3 Flow program of the project The steps are as follows: • Create two http in nodes and configure them as follows: First http in node: Method: GET URL: /LED/on Second http in node: Method: GET URL: /LED/off • When the GET request 192.168.1.202:1880/LED/on comes from the Android mobile phone, http in node /LED/on is activated. Similarly, node /LED/off is activated when the GET request 192.168.1.202:1880/LED/off comes.

● 195

MIT App Inventer UK 200311.indd 195

03-04-20 10:38

MIT App Inventor Projects

• 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];

Figure 8.4 Function node • 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 • Join the nodes as in Figure 8.3 and click Deploy. 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. 8.3 Project 2 – Controlling 4 Relays – Web Server Description: In this project, a 4 channel relay module is connected to Raspberry Pi as in Project 3 (section 7.4). The relay channels are controlled individually by clicking buttons on the Android mobile phone. Block Diagram: The block diagram of the project is as shown in Figure 7.12.

● 196

MIT App Inventer UK 200311.indd 196

03-04-20 10:38

Chapter 8 • Raspberry Pi Node-Red based projects using MIT App Inventor

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.

Figure 8.5 Change variable RaspberryPi The QR code of the project is shown in Figure 8.6.

Figure 8.6 QR code of the project Node-RED flow program: Figure 8.7 shows the Node-RED flow program (NODE_RELAY) 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. The steps are: • Create 8 http in nodes and configure the as follows: Node Node Node Node Node Node Node Node

1: 2: 3: 4: 5: 6: 7: 8:

Method: Method: Method: Method: Method: Method: Method: Method:

GET GET GET GET GET GET GET GET

URL: URL: URL: URL: URL: URL: URL: URL:

/RELAY/on1 /RELAY/off1 /RELAY/on2 /RELAY/off2 /RELAY/on3 /RELAY/off3 /RELAY/on4 /RELAY/off4

• 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 activates 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

MIT App Inventer UK 200311.indd 197

03-04-20 10:38

MIT App Inventor Projects

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

MIT App Inventer UK 200311.indd 198

03-04-20 10:38

Chapter 8 • Raspberry Pi Node-Red based projects using MIT App Inventor

Figure 8.7 Flow program of the project

Figure 8.8 Part of the function code

Figure 8.9 rpi gpio out node for RELAY4

● 199

MIT App Inventer UK 200311.indd 199

03-04-20 10:38

MIT App Inventor Projects

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 processor and Android mobile phone with App Inventor.

● 200

MIT App Inventer UK 200311.indd 200

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor 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. 9.2 Arduino Uno Board Figure 9.1 shows the Arduino Uno board in close-up with the major components marked. The pin definitions are as follows (see Figure 9.2). A0 – A5: Analog input ports 0 – 13: Digital input/output ports ~3,~5,~6,~9,~10,~11: PWM output ports 0,1: UART RX/TX pins. LEDs labelled TX, RX will flash when data is transmitted or received respectively GND: Power supply ground pin 5V: Regulated +5V output 3.3V: Regulated +3.3V output Vin: Voltage input (instead of using Power In or USB). The voltage must be in the range 7-12V. It is regulated to +5V internally. This pin can also be used as a voltage output (if power is supplied using Power In or USB port). The voltage is a copy of the voltage supplied through Power In or the USB port. IOREF: Used by external shield boards to know if they should operate as +3.3V or as +5V devices Power In: Power supply Barrel Jack pin (6V to 12V) USB port: Power and data port (connect to a computer) User LED: Onboard LED connected to output port 13 (can be used for test purposes) 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

MIT App Inventer UK 200311.indd 201

03-04-20 10:38

MIT App Inventor Projects

The absolute maximum current for any I/O pin is specified as 40mA (it is however recommended not to exceed 20mA). The absolute total current from all the I/O pins is 200mA.

Figure 9.1 Arduino Uno board

Figure 9.2 Arduino Uno pin layout 9.3 Arduino Uno Program Development A nice feature of all the Arduino boards is that they can all be programmed using the Arduino IDE. The latest version of Arduino IDE can be downloaded from the following web site. At the time of writing this book the latest version was 1.8.8: https://www.arduino.cc/en/Main/Software The steps to writing and uploading a program to your Arduino Uno are as follows:

● 202

MIT App Inventer UK 200311.indd 202

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

• Connect your Arduino Uno to the USB port of your computer • Start the Arduino IDE on your computer • 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 • Write and then save your program • Click Sketch -> Verify/Compile to compile your program. Make sure there are no compilation errors • Click Sketch->Upload to upload the executable code to the program memory of your Arduino Uno 9.4 Bluetooth for Arduino Uno Unfortunately, Arduino Uno does not have on-board Bluetooth circuitry. However, we can easily connect external Bluetooth modules to Arduino. Two popular and cheap Bluetooth modules are HC-05 and HC-06. HC-05 and HC-06 are very similar to each other and they can both be used to provide Bluetooth connectivity to Arduino Uno. 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.

Figure 9.3 HC-06 Bluetooth module

● 203

MIT App Inventer UK 200311.indd 203

03-04-20 10:38

MIT App Inventor Projects

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 connected 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. 9.5 Project 1 - Controlling an LED Description: In this project, the on-board LED of Arduino UNO is controlled from an Android mobile phone over a Bluetooth link. Block Diagram: Figure 9.4 shows the block diagram of the project.

Figure 9.4 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

MIT App Inventer UK 200311.indd 204

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.5 Circuit diagram of the project App Inventor Program: The App Inventor program of this project is the same as in chapter 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 program 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

// 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

MIT App Inventer UK 200311.indd 205

03-04-20 10:38

MIT App Inventor Projects

} void loop() { if(Bluetooth.available() > 0)

// If data available

{ rd = Bluetooth.read();

// Read data

if(rd == '1')

// If "1"

digitalWrite(LED, HIGH); else if(rd == '0') digitalWrite(LED, LOW);

// Turn ON LED // If "0" // Turn OFF LED

} }

Figure 9.6 Arduino UNO program 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 • Go to Bluetooth settings and enable Bluetooth on your Android mobile phone. Click scan and wait until HC-06 is displayed • 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 • Compile and upload the Arduino Uno program (Arduino_LED) • Click Connect on your Android mobile phone and select HC-06 to make a connection 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

MIT App Inventer UK 200311.indd 206

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.7 Turn ON the LED Figure 9.8 shows the circuit where the potential divider resistors are placed on a breadboard and connection between the HC-06 and Arduino UNO is made using jumper wires.

Figure 9.8 Construction of the circuit 9.6 Project 2 - Controlling a 4 Channel Relay Description: In this project, the 4 channel relay used in Project 2 in Chapter 8 is connected 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

MIT App Inventer UK 200311.indd 207

03-04-20 10:38

MIT App Inventor Projects

Figure 9.9 Block diagram of the project 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.

Figure 9.10 Circuit diagram of the project

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): • Create a new program and name it as Arduino_Relay4 • Insert a HorizontalArrangement and insert a Label on it. Set the Text of the Label to 4 RELAY CONTROLLER • Insert a VerticalArrangement with the following configuration: 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 Bluetooth connection status. Configure this Label as follows:

● 208

MIT App Inventer UK 200311.indd 208

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Name: LblStatus FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Text: Status TextColor: None Visible: ticked • Insert a ListPicker component on the VerticalArrangement with the following configuration. The user will select the Bluetooth device to connect to with this component: Name: ListPicker1 BackgrundColor: Default FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Image: none TextColor: White • Insert 4 HorizontalArrangements and insert 2 Buttons on each one. Clicking these buttons will turn the LED ON or OFF. The configurations of the buttons are as follows: Button Name

BackgroundColor FontBold

FontSize Shape Text

TextColor

Relay1ON

Blue

ticked

20

oval

White

Relay1OFF

Blue

ticked

20

oval RELAY1OFF White

Relay2ON

Blue

ticked

20

oval

Relay2OFF

Blue

ticked

20

oval RELAY2OFF White

RELAY1 ON RELAY2 ON

White

Relay3ON

Blue

ticked

20

oval

RELAY3 ON

White

Relay3OFF

Blue

ticked

20

oval

RELAY3 OFF

White

Relay4ON

Blue

ticked

20

oval

RELAY4 ON

White

Relay4OFF

Blue

ticked

20

oval

RELAY4 OFF

White

• Insert a BluetoothClient and a Clock component onto the Viewer. These are shown at the bottom of the phone image

● 209

MIT App Inventer UK 200311.indd 209

03-04-20 10:38

MIT App Inventor Projects

Figure 9.11 Design of App Inventor Figure 9.12 shows the block program of the project. Notice that part of the blocks that interface 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: Command 1on 1off 2on 2off 3on 3off 4on 4off

Relay function Activate RELAY1 Deactivate RELAY1 Activate RELAY2 Deactivate RELAY2 Activate RELAY3 Deactivate RELAY3 Activate RELAY4 Deactivate RELAY4

The steps are: • Click Relay1ON and select when Relay1ON.Click do. This block will be activated when user clicks on button RELAY1 ON. • Insert a block to check whether or not there is Bluetooth connection • Click BluetoothClient1 and select call BluetoothClient1.SendText. Insert a Text block and set the text to 1on. Sending 1on will request from Arduino UNO to activate RELAY1 • Repeat for all the other 7 buttons as shown in Figure 9.12a and Figure 9.12b.

● 210

MIT App Inventer UK 200311.indd 210

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.12a Block program of the project

Figure 9.12b cont…

● 211

MIT App Inventer UK 200311.indd 211

03-04-20 10:38

MIT App Inventor Projects

The QR code of the project is shown in Figure 9.13.

Figure 9.13 QR code of the project 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

// 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

MIT App Inventer UK 200311.indd 212

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

digitalWrite(IN1, HIGH);

// Relay1 OFF at start

digitalWrite(IN2, HIGH);

// Relay2 OFF at start

digitalWrite(IN3, HIGH);

// Relay3 OFF at start

digitalWrite(IN4, HIGH);

// Relay4 OFF at start

Bluetooth.begin(9600);

// Bluetooth speed

} 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 To steps to test the program are: • Power up your circuit with the HC-06 connected. You should see the red LED flashing on your HC-06 module • Go to Bluetooth settings and enable Bluetooth on your Android mobile phone. Click scan and wait until HC-06 is displayed • 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

MIT App Inventer UK 200311.indd 213

03-04-20 10:38

MIT App Inventor Projects

• Compile and upload the Arduino Uno program (Arduino_Relays) • Click Connect on your Android mobile phone and select HC-06 to make a connection 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 application on an Android mobile phone is shown in Figure 9.15

Figure 9.15 Example run of the program 9.7 Project 3 - Controlling a 4 Channel Relay with Sound Output 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. Circuit Diagram: The circuit diagram is the same as in Figure 9.10. App Inventor Program: The App Inventor design (Arduino_Relay4_Sound) is the same as in Figure 9.11 except that here, additionally a TextToSpeech component must be added to the Viewer. 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

MIT App Inventer UK 200311.indd 214

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.16a Block program of the project

Figure 9.16b cont…

● 215

MIT App Inventer UK 200311.indd 215

03-04-20 10:38

MIT App Inventor Projects

The QR code of the project is shown in Figure 9.17.

Figure 9.17 QR code of the project 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. 9.8 Project 4 - Controlling a 4 Channel Relay with Speech Description: This project is very similar to Project 2, but here the relays are controlled with speech. Block Diagram: The block diagram is the same as in Figure 9.9. Circuit Diagram: The circuit diagram is the same as in Figure 9.10. 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: RELAY

Equipment connected to

Speech Command

Arduino UNO command

1

Heater

heater on

1on

1

Heater

heater off

1off

2

Boiler

boiler on

2on

2

Boiler

boiler off

2off

3

Charger

charger on

3on

3

Charger

charger off

3off

4

Radio

radio on

4on

4

Radio

radio off

4off

Figure 9.18 shows the design of the project. The steps are as follows: • Create a new project and name it as Arduino_Relay4_Speech • Insert a HorizontalArrangement and a Label and set the Text of the Label to RELAY SPEECH CONTROL

● 216

MIT App Inventer UK 200311.indd 216

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

• Insert a VerticalArrangement and insert a Label and a ListPicker on it as described in Project 2 • Insert a HorizontalArrangement and insert a Button on it. Clicking this button will enable the user to give the speech command. Configure the button as follows: Name: ButtonStart BackgroundColor: Blue FontBold: ticked FontSize: 20 FontTypeface: default Height: Automatic Width: Automatic Image: none Shape: oval Text: Start • Insert a BluetoothClient component, a Clock component, and a SpeechRecognizer component onto the Viewer.

Figure 9.18 Design of the project 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

MIT App Inventer UK 200311.indd 217

03-04-20 10:38

MIT App Inventor Projects

• 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 • If Bluetooth is connected, then click SpeechRecognizer1 and select call SpeechRecognizer1.GetText and join this block to the other one as shown in the figure. This block will receive the spoken command and save it in text format • Click SpeechRecognizer1 and select when SpeechRecognizer1.AfterGettingText do. This block will be activated after the end of the spoken command. Here, we compare the received command with the valid commands and then send the corresponding command to the Arduino UNO to activate/deactivate the correct relay. Variable result is used to hold the text form of the spoken command. For example, if the spoken command is heater on then variable result is set to 1on. Similarly, if the spoken command is boiler off then variable result is set to 2off. At the end of the if-then-else block the contents of variable result is sent to the Arduino Uno by calling BluetoothClient1 and setting its text to result.

● 218

MIT App Inventer UK 200311.indd 218

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.19 Block program of the project The QR code of the project is shown in Figure 9.20.

Figure 9.20 QR code of the project Arduino Uno Program: The Arduino Uno program is exactly the same as the one given in Figure 9.14 (Arduino_Relays).

● 219

MIT App Inventer UK 200311.indd 219

03-04-20 10:38

MIT App Inventor Projects

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 • Go to Bluetooth settings and enable Bluetooth on your Android mobile phone. Click scan and wait until HC-06 is displayed • Pair the HC-06 with your Android mobile phone. If asked for a password, enter 1234 • Install App Inventor on your Android mobile phone • Compile and upload the Arduino Uno program (Arduino_Relays) • Click Connect on your Android mobile phone and select HC-06 to make a connection 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.

Figure 9.21 Application on the Android mobile phone

● 220

MIT App Inventer UK 200311.indd 220

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

9.9 Project 5 – Sending Text to Arduino UNO Description: In this project, a 16x2 (16 columns x 2 rows) LCD is connected to the Arduino 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 compatible 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 16pin) 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: Pin no

Name

Function

1

VSS

Ground

2

VDD

+ ve supply

3

VEE

Contrast

4

RS

Register select

5

R/W

Read/write

6

E

Enable

7

D0

Data bit 0

8

D1

Data bit 1

9

D2

Data bit 2

10

D3

Data bit 3

11

D4

Data bit 4

12

D5

Data bit 5

13

D6

Data bit 6

14

D7

Data bit 7

15

A

Anode (light)

16

K

Cathode (light)

Table 9.1 Pin configuration of HD44780 LCD module 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

MIT App Inventer UK 200311.indd 221

03-04-20 10:38

MIT App Inventor Projects

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 between 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 becomes 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.

Figure 9.22 Block diagram of the project Circuit Diagram: The circuit diagram is same as in Figure 9.23. The connections between the LCD and the Arduino UNO are as follows: LCD D4 D5 D6 D7 E RS R/W K Vdd VE

Arduino UNO 8 9 10 11 12 13 GND GND +5V Potentiometer

● 222

MIT App Inventer UK 200311.indd 222

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.23 Circuit diagram of the project App Inventor Program: The App Inventor design (LCD_Arduino) is shown in Figure 9.24. The steps are as follows: • Insert a VerticalAssignment and a Label and a ListPicker on it as described in the earlier projects. These components establish the Bluetooth communication • Insert a TableArrangement with the following configuration: Columns: 3 Height: Automatic Width: Fill parent Rows: 2 Visible: ticked • Insert 2 Labels and 2 TextBoxes onto the TableArrangement with the following 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: Component Name FontBold FontSize Height

Width

Label

Label1

TextBox Label TextBox

TxtRow2 ticked

ticked

Text TextColor

20

Automatic

Automatic Row1: Blue

TxtRow1 ticked

16

Automatic

40 percent -

Label2

20

Automatic

Automatic Row2: Blue

16

Automatic

40 percent -

ticked

Default Default

• Insert a HorizontalArrangement and insert 2 Buttons on it with the following configurations. Clicking Button Click to Send sends the data in the two TextBoxes to the Arduino so that they are displayed on the LCD. Clicking Button Click to Clear clears the LCD: Name: ButtonSend BackgroundColor: Default FontBold: ticked FontSize: 20

● 223

MIT App Inventer UK 200311.indd 223

03-04-20 10:38

MIT App Inventor Projects

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 • Insert a HorizontalArrangement and insert a Button on it with the name ButtonDisconnect. Clicking this button will disconnect the Bluetooth connection • Insert a BluetoothClient component and a Clock component onto the Viewer

Figure 9.24 Design of the project 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

MIT App Inventer UK 200311.indd 224

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

toothClient1.SendText. The text we wish to send to the Android mobile phone should be joined to this block. Insert a Join block and extend it to have 3 inputs. Insert the text that should be displayed at row 1 of the LCD, then insert the character #, followed by the text that should be displayed at row 2 of the LCD. Notice that the text for row1 and row2 are separated with the # character (the Arduino UNO program will extract the text for row1 and row2). • Click ButtonClear and insert blank texts for both row1 and row2 of the LCD. Clicking this button will clear the LCD screen • Click ButtonDisconnect and insert a block to disconnect the Bluetooth link

Figure 9.25 Block program of the project The QR code of the project is shown in Figure 9.26.

● 225

MIT App Inventer UK 200311.indd 225

03-04-20 10:38

MIT App Inventor Projects

Figure 9.26 QR code of the project 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 included in the program. The RX and TX pins of the serial UART are defined as 6 and 7 respectively. 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. The LCD pin assignmnets ust be declared in LiquidCrystal as: LiquidCrystal lcd(RS, E, D4, D5, D6, D7); Program: LCD_TEST Date

: February 2020

Author : Dogan Ibrahim -------------------------------------------------------------------*/ #include

// Software UART

#include

// LCD library

SoftwareSerial Bluetooth(6, 7);

// RX, TX

//

● 226

MIT App Inventer UK 200311.indd 226

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

// Initialize the LCD library // LiquidCrystal lcd(13, 12, 8, 9, 10, 11);

// LCD connections

String rd, firstrow, secondrow; int hash; 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

} }

Figure 9.27 Arduino UNO program (LCD_TEST) of the project 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): Blink(): Turn ON blinking noBlink(): Turn OFF blinking autoscroll(): Turn ON scrolling noAutoScroll(): Turn OFF auto-scrolling clear(): Clear display and home the cursor home(): Home the cursor setCursor(): Set cursor position print(): Print text to LCD 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

MIT App Inventer UK 200311.indd 227

03-04-20 10:38

MIT App Inventor Projects

Figure 9.28 Example run of the program

Figure 9.29 Texts displayed on the LCD 9.10 Project 6 – Sending the Ambient Temperature to Android Mobile Phone Description: In this project, an analog temperature sensor chip is connected to Arduino UNO. The temperature readings are sent to an Android mobile phone and displayed on the screen. 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: Vcc: power supply (+5V) Gnd: power ground Vo: Output 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 millivolts. For example, if the output voltage is 250mV then the measured temperature is 25ºC.

● 228

MIT App Inventer UK 200311.indd 228

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.30 LM35 temperature sensor LM35DZ has the following features: • output voltage 10mV/ • accuracy 0.5ºC • -55ºC to +150ºC measurement range • 4V to 30V operation • 60μA current consumption • 0.08ºC self-heating Block Diagram: The block diagram of the project is shown in Figure 9.31.

Figure 9.31 Block diagram of the project Circuit Diagram: Figure 9.32 shows the circuit diagram of the project.

Figure 9.32 Circuit diagram of the project

● 229

MIT App Inventer UK 200311.indd 229

03-04-20 10:38

MIT App Inventor Projects

App Inventor Program: Figure 9.33 shows the App Inventor design. The steps are: • Create a new project and name it as LM35DZ_APP • Insert a VerticalArrangement and components ListPicker1 and LblStatus as in the previous project as these components establish Bluetooth communication with the Android mobile phone • Insert a HorizontalArrangement and insert a Label on it with the following configuration: Name: Label1 BackgroundColor: None FontBold: ticked FontSize: 30 Height: Automatic Width: Automatic Text: Temperature (C) TextColor: Red • Insert a HorizontalArrangement with a Height of 20 percent and BackgroundColor set to Orange • Insert a TextBox on the HorizontalArrangement. This TextBox will display the temperature received from the Arduino UNO. Configure this TextBox as follows (this TextBox will not be visible since its BackgroundColor is same as the colour of the HorizontalArrangement): Name: TxtTemperature BackgroundColor: Orange FontBold: ticked FontSize: 70 Height: 15 percent Width: 65 percent Hint: blank Text: blank TextColor: Blue • Insert a BluetoothClient component and 2 Clock components. Name one of the Clock components as TempClock. This Clock component will be used to periodically read and display the temperature data received from the Arduino UNO.

● 230

MIT App Inventer UK 200311.indd 230

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.33 Design of the project 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 activated 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 enter 0176. The temperature will be displayed in this TextBox in the form of nn.nºC.

Figure 9.34 Block program of the project

● 231

MIT App Inventer UK 200311.indd 231

03-04-20 10:38

MIT App Inventor Projects

Figure 9.35 shows the QR code of the project.

Figure 9.35 QR code of the project Arduino UNO Program: Figure 9.36 shows the Arduino UNO program (Arduino_LM35DZ). At the beginning of the program header file SoftwareSerial is included in the program 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 quantization 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 ================== In this project a LM35DZ type analog sensor chip is connected to pin A0 of teh Arduino UNO. The temperature readings are sent to the Android mobile phone. Program: Arduino_LM35DZ Date

: February 2020

Author : Dogan Ibrahim -------------------------------------------------------------------*/ #include

// 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

MIT App Inventer UK 200311.indd 232

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

{ 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

Bluetooth.print(rd);

// Send to Android

delay(1000); }

Figure 9.36 Arduino UNO program (Arduino_LM35DZ) listing To test the program: • Compile and upload the Arduino UNO program • Install and start the Android mobile phone program • Click Connect and select the HC-06 to connect to the Arduino UNO • You should see the temperature displayed in large characters as shown in Figure 9.37.

Figure 9.37 Temperature displayed on the Android mobile phone

● 233

MIT App Inventer UK 200311.indd 233

03-04-20 10:38

MIT App Inventor Projects

9.11 Project 7 – Weather Watch 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 sensor 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

Figure 9.38 DHT11 module 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.

Figure 9.39 Block diagram of the project

● 234

MIT App Inventer UK 200311.indd 234

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

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.

Figure 9.40 Circuit diagram of the project App Inventor Program: Figure 9.41 shows the design of the project (see Figure 9.41) • Create a new project and name it as ARDUINO_DHT11 • Insert a VerticalArrangement and components ListPicker1 and LblStatus as in the previous project as these components establish Bluetooth communication with the Android mobile phone • Insert 3 HorizontalArrangements and set their BackgroundColor to Pink • Insert 3 Labels and 3 TextBoxes on these HorizontalArrangements with the following configurations: Component Name

FontSize Height

Width

Text

Label

Label1

16

Automatic

Automatic

Temperature (C) Blue

TextColor

Label

Label2

16

Automatic

Automatic

Humidity (%)

Blue

Label

Label3

16

Automatic

Automatic

Dew Point (C)

Blue

TextBox

TxtTemperature 20

Automatic

20 precent

TextBox

TxtHumidity

20

Automatic

20 percent

TextBox

TxtDewpoint

20

Automatic

20 percent

• Insert a HorozontalArrangement with its Height and Width both set to Fill parent and its BackgroundColor set to White • Insert an Image component on the HorizontalArrangement and upload the weather image (weather.jpg) shown in Figure 9.41 • Insert a BluetoothClient component and 2 Clock components. Change the name of one of the Clock components to ClockGetData. This component will be activated at regular intervals to read the data sent by the Arduino UNO.

● 235

MIT App Inventer UK 200311.indd 235

03-04-20 10:38

MIT App Inventor Projects

Figure 9.41 Design of the project 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 Arduino 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 • Set variable THD to the BluetoothClient1.ReceiveText block and store the received data in this variable. • 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 separator 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. • Check to make sure that the list contains 3 items - Set TxtTemperature to index 1 of the list, i.e. the temperature - Set TxtHumidity to index 2 of the list, i.e. the humidity - Set TxtDewPoint to index 3 of the list, i.e. the dew point

● 236

MIT App Inventer UK 200311.indd 236

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.42 Block program of the project 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 Libraries • Enter DHT and look for DHT sensor library by Adafruit as shown in Figure 9.43. • Click Install

Figure 9.43 Look for the DHT sensor library • Search for the library Adafruit Unified Sensor by Adafruit (you may have to scroll to find it), and click Install • Close the Library Manager

● 237

MIT App Inventer UK 200311.indd 237

03-04-20 10:38

MIT App Inventor Projects

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 ============================== In this project a DHT11 type sensor module is connected to the Arduino. The ambient temperature, humidity, and Dew Point are sent to the Android mobile phone over the Bluetooth link. Program: Arduino_DHT11 Date

: February 2020

Author : Dogan Ibrahim ------------------------------------------------------------------------*/ #include "DHT.h"

// DHT library

#include

// Software UART

#define DHTPIN 8

// DHT11 at pin 8

#define DHTTYPE DHT11

// Using DHT11

DHT dht(DHTPIN, DHTTYPE); SoftwareSerial Bluetooth(6, 7);

// RX, TX

String rd; 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

MIT App Inventer UK 200311.indd 238

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

rd = TS + "," +HS + "," + DS;

// Join T,H,D

Bluetooth.print(rd);

// Send to Android

delay(5000);

// 5 second delay

}

Figure 9.44 Arduino UNO program (Arduino_DHT11) An example run of the program on the Android mobile phone is shown in Figure 9.45.

Figure 9.45 Example run of the program 9 .12 Project 8 – ON-OFF Temperature Control Description: This is an ON-OFF temperature control project which controls the temperature 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. Background Information: ON-OFF temperature control is the simplest form of temperature control. The advantage of this method is that there is no need to know the characteristics of the room whose temperature is to be controlled. Additionally, there are no complicated algorithms involved. The ON-OFF control algorithm can be described by the following statements: IF set-point temperature > Room temperature THEN Activate the relay ELSE Deactivate the relay ENDIF

● 239

MIT App Inventer UK 200311.indd 239

03-04-20 10:38

MIT App Inventor Projects

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.

Figure 9.46 ON-OFF type temperature control Block Diagram: Figure 9.47 shows the block diagram of the project.

Figure 9.47 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.

Figure 9.48 Circuit diagram of the project

● 240

MIT App Inventer UK 200311.indd 240

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

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 displays 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. The steps are as follows: • Create a new project and name it as TEMP_ON_OFF • Insert a VerticalArrangement and components ListPicker1 and LblStatus as in the previous project as these components establish Bluetooth communication with the Android mobile phone • 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 • Insert a VerticalArrangement and insert a Label, a TextBox and a Slider component on it. Set the Text of the Label to SET TEMPERATURE (C), name of the TextBox to TxtSet, and the name of the Slider to Slider1. Set the Width of the TextBox to 20 percent, and set the Width of the Slider to 85 percent, its MaxValue to 50 and its MinValue to 0. • Insert components BluetoothClient and 2 Clocks on the Viewer. Name one of the Clocks as ClockGetData. This Clock will be used to get the temperature readings from the Arduino UNO periodically.

Figure 9.49 Design of the project

● 241

MIT App Inventer UK 200311.indd 241

03-04-20 10:38

MIT App Inventor Projects

Figure 9.50 shows the block program of the project. The steps are as follows: • Initialize a variable called RoomTemp and a variable called SetTemp. These variables will hold the room temperature and the set-temperature values respectively. • Set the TxtRoom.Text and TxtSet.Text to RoomTemp and SetTemp respectively at the beginning of the program • Insert blocks as in the previous projects to establish Bluetooth communication • 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 Arduino 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 background 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

MIT App Inventer UK 200311.indd 242

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.50 Block program of the project 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 setpoint is higher than the room temperature and the background colour is changed to pink to indicate that the relay is activated.

Figure 9.51 QR code of the project

● 243

MIT App Inventer UK 200311.indd 243

03-04-20 10:38

MIT App Inventor Projects

Figure 9.52 Set-point lower than the room temperature

Figure 9.53 Set-point higher than the room temperature 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

MIT App Inventer UK 200311.indd 244

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

/*--------------------------------------------------------------ON-OFF TEMPERATURE CONTROL ========================== In this project a LM35DZ type analog sensor chip is connected to pin A0 of the Arduino UNO. The temperature readings are sent to the Android mobile phone. Android mobile phone sends commands to the Arduino UNO to activate or deactivate the relay. Program: Arduino_ON_OFF_TEMP Date

: February 2020

Author : Dogan Ibrahim -------------------------------------------------------------------*/ #include

// 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

if(Bluetooth.available())

// Is data available

{ rd = Bluetooth.readString();

// read command

if(rd == "1")

// If "1"?

digitalWrite(RELAY, HIGH); else if(rd == "0") digitalWrite(RELAY, LOW);

// Turn ON Relay // If "0"? // Turn OFF Relay

} delay(1000);

● 245

MIT App Inventer UK 200311.indd 245

03-04-20 10:38

MIT App Inventor Projects

}

Figure 9.54 Arduino UNO program (Arduino_ON_OFF_TEMP) 9.13 Project 9 – Modified ON-OFF Temperature Control 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 components are added to the design. These components are used to deactivate the relay and disconnect from the Bluetooth.

Figure 9.55 Design of the project Figure 9.56a and Figure 9.56b show the block program of the project. The disconnection process is as follows: • User click Button Disconnect • Clock2 timer interval is set to 5000 milliseconds • The background colour is changed to gray to indicate that the heater is OFF • Clock2 timer is enabled • After 5000 milliseconds, Clock 2 is triggered • A "0" is sent to the Arduino UNO to command for the relay to be deactivated • Clock3 timer interval is set to 3000 milliseconds • Clock3 timer is enabled • After 3000 milliseconds Bluetooth is disconnected

● 246

MIT App Inventer UK 200311.indd 246

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

The description of this block program is left as an exercise to the reader.

Figure 9.56a Block program of the project

Figure 9.56b cont…

● 247

MIT App Inventer UK 200311.indd 247

03-04-20 10:38

MIT App Inventor Projects

9.14 Project 10 – Controlling a Stepper Motor 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 direction (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 motors are used in many precision motion control applications, in robotic arms, and in mobile robots to drive the wheels. There are two types of stepper motors: unipolar and bipolar. Unipolar Stepper Motors Unipolar stepper motors have four windings with a common center tap on each pair of windings (see Figure 9.57). Therefore, there are normally 5 or 6 leads depending on whether the common leads are joined or not.

Figure 9.57 Unipolar stepper motor windings 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

MIT App Inventer UK 200311.indd 248

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

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

Table 9.3 2 Phase half-step mode Bipolar Stepper Motors Bipolar stepper motors have one winding per phase as shown in Figure 9.58. Bipolar motor driver circuits are more complicated since the current in the windings needs to be reversed to rotate them in the reverse direction.

Figure 9.58 Bipolar stepper motor windings

● 249

MIT App Inventer UK 200311.indd 249

03-04-20 10:38

MIT App Inventor Projects

Speed of a Stepper Motor The speed of a stepper motor depends on the time between the pulses given to its windings. For faster speeds, the pulses must be given with shorter delays between them. If T is the time between the pulses and β is the step constant of the motor, the moto rotates by β/T steps in one second. Since a complete revolution is 360º, the number of revolutions in a second is β/360T. The speed of a motor is normally quoted in RPM and therefore: or,

RPM = 60β/360T 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:

T = β/6RPM = 10 / (6 x 1000) = 1.66ms

Therefore, the pulses between each step must be 1.66ms. Movement of the Motor Shaft In some applications, we may want the motor shaft to rotate a specified amount and we need to know how many pulses to send to the motor. If β is the step constant of the motor and we want the shaft to rotate by v degrees, the required number of pulses is given by:

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.

Figure 9.59 Block diagram of the project

● 250

MIT App Inventer UK 200311.indd 250

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Circuit Diagram: In this project, a small 28BYJ-48 type unipolar stepper motor (see Figure 9.60) is used. This motor has the following specifications: Rated voltage: Number of phases: Gear ratio: Frequency: Step angle: Maximum speed:

5V 4 64 100Hz 11.25º / step 18 RPM

Figure 9.60 28BYJ-48 unipolar stepper motor 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 righthand side of the module. In this project, the module was powered from an external +5V DC power supply for the motor.

Figure 9.61 ULN2003 motor driver module Figure 9.62 shows the circuit diagram of the project. Port pins 8, 9 10, and 11 of the Arduino UNO are connected to driver module inputs IN1, IN2, IN3, and IN4 respectively.

● 251

MIT App Inventer UK 200311.indd 251

03-04-20 10:38

MIT App Inventor Projects

Figure 9.62 Circuit diagram of the project) 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: • Create a new project and name it as Stepper • Insert a VerticalArrangement and components ListPicker1 and LblStatus as in the previous project as these components establish Bluetooth communication with the Android mobile phone • Insert a VerticalArrangement and insert a TextBox, a Slider, and a Label on it. Set the TextBox name to TxtRevs, its FontSize to 20, Height to Automatic and Width to 25 percent. This TextBox will show the selected revolution as the slider arm is moved. Set the name of the Slider to Slider1, its MinValue to 1 and MaxValue to 30 (we can request from 1 to up to 30 revolutions). Set the Text of the Label to Number of Revolutions, and set its FontSize to 16. • Insert a HorizontalArrangement and set its Height and Width to Fill parent. Insert the image motor.jpg on it. • Insert components BluetoothClient and Clock as in the previous Bluetooth based projects

● 252

MIT App Inventer UK 200311.indd 252

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Figure 9.63 Design of the project 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 revolutions. 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.

Figure 9.64 Block program of the project

● 253

MIT App Inventer UK 200311.indd 253

03-04-20 10:38

MIT App Inventor Projects

The QR code of the project is shown in Figure 9.65.

Figure 9.65 QR code of the project 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 repeated. Reversing the sequence reverses the direction of rotation). Step

4 (orange)

3 (yellow)

2 (pink)

1 (blue)

IN1

IN2

IN3

IN4

1

1

1

0

0

2

0

1

1

0

3

0

0

1

1

4

1

0

0

1

Table 9.4 Full-step mode Half-step Mode The half-step mode with 8 steps per cycle is recommended by the manufacturer. In halfstep 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

MIT App Inventer UK 200311.indd 254

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

Step

4 (orange)

3 (yellow)

2 (pink)

1 (blue)

IN1

IN2

IN3

IN4

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

Table 9.5 Half-step mode 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 complete revolution. The motor speed in RPM is given by the following equation: or,

RPM = 60 x 103 / (2048 x T) RPM = 29.3 / T

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 control the motor in Full-step mode are defined in integer array FullMode as follows: int FullMode[4] = {0b01100, 0b00110, 0b00011, 0b01001};

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

MIT App Inventer UK 200311.indd 255

03-04-20 10:38

MIT App Inventor Projects

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 ===================== In this project a stepper motor is connected to the Arduino UNO through a motor driver module. The program receives commands from the mobile phone and controls the number of rotations. Program: Arduino_Stepper Date

: February 2020

Author : Dogan Ibrahim -------------------------------------------------------------------*/ #include

// 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; for(j = 0; j < count; j++) { for(m = 0; m < StepsPerCycle; m++) { for(i = 0; i < 4; i++) { k = 3-i; SendPulse(k); delay(StepDelay); }

● 256

MIT App Inventer UK 200311.indd 256

03-04-20 10:38

Chapter 9 • Arduino Uno Bluetooth based projects using MIT App Inventor

} } }

// // 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; IN1bit = BitRead(FullMode[k], 1); IN2bit = BitRead(FullMode[k], 2); IN3bit = BitRead(FullMode[k], 4); IN4bit = BitRead(FullMode[k], 8); digitalWrite(IN1, IN1bit);

// Pulse IN1

digitalWrite(IN2, IN2bit);

// Pulse IN2

digitalWrite(IN3, IN3bit);

// Pulse IN3

digitalWrite(IN4, IN4bit);

// Pulse IN4

} 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

digitalWrite(IN1, 0);

// IN1 = 0 at start

digitalWrite(IN2, 0);

// IN2 = 0 at start

digitalWrite(IN3, 0);

// IN3 = 0 at start

digitalWrite(IN4, 0);

// IN4 = 0 at start

● 257

MIT App Inventer UK 200311.indd 257

03-04-20 10:38

MIT App Inventor Projects

Bluetooth.begin(9600);

// Bluetooth speed

} 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) An example display of the mobile phone is shown in Figure 9.67.

Figure 9.67 Example display of the mobile phone 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

MIT App Inventer UK 200311.indd 258

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor 10.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 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 completeness. 10.2 Arduino Uno Wi-Fi Connectivity Arduino Uno has no built-in Wi-Fi module and as such, cannot be connected to a Wi-Fi network without interfacing an external Wi-Fi module. There are several Arduino Wi-Fi shields available on the market that can be plugged on top of the Arduino Uno to provide Wi-Fi capability to the basic board. Perhaps the easiest and the cheapest way of providing Wi-Fi capability to an Arduino Uno is by using an ESP-01 processor board. This is a tiny board (see Figure 10.1), measuring only 2.7cm x 1.2cm, and is based on the ESP8266 processor chip. It costs around $3. ESP-01 has the following features: • Operating voltage: +3.3V • Interface: using simple AT commands over serial port/UART • Integrated TCP/IP protocol stack. 802.11 b/g/n • No external components required

Figure 10.1 ESP-01 processor board 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: VCC: +3.3V power supply pin GND: Power supply ground GPIO0: I/O pin. This pin must be connected to +3.3V for normal operation, and to GND for uploading firmware to the chip GPIO2: General purpose I/O pin RST: Reset pin. Must be connected to +3.3V for normal operation CH_PD: Enable pin. Must be connected to +3.3V for normal operation TX: Serial output pin RX: Serial input pin

● 259

MIT App Inventer UK 200311.indd 259

03-04-20 10:38

MIT App Inventor Projects

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).

Figure 10.2 ESP-01 breadboard adapter ESP-01 is controlled by AT commands. Some of the commonly used AT commands for Wi-Fi operation are: AT+RST AT+CWMODE AT+CWJAP AT+CIPMUX AT+CIFSR AT+CIPSTART

- reset ESP-01 - set ESP-01 mode (e.g. Station mode) - set Wi-Fi SSID name and password - set connection mode (here it is set to multiple connections) - returns the IP address (not used here) - set TCP or UDP connection mode, destination IP address, and port number AT+CIPSERVER - configure the module as a server 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 software-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.

Figure 10.3 Connecting the ESP-01 to Arduino UNO

● 260

MIT App Inventer UK 200311.indd 260

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

10.3 Project 1 – Controlling an LED Description: In this project, an LED is connected to the Arduino Uno board and it is controlled from the Android mobile phone using a Wi-Fi link. Block Diagram: Figure 10.4 shows the block diagram of the project.

Figure 10.4 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.

Figure 10.5 Circuit diagram of the project App Inventor Program: The design of the project is shown in Figure 10.6. The steps are as follows: • Create a new project and name it as LEDWIFI • Insert a HorizontalArrangement and insert a Label on it with its Text set to LED CONTROLLER

● 261

MIT App Inventer UK 200311.indd 261

03-04-20 10:38

MIT App Inventor Projects

• Insert a HorizontalArrangement and insert two Buttons on it with the following configurations: Name BackgroundColor FontBold FontSize Shape Text

TextColor

LEDOn

Yellow

ticked

20

oval

LED ON

Default

LEDOff

Yellow

ticked

20

oval

LED OFF

Default

• Insert a TextBox under the HorizontalArrangement named TxtError and unclick the visible box so that the TextBox is not visible. Sometimes the HTTP response returns response errors and we will ignore these errors and will not display them on the screen. • Click tab Connectivity and insert a Web component onto the Viewer

Figure 10.6 Design of the project 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

MIT App Inventer UK 200311.indd 262

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

• 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.

Figure 10.7 Block program of the project The QR code of the project is shown in Figure 10.8.

Figure 10.8 QR code of the project 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 executed 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

MIT App Inventer UK 200311.indd 263

03-04-20 10:38

MIT App Inventor Projects

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):

+IPD,0,344: GET /LEDON HTTP/1.1 Host: 192.168.1.178

If characters LEDON is received then the LED is turned ON by calling function digitalWrite(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 successful 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:

*

Author: Dogan Ibrahim

ArduinoLED

*

Date:

February 2020

*********************************************************************/ #include

// Include serial

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

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

MIT App Inventer UK 200311.indd 264

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

SendCmd("AT+CIPSERVER=1,80"); delay(3000); } void loop() { String received=""; while (wifi.available())

// While there is data

{ received = wifi.readString();

// Read data

if (received.indexOf("LEDON") != -1)

// Data contains

LEDON? { digitalWrite(LED, HIGH);

// LED ON

SendCmd("AT+CIPSEND=6");

//

wifi.print("200 OK");

// Send success code

delay(1000); SendCmd("AT+CIPCLOSE=0"); } if (received.indexOf("LEDOFF") != -1)

// Data contains

LEDOFF? { digitalWrite(LED, LOW);

// LED OFF

SendCmd("AT+CIPSEND=6"); wifi.print("200 OK");

// Send success code

delay(1000); SendCmd("AT+CIPCLOSE=0"); } } } // // 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

MIT App Inventer UK 200311.indd 265

03-04-20 10:38

MIT App Inventor Projects

To test the program: • Power-up the circuit • Compile the Arduino program and upload it to the Arduino UNO • 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.

Figure 10.10 Android apps to show devices on our Wi-Fi router • 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 processor, and start the application on your Android mobile phone. • Click LED ON and you should see that the LED will turn ON.

Figure 10.11 IP address of the ESP-01 processor

● 266

MIT App Inventer UK 200311.indd 266

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

An example run on the Android mobile phone is shown in Figure 10.12.

Figure 10.12 Example run on the Android mobile phone 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 correctly. 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:

*

Author: Dogan Ibrahim

ArduinoLED2

*

Date:

February 2020

*********************************************************************/ #include

// 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

MIT App Inventer UK 200311.indd 267

03-04-20 10:38

MIT App Inventor Projects

SendCmd("AT+RST", "Ready");

// Reset ESP-01

delay(5000); SendCmd("AT+CWMODE=1","OK");

//

SendCmd("AT+CIFSR", "OK");

//

SendCmd("AT+CIPMUX=1","OK");

//

SendCmd("AT+CIPSERVER=1,80","OK");

//

} void loop() { String received=""; while (wifi.available())

// While there is data

{ received = wifi.readString();

// Read data

if (received.indexOf("LEDON") != -1)

// Data contains

LEDON? { digitalWrite(LED, HIGH);

// LED ON

wifi.println("AT+CIPSEND=6");

//

wifi.print("200 OK");

// Send success code

delay(1000); SendCmd("AT+CIPCLOSE=0", "OK"); } if (received.indexOf("LEDOFF") != -1)

// Data contains

LEDOFF? { digitalWrite(LED, LOW);

// LED OFF

wifi.println("AT+CIPSEND=6"); wifi.print("200 OK");

// Send success code

delay(1000); SendCmd("AT+CIPCLOSE=0", "OK"); } } } // // 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

MIT App Inventer UK 200311.indd 268

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

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

if (ch == retword[cnt])

// Check return

cnt++; if (cnt == retword_length) return true;

// End of check? // Return word

received } } return false;

// Return word not

received }

Figure 10.13 Modified Arduino UNO program (ArduinoLED2) 10.4 Project 2 – Controlling a 4 Channel Relay Module 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

MIT App Inventer UK 200311.indd 269

03-04-20 10:38

MIT App Inventor Projects

Figure 10.14 Block diagram of the project 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.

Figure 10.15 Circuit diagram of the project App Inventor Program: The design of the project is shown in Figure 10.16. The steps are as follows: • Create a new project and name it as ARDUINO4_RELAY • Insert a HorizontalArrangement and insert a Label on it with its Text set to 4 RELAY CONTROLLER • Insert 4 HorizontalArrangements and insert buttons on it to control the relay channels. Configure the buttons as follows: Name

BackgroundColor FontBold FontSize Shape Text

TextColor

RELAY1On

Yellow

ticked

20

oval

RELAY1 ON

Default

RELAY1Off

Yellow

ticked

20

oval

RELAY1 OFF

Default

RELAY2On

Yellow

ticked

20

oval

RELAY2 ON

Default

RELAY2Off

Yellow

ticked

20

oval

RELAY2 OFF

Default

RELAY3On

Yellow

ticked

20

oval

RELAY3 ON

Default

● 270

MIT App Inventer UK 200311.indd 270

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

RELAY3Off

Yellow

ticked

20

oval

RELAY3 OFF

Default

RELAY4On

Yellow

ticked

20

oval

RELAY4 ON

Default

RELAY4Off

Yellow

ticked

20

oval

RELAY4 OFF

Default

• Insert a WebViewer component onto the Viewer and unclick it to be not visible

Figure 10.16 Design of the project Figure 10.17a and Figure 10.17b shows the block program of the project. The relay channels are controlled as follows Command sent Relay status /on1 activate RELAY1 /off1 deactivate RELAY1 /on2 activate RELAY2 /off2 deactivate RELAY2 /on3 activate RELAY3 /off3 deactivate RELAY3 /on4 activate RELAY4 /off4 deactivate RELAY4 The steps are: • 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 activated when button RELAY1 ON is clicked. • Click WebViewer1 and select call WebViewer1.GoToUrl. Insert a Join block and enter the ip address of the ESP-01 processor and command /on1 as shown in the Figure. When clicked, the web address 192.168.1.160/on1 will be sent to the Arduino UNO.

● 271

MIT App Inventer UK 200311.indd 271

03-04-20 10:38

MIT App Inventor Projects

• Click RELAY1On and set the button colour to red which clicked ON. Also, set the button colour to black when clicked OFF. • Repeat for the other 7 buttons as shown in the Figure.

Figure 10.17a Block program of the project

● 272

MIT App Inventer UK 200311.indd 272

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

Figure 10.17b cont… Figure 10.18 shows the QR code of the project.

Figure 10.18 QR code of the project Arduino UNO Program: Figure 10.19 shows the Arduino UNO program (Arduino4_Relay). At the beginning of the program, inputs IN1, IN2, IN3 and IN4 of the relay 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 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:

*

Author: Dogan Ibrahim

Arduino4_Relay

*

Date:

February 2020

*********************************************************************/ #include

// Include serial

#define TIMOUT 6000

// Timeout 6 secs

● 273

MIT App Inventer UK 200311.indd 273

03-04-20 10:38

MIT App Inventor Projects

char ch; int IN1 = 8;

// Relay IN1

int IN2 = 9;

// Relay IN2

int IN3 = 10;

// Relay IN3

int IN4 = 11;

// Relay IN4

SoftwareSerial wifi(6, 7);

// RX, TX

// // 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

digitalWrite(IN1, HIGH);

// Relay1 OFF

digitalWrite(IN2, HIGH);

// Relay2 OFF

digitalWrite(IN3, HIGH);

// Relay3 OFF

digitalWrite(IN4, HIGH);

// RElay4 OFF

wifi.begin(115200);

// ESP-01 Baud rate

SendCmd("AT+RST", "Ready");

// Reset ESP-01

delay(5000); SendCmd("AT+CWMODE=1","OK");

//

SendCmd("AT+CIFSR", "OK");

//

SendCmd("AT+CIPMUX=1","OK");

//

SendCmd("AT+CIPSERVER=1,80","OK");

//

} void loop() { String received=""; while (wifi.available())

// While there is data

{ received = wifi.readString();

// Read data

if (received.indexOf("/on1") != -1)

// Data contains /on1

digitalWrite(IN1, LOW); else if(received.indexOf("/off1") != -1) digitalWrite(IN1, HIGH); else if(received.indexOf("/on2") != -1)

// Relay1 ON // Data contains /off1 // Relay1 OFF // Data contains /on2

● 274

MIT App Inventer UK 200311.indd 274

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

digitalWrite(IN2, LOW); else if(received.indexOf("/off2") != -1) digitalWrite(IN2, HIGH); else if(received.indexOf("/on3") != -1) digitalWrite(IN3, LOW); else if(received.indexOf("/off3") != -1) digitalWrite(IN3, HIGH); else if(received.indexOf("/on4") != -1) digitalWrite(IN4, LOW); else if(received.indexOf("/off4") != -1) digitalWrite(IN4, HIGH);

// Relay2 ON // Data contains /off2 // Relay2 OFF // Data contains /on3 // Relay3 ON // Data contains /off3 // Relay3 OFF // Data contains /on4 // Relay4 ON // Data contains /off4 // RElay4 OFF

} } // // 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

if (ch == retword[cnt])

// Check return

cnt++;

● 275

MIT App Inventer UK 200311.indd 275

03-04-20 10:38

MIT App Inventor Projects

if (cnt == retword_length) return true;

// End of check? // Return word

received } } return false;

// Return word not

received }

Figure 10.19 Arduino UNO program (Arduino4_Relay) listing

To test the program: • Power-up the circuit • Compile the Arduino program and upload it to the Arduino UNO • Build the App Inventor program after entering the IP address of the ESP-01 processor, 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. An example run on the Android mobile phone is shown in Figure 10.20.

Figure 10.20 Example run on the Android mobile phone

● 276

MIT App Inventer UK 200311.indd 276

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

10.5 Project 3 – Speech Control of a 4 Channel Relay Module 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: • Create a new project and name it as ARDUINO_SPEECH4 • Insert a HorizontalArrangement and insert a Label on it with its Text set to RELAY SPEECH CONTROLLER • Insert a HorizontalArrangement and insert a Button on it with the name ButtonStart • Insert a SpeechRecognizer component on the Viewer • Insert a WebViewer component and unclick its visible box so that it is not visible

Figure 10.21 Design of the project 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 processor 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

MIT App Inventer UK 200311.indd 277

03-04-20 10:38

MIT App Inventor Projects

• Click SpeechRecognizer1.AfterGettingText. This block will be executed after the end of the speech command. Here, we have to compare the speech with the expected commands and then send the corresponding command to the Android mobile phone to activate/deactivate a relay. It is assumed that the following equipment is connected to two relay channels; Relay Channel 1 1 2 2

Equipment Connected heater heater boiler boiler

Valid Commands heater on heater off boiler on boiler off

• Variable speech is compared with the spoken command. If for example, the spoken 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.

Figure 10.22 Block program of the project The QR code of the project is shown in Figure 10.23.

● 278

MIT App Inventer UK 200311.indd 278

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

Figure 10.23 QR code of the project Arduino UNO Program: This program is the same as the one given in Figure 10.19. To test the program: • Power-up the circuit • Compile the Arduino program and upload it to the Arduino UNO • Build the App Inventor program after entering the IP address of the ESP-01 processor, 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. 10.6 Project 4 – UDP Based Control – LED Control Description: In this project, an LED is connected to the Arduino UNO and the LED is controlled from the Android mobile phone using the UDP protocol. This is a very simple project. The aim here has been to show how UDP can be used to establish communication between an Android device and the Arduino UNO. 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 handshaking and thus guarantees the delivery of packets to the required destination. UDP, on the other hand, is not so reliable but is a fast protocol. Table 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

Table 10.1 Comparison of UDP and TCP

● 279

MIT App Inventer UK 200311.indd 279

03-04-20 10:38

MIT App Inventor Projects

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 Extensions 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: • Create a new project and name it as LED_UDP • Insert the title UDP CONTROLLER • Insert a HorizontalArrangement and insert two Buttons on it with the names ButtonON and ButtonOFF. Clicking ButtonON (LED ON) will turn ON the LED. Similarly, clicking ButtonOFF (LED OFF) will turn OFF the LED • Insert a ClientUDP component on the Viewer. This is a hidden component and is only shown at the bottom of the phone image.

Figure 10.24 Design of the project

● 280

MIT App Inventer UK 200311.indd 280

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

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 ButtonON and select when ButtonON.Click do. • Click ClientUDP1 and select call ClientUDP1.Send. Fill in the ip address, port number, broadcast (false), the message, and the timeout. Here, message LEDON# will be sent to the Arduino UNO to turn OFF the LED (# is used as the terminator character). Set the timeout to 5000. • Repeat above for the ButtonOFF

Figure 10.25 Block program of the project Figure 10.26 shows the QR code of the project.

Figure 10.26 QR code of the project

● 281

MIT App Inventer UK 200311.indd 281

03-04-20 10:38

MIT App Inventor Projects

Arduino Uno Program: This program is based on sockets. Figure 10.27 shows the program 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 WiFi 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 contains 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:

*

Author: Dogan Ibrahim

Arduino_UDP

*

Date:

March 2020

*********************************************************************/ #include

// 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

MIT App Inventer UK 200311.indd 282

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

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 0)

// LEDON detected

digitalWrite(LED, HIGH); else if(strstr(buf, "LEDOFF") > 0) digitalWrite(LED, LOW);

// LED ON // LEDOFF detected // LED OFF

}

Figure 10.27 Arduino UNO program (Arduino_UDP) of the project 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. 10.7 Project 5 – UDP Based Control – Digital Thermometer Description: In this project, an analog sensor is connected to the Arduino UNO. The ambient 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.

Figure 10.28 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

MIT App Inventer UK 200311.indd 283

03-04-20 10:38

MIT App Inventor Projects

Figure 10.29 Circuit diagram of the project App Inventor Program: In this project, we will be using a more sophisticated UDP component 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. The steps are (see Figure 10.30): • Create a new project and name it as UDP_TEMP Insert a VerticalArrangement. Insert a thermometer image, a Label, and a TextBox on the VerticalArrangement. Set the Label Text to TEMPERATURE (C) and its FontSize to 35. Set the name of the TextBox to TxtTemperature and its FontSize to 50. Set the BackgroundColor of the TextBox to be the same as the BackgroundColour of the VerticalArrangement (Yellow) so that the borders of the TextBox are not visible. Insert a UrsAI2UDPv31 component onto the Viewer. This is a hidden component and is only visible outside the phone image.

● 284

MIT App Inventer UK 200311.indd 284

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

Figure 10.30 Design of the project 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. • Click UrsAI2UDPv31 and select when UrsAAI2UDPv31.DataReceived. This block will be activated when data is received from the Arduino UNO via the UDP. Load the received data into TxtTemperature so that the temperature is displayed by the TextBox. Notice that to display the degree sign, press Alt and then enter 0176 while keeping Alt pressed.

Figure 10.31 Block program of the project Figure 10.32 shows the QR code of the project.

Figure 10.32 QR code of the project

● 285

MIT App Inventer UK 200311.indd 285

03-04-20 10:38

MIT App Inventor Projects

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 Android 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

// Include serial

int val, l, temp = A0; String tempc, Dt; SoftwareSerial wifi(6, 7);

// RX, TX

// // 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

MIT App Inventer UK 200311.indd 286

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

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.

Figure 10.34 Example run of the program

● 287

MIT App Inventer UK 200311.indd 287

03-04-20 10:38

MIT App Inventor Projects

10.8 Project 6 – UDP Based Control – Speaking Thermometer 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 Figure 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.

Figure 10.35 Block program of the project Figure 10.36 shows the QR code of the project.

Figure 10.36 QR code of the project 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

MIT App Inventer UK 200311.indd 288

03-04-20 10:38

Chapter 10 • Arduino Wi-Fi based projects using MIT App Inventor

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 Arduino UNO and Android mobile phone. In the next chapter, we will develop App Inventor based projects using ESP32.

● 289

MIT App Inventer UK 200311.indd 289

03-04-20 10:38

MIT App Inventor Projects

Chapter 11 • ESP32 based projects using the MIT App Inventor 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 created, 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. 11.2 ESP32 DevKitC Hardware ESP32 DevKitC is a small ESP32 processor-based board developed and manufactured by Espressif. As shown in Figure 11.1, the board is breadboard compatible and has the dimensions 55 mm x 27.9 mm.

Figure 11.1 ESP32 DevKitC development 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

MIT App Inventer UK 200311.indd 290

03-04-20 10:38

Chapter 11 • ESP32 based projects using the MIT App Inventor

Figure 11.2 ESP32 DevKitC connectors 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 functions of each pin.

● 291

MIT App Inventer UK 200311.indd 291

03-04-20 10:38

MIT App Inventor Projects

Figure 11.3 Multiple functions of each pin. Source: www.cnx-software.com Note that GPIO34, GPIO35, GPIO36, GPIO37, GPIO38, and GPIO39 ports are input only and cannot be used as output ports (GPIO37 and GPIO38 are not available 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. 11.3 Arduino IDE for The ESP32 DevKitC By default, the ESP32 DevKitC is distributed with no programming firmware installed. It is, therefore, necessary to install a programming language firmware on the processor so that user programs can be developed and uploaded to the processor. The ESP32 processor is compatible with various programming languages such as C, MicroPython and so on. Arduino IDE is one of the most commonly used development environments for microcontrollers, 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. 11.3.1 Installing the Arduino IDE for the ESP32 DevKitC The steps on installing the ESP32 support to the Arduino IDE on a Windows PC are given in this section. If you have already installed ESP32 on Arduino IDE then you must delete the Espressif folder from your Arduino directory before re-installing it.

● 292

MIT App Inventer UK 200311.indd 292

03-04-20 10:38

Chapter 11 • ESP32 based projects using the MIT App Inventor

The steps to install the ESP32 on Arduino IDE are as follows: • 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

Figure 11.4 Preferences window • Click OK • Click Tools -> Boards -> Board Managers window and search for ESP32 as shown in Figure 11.5

Figure 11.5 Search for ESP32 • Click the Install button. You should see the installed message as shown in Figure 11.6. Close the window.

● 293

MIT App Inventer UK 200311.indd 293

03-04-20 10:38

MIT App Inventor Projects

Figure 11.6 ESP32 installed • 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.

Figure 11.7 Select the ESP32 Dev Module 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. 11.4 Project 1 – Controlling an LED – Bluetooth Communication 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

MIT App Inventer UK 200311.indd 294

03-04-20 10:38

Chapter 11 • ESP32 based projects using the MIT App Inventor

Figure 11.8 Block diagram of the project Circuit Diagram: Figure 11.9 shows the circuit diagram of the project.

Figure 11.9 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) listing, developed using the Arduino IDE. At the beginning of the program header file, BluetoothSerial 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

MIT App Inventer UK 200311.indd 295

03-04-20 10:38

MIT App Inventor Projects

* Date:

March 2020

*********************************************************************/ #include"BluetoothSerial.h"

// Include Bluetooth

BluetoothSerial BT; int LED = 23;

// LED port

String rd; // // 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); else if(rd.indexOf("0") != -1) digitalWrite(LED, LOW);

// LED ON // Contains "0"? // LED OFF

} }

Figure 11.10 ESP32 DevKitC program (ESP32_LED) listing Testing the program: • Install App Inventor on your Android mobile phone (Figure 6.4) • Build the circuit and connect the ESP32 DevKitC to your PC • 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

MIT App Inventer UK 200311.indd 296

03-04-20 10:38

Chapter 11 • ESP32 based projects using the MIT App Inventor

Figure 11.11 Device LEDBT displayed • 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. • Click LED ON. You should see the LED turning ON

Figure 11.12 Select LEDBT 11.5 Project 2 – Speech Control of an LED – Bluetooth Communication Description: In this project, an LED is connected to the ESP32 DevKitC as in the previous project. The LED is controlled from the Android mobile phone by speech as follows (notice that LED should be pronounced as l e d and not as led):

To turn ON the LED the user should speak: LED on 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

MIT App Inventer UK 200311.indd 297

03-04-20 10:39

MIT App Inventor Projects

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): • Install App Inventor on your Android mobile phone (Figure 6.12) • Build the circuit and connect the ESP32 DevKitC to your PC • 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 • The green Connected message should be displayed. • Click the Start button and allow audio. Speak the command when the microphone is enabled (Figure 11.13). You should click the Start button again to send another command.

Figure 11.13 Speak the command

● 298

MIT App Inventer UK 200311.indd 298

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

11.6 Project 3 – Controlling a 4 Channel Relay Module – Bluetooth Communication 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.

Figure 11.14 Block diagram of the project Circuit Diagram: Figure 11.15 shows the circuit diagram of the project.

Figure 11.15 Circuit diagram of the project App Inventor Program: The App Inventor program is the same as the one given in Project 2 in Chapter 9.6 (program: Arduino_Relay4). If you have already designed this project, 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: Command 1on 1off 2on 2off 3on 3off 4on 4off

Relay Action RELAY1 ON RELAY1 OFF RELAY2 ON RELAY2 OFF RELAY3 ON RELAY3 OFF RELAY4 ON RELAY4 OFF

● 299

MIT App Inventer UK 200311.indd 299

03-04-20 10:39

MIT App Inventor Projects

ESP32 DevKitC Program: Figure 11.16 shows the ESP32 DevKitC program (ESP32Rel4). 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; int IN1 = 19;

// IN1 pin

int IN2 = 18;

// IN2 pin

int IN3 = 5;

// IN3 pin

int IN4 = 17;

// IN4 pin

String rd; // // 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

digitalWrite(IN1, HIGH);

// Channel 1 OFF

digitalWrite(IN2, HIGH);

// Channel 2 OFF

digitalWrite(IN3, HIGH);

// Channel 3 is OFF

digitalWrite(IN4, HIGH);

// Channel 4 is OFF

BT.begin("LEDBT");

// Initialize

}

● 300

MIT App Inventer UK 200311.indd 300

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

void loop() { if(BT.available())

// Data available?

{ rd = BT.readString();

// Read data

if(rd == "1on")

// 1on?

digitalWrite(IN1, LOW); else if(rd == "1off") digitalWrite(IN1, HIGH); else if(rd == "2on") digitalWrite(IN2, LOW); else if(rd == "2off") digitalWrite(IN2, HIGH); else if(rd == "3on") digitalWrite(IN3, LOW); else if(rd == "3off") digitalWrite(IN3, HIGH); else if(rd == "4on") digitalWrite(IN4, LOW); else if(rd == "4off") digitalWrite(IN4, HIGH);

// Channel 1 ON // 1off? // Channel1 OFF // 2on? // Channel 2 ON // 2off? // Channel 2 OFF // 3on? // Channel 3 ON // 3off? // Channel 3 OFF // 4on? // Channel 4 ON // 4off? // Channel 4 OFF

} }

Figure 11.16 ESP32 DevKitC program (ESP32-Rel4) of the project 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: • Create a new project and name it as Arduino_Relay4_2 • Insert a VerticalArrangement and the Bluetooth controls LblStatus and ListPicker as in the previous Bluetooth based projects

● 301

MIT App Inventer UK 200311.indd 301

03-04-20 10:39

MIT App Inventor Projects

• Insert 4 HorizontalArrangements and insert a Switch component (from User Interface) on each HorizontalArrangement. Configure the Switch components as follows: Name

FontBold FontSize Text

ThumbColorInactive TrackColorActive

RELAY1 ticked

20

RELAY1 Blue

Red

RELAY2 ticked

20

RELAY2 Blue

Red

RELAY3 ticked

20

RELAY3 Blue

Red

RELAY4 ticked

20

RELAY4 Blue

Red

• Insert a BluetoothClient and a Clock component on the Viewer.

Figure 11.17 Design of the project 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 projects • Click RELAY1 and select when RELAY1.Changed do. This block will be executed when RELAY1 is clicked. • Check if the Bluetooth connection has already been established. • Insert an if-then block • Insert an if-then-else block

● 302

MIT App Inventer UK 200311.indd 302

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

• Click RELAY1 and select RELAY1.On. If the state of RELAY1 is On, click BluetoothClient1 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 • Repeat the above for all 4 relays

Figure 11.18a Block program of the project

Figure 11.18b cont…

● 303

MIT App Inventer UK 200311.indd 303

03-04-20 10:39

MIT App Inventor Projects

Figure 11.19 shows the QR code of the project.

Figure 11.19 QR code of the project 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.

Figure 11.20 Example run of the program on Android mobile phone 11.8 Project 5 – Displaying the Ambient Temperature – Bluetooth Communication 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

MIT App Inventer UK 200311.indd 304

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

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.

Figure 11.21 Pin layout of TMP36 temperature sensor chip Block Diagram: The block diagram of the project is shown in Figure 11.22.

Figure 11.22 Block diagram of the project 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.

Figure 11.23 Circuit diagram of the project 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

MIT App Inventer UK 200311.indd 305

03-04-20 10:39

MIT App Inventor Projects

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; #define TMP36 34

// TMP36 pin

// // 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

}

Figure 11.24 ESP32 DevKitC program (ESP32_TMP36) of the project

● 306

MIT App Inventer UK 200311.indd 306

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

Figure 11.25 Example display on the Android mobile phone 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. Background Information: I2C is a multi-slave, multi-master, single-ended serial bus used to attach low-speed peripheral devices to microcontrollers. The bus consists of only two wires called SDA and SCL where SDA is the data line and SCL is the clock line and up to 1008 slave devices can be supported on the bus. Both lines must be pulled up to the supply voltage by suitable resistors. The clock signal is always generated by the bus master. The devices on the I2C bus can communicate at 100 kHz or 400 kHz. 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 potentiometer mounted on this board. A jumper is provided on this board to disable the backlight if required.

Figure 11.26 I2C compatible LCD (front and back views)

● 307

MIT App Inventer UK 200311.indd 307

03-04-20 10:39

MIT App Inventor Projects

Block Diagram: The block diagram of the project is shown in Figure 11.27.

Figure 11.27 Block diagram of the project 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.

Figure 11.28 Circuit diagram of the project App Inventor Program: Figure 11.29 shows the App Inventor design. The steps are: • Create a new project and name it as LightMeter • Insert a VerticalArrangement and the Bluetooth controls LblStatus and ListPicker as in the previous Bluetooth based projects • Insert a Label with the Text set to AMBIENT LIGHT (Lux) on a HorizontalArrangement • Insert a HorizontalArrangement and insert a TextBox named TxtPressure on it. This TextBox will display the ambient air pressure. Set the BackgroundColor of the TextBox to be the same as the BackgoundColor of the HorizontalArrangement so that the background colour of the TextBox is not visible. • Insert the following components on the Viewer: BluetoothClient, two Clocks, and a LightSensor (under tab Sensors). Name one of the Clocks as TempClock where this will send the pressure readings to the ESP32 DevKitC processor periodically.

● 308

MIT App Inventer UK 200311.indd 308

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

Figure 11.29 Design of the project 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 projects • 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.

Figure 11.30 Block program of the project

● 309

MIT App Inventer UK 200311.indd 309

03-04-20 10:39

MIT App Inventor Projects

The QR code of the project is shown in Figure 11.31.

Figure 11.31 QR code of the project 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 download and include the I2C LCD library in our Arduino IDE folder. The steps to do this are given below: • Create a folder named LiquidCrystal_I2C under the folder named libraries in your Arduino IDE folder. • Go to the following link to download the I2C LCD library:

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 LiquidCrystal_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 configured 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

MIT App Inventer UK 200311.indd 310

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

#include"BluetoothSerial.h"

// Include Bluetooth

#include #include BluetoothSerial BT; // // Set the LCD address to 0x27 and the configuration to // 16 chars and 2 rows display // LiquidCrystal_I2C lcd(0x27, 16, 2);

// LCD address 0x27

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 displayed on the LCD is shown in Figure 11.34.

● 311

MIT App Inventer UK 200311.indd 311

03-04-20 10:39

MIT App Inventor Projects

Figure 11.33 Data displayed on the Android mobile phone

Figure 11.34 Data displayed on the LCD 11.10 Project 7 – Controlling an LED – Wi-Fi Communication 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 replaced 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.

Figure 11.35 Block diagram of the project

● 312

MIT App Inventer UK 200311.indd 312

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

Circuit Diagram: Figure 11.36 shows the circuit diagram of the project. The LED is connected to port IO23 through 330 Ohm current limiting resistor.

Figure 11.36 Circuit diagram of the project App Inventor Program: The App Inventor program is the same as the one given in Project 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. ESP32 DevKitC Program: The program (ESP32_UDP) listing is shown 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

MIT App Inventer UK 200311.indd 313

03-04-20 10:39

MIT App Inventor Projects

/********************************************************************** *

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 #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

MIT App Inventer UK 200311.indd 314

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

{ 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); if(Packet[0]='L' && Packet[1] == 'E' && Packet[2]=='D' && Packet[3]=='O') { if(Packet[4]=='N') { digitalWrite(LED, HIGH); } else if(Packet[4]=='F' && Packet[5]=='F') { digitalWrite(LED, LOW); } } } }

Figure 11.37 ESP32 DevKitC program (ESP32_UDP) of the project 11.11 Project 8 – Speaking Thermometer – Wi-Fi Communication 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

MIT App Inventer UK 200311.indd 315

03-04-20 10:39

MIT App Inventor Projects

Block Diagram: The block diagram of the project is shown in Figure 11.38.

Figure 11.38 Block diagram of the project 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 Project 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 temperature 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

MIT App Inventer UK 200311.indd 316

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

* * File:

ESP32_SPEECH

* Author: Dogan Ibrahim * Date:

March 2020

*********************************************************************/ #include "WiFi.h" #include 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

MIT App Inventer UK 200311.indd 317

03-04-20 10:39

MIT App Inventor Projects

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

udp.beginPacket(remote_IP, remote_port);

// Remote IP and port

udp.print(tempc);

// Send temperature

udp.endPacket(); delay(5000);

// WAit 5 secs

}

Figure 11.39 ESP32 DevKitC program (ESP32_SPEECH) listing

Figure 11.40 Temperature displayed on the Android mobile phone 11.12 Project 9 – Saving the Temperature Data – Wi-Fi Communication 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

MIT App Inventer UK 200311.indd 318

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

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 new project and name it as TEMP_SAVE • Create a VerticalArrangement with its Height set to 30 percent, and insert a Label on it with its Text set to TEMPERATURE (C). Also, insert a TextBox on it with the name TxtTemperature, and FontSize set to 45, Height 15 percent. • Create a TextBox named TextBox1, set the FontSize to 18, Height 40%, and MultiLine ticked. Clear fields Hint and Text • Insert a HorizontalArrangement and insert a Button on it with the name ButtonSave. Clicking this button will display the saved data • Insert components UrsAI2UDPv31, File, and Clock. Make sure that the Clock TimerInterval is set to 1000ms in the properties.

Figure 11.41 Design of the project Figure 11.42 shows the block program of the project. The steps are: • Initialize 3 variables: timenow, filename, dummy. timenow will store the current time, filename will store the name of the file where we wish to store the data.

● 319

MIT App Inventer UK 200311.indd 319

03-04-20 10:39

MIT App Inventor Projects

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

Figure 11.42 Block program of the project

● 320

MIT App Inventer UK 200311.indd 320

03-04-20 10:39

Chapter 11 • ESP32 based projects using the MIT App Inventor

The QR code of the project is shown in Figure 11.43.

Figure 11.43 QR code of the project 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.

Figure 11.44 Example output on the Android mobile phone 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. Readers should find it very easy to modify these projects to suit their own applications.

● 321

MIT App Inventer UK 200311.indd 321

03-04-20 10:39

MIT App Inventor Projects

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 languages 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 Inventor. 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

MIT App Inventer UK 200311.indd 322

03-04-20 10:39

Appendix A • Exercises

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 numbers 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 degrees 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 remotely. 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 Raspberry Pi 4 computer). 2. Develop an MIT App Inventor application to read the acceleration in the X direction from your mobile phone. Send this reading to the Raspberry Pi 4 computer 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 application 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 Inventer UK 200311.indd 323

03-04-20 10:39

MIT App Inventor Projects

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 commands. 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 using 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 communication. 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

MIT App Inventer UK 200311.indd 324

03-04-20 10:39

Appendix A • Exercises

7. What other Wi-Fi modules can you use instead of the ESP-01 to give Wi-Fi connectivity 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 connected 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 Inventor. 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

MIT App Inventer UK 200311.indd 325

03-04-20 10:39

MIT App Inventor Projects

Appendix B • Using the MIT App Inventor offline 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 Inventor 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. B.2 Installing the App Inventor Ultimate The steps to install App Inventor Ultimate are as follows (the filenames given below may change as they were valid at the time of writing this book): • Make sure that you have Java installed on your computer • Go to the following web site:

http://sourceforge.net/projects/ai2u/files/

• Click on the latest version. e.g. ai2u 4.6 (see Figure B.1)

Figure B.1 Click on the latest version • Click on Installer • Download file AI2Starter46.exe and depending on your computer, download either the 32-bit or the 64-bit version of the other file. The author had a 64-bit computer and hence file AI2U 64bit v4.6.exe was downloaded (see Figure B.2)

Figure B.2 Download files

● 326

MIT App Inventer UK 200311.indd 326

03-04-20 10:39

Appendix A • Exercises

• 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 welcome message as shown in Figure B.3

Figure B.3 App Inventor welcome message screen • Click to use your Google Account to log in • Click Login and accept the conditions • 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

MIT App Inventer UK 200311.indd 327

03-04-20 10:39

MIT App Inventor Projects

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

MIT App Inventer UK 200311.indd 328

03-04-20 10:39

Appendix C • Loading the programs from the book website

Appendix C • Loading the programs from the book website C.1 File Extensions All the programs shown in the book can be downloaded from the book web site. The programs in the web site have the following file extensions: .aia .py Folders .jpg .mp3

- MIT App Inventor program - Python 3 program - Arduino UNO and ESP32 DevKitC programs. ESP32 DevKitC folder names start with ESP32 - Images used in MIT App Inventor programs - audio files used in MIT App Inventor programs

C.2 Loading MIT App Inventor Programs The steps to load MIT App Inventor programs are (assuming that all the programs are on your computer, e.g. on a flash memory drive): • Start the MIT App Inventor • Click My Projects • Click Import project (.aia) from my computer • Browse and click OK to load the program C.3 Loading Android UNO Programs The steps to load an Arduino UNO program are: • Start the Arduino IDE • Click Tools and select board Arduino Uno • Click File and then Open. Browse and select the required file from the book web site C.4 Loading ESP32 DevKitC Programs The steps to load an ESP32 DevKitC program are: • Start Arduino IDE • Click Tools and select ESP32 Dev Module • Click File and then Open. Browse and select the required file from the book web site

● 329

MIT App Inventer UK 200311.indd 329

03-04-20 10:39

MIT App Inventor Projects

Appendix D • MIT App Inventor extension components 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. MIT App Inventor extensions have the filename extensions .aix The steps to include an extension in your project are: • Start MIT App Inventor • Click tab Extension at the bottom left-hand side • Click Import extension • Browse to the site where the extension is and click OK to download the required extension • You should see the downloaded extension in your Extension tab The following web sites include large numbers of Extension components: https://puravidaapps.com/extensions.php https://community.thunkable.com/t/index-of-available-extensions/2680

● 330

MIT App Inventer UK 200311.indd 330

03-04-20 10:39

Appendix E •

Appendix E • List of components used in the book • 4 • 4 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 1 • 6 • 6 • 1

x x x x x x x x x x x x x x x x x x x x x

LED 470 Ohm resistor 330 Ohm resistor 1K resistor 2K resistor 100 Ohm resistor small DC motor DHT11 sensor small 1N4148 diode 4-way relay module (Elegoo) HC-06 Bluetooth module parallel LCD I2C LCD LM35DZ sensor chip small stepper motor (28BYJ-48) stepper motor driver board (ULN2003 based) ESP-01 processor NPN transistor F-M jumper wires M-M jumper wires small breadboard

Processors used • Raspberry Pi 4 • Arduino UNO • ESP32 DevKitC

● 331

MIT App Inventer UK 200311.indd 331

03-04-20 10:39

MIT App Inventor Projects

Index A Acceleration 65 AI2 Companion 17, 20 aiStarter 25 Arduino Uno 201 B Bell sound 28 Bipolar stepper 249 Blocks 15 Bluetooth 129, 203, 294 Boot 291 Buster 106 Button 32 C Chronograph 81 Command mode 115 Command prompt 114 Contact list 58 Counter 84 CPU fan 105 CSI port 103 D Date 75 DC motor 155 Designer 15 Desktop 108 DHT11 161, 234 Dice 93 Digital thermometer 283 DSI port 103 E Emulator 24 EN 291 English to German 42 ESP-01 259 ESP32 290 ESP32 DevKitC 290 Etcher 107 Ethernet 103 Export project 31

Extensions 330 F Fixed telephone number 56 Formatting 35 Full-step mode 254 G Global positioning system 70 GPIO 122 GPIO library 123 GPS 70 H Half-step mode 254 HC-05 203 HC-06 203 H135ciconfig HDMI 103 Humidity 160, 189 I I2C 308 I2C LCD 307 Images 43 Import project 31 Interrupt 125 L Label 32 LCD 307 Light level 68 LM35DZ 229 Loading programs 329 M Map 72 Motor shaft 250 Motor driver 251 Multiple LEDs 145, 152 N Nano 115 Node-RED 194

● 332

MIT App Inventer UK 200311.indd 332

03-04-20 10:39

Index

O Offline 326 ON-OFF control 239 P Parallel interface 122 Password protection 169 Play 77 PoE port 103 Pin numbering 123 Procedures 100 Putty 110 Python 114 PWM 156 Q Quiz 94 R RAM 103 Random number 93 Raspberry Pi 4 102 Record 77 Relay 181, 207, 214 Remote access 112 RPM 255

S Save 31 Scratch 13 SendMessage 47 Sending text 221 Share 32 SMS 47, 50 Sound output 138, 152 Speech command 140 Speech control 277 Speech recognizer 79 Speed control 155 SSH 110 StarLogo 15 Stepper motor 248 T Taking picture

TCP 279 Telephone number 55 Temperature 160, 189, 228 Temperature control 239 TextBox 32 Text editor 115 Text To Speech 37 Thonny 119 TightVNC 113 Time 75 Time table 98 TMP36 305 Trash 31 Trigonometric function 96 U UDP 279, 283, 288 ULN2003 251 Unipolar stepper 248 USB keyboard 104 USB port 103 V VNC 110 VNC server 112 W Weather 234 Web server 177, 181, 194 Wi-Fi 174, 312 Q QR code

17

Y YandexTranslate 34

59

● 333

MIT App Inventer UK 200311.indd 333

03-04-20 10:39

MIT App Inventor Projects

Elektor International Media

www.elektor.com

The projects developed in this book include: • • • • • •

Using the text-to-speech component Intonating a received SMS message Sending SMS messages Making telephone calls using a contacts list Using the GPS and Pin-pointing our location on a map Speech recognition and speech translation to another language • Controlling multiple relays by speech commands • Projects for the Raspberry Pi, ESP32 and Arduino using Bluetooth and Wi-Fi • MIT APP Inventor and Node-RED projects for the Raspberry Pi

MIT App Inventor Projects

MIT App Inventor Projects

ISBN 978-1-907920-89-9

In this book, many tested and fully working projects are given both in standalone mode and using an external processor. Full design steps, block programs, circuit diagrams, QR codes and full program listings are given for all projects.

50+ Apps with Raspberry Pi, ESP32 and Arduino



Prof. Dr. Dogan Ibrahim has a BSc. in Electronic Engineering, an MSc. in Automatic Control Engineering, and a Ph.D. in Digital Signal Processing. He worked in many industrial organisations before returning to academia. Prof. Ibrahim is the author of over 60 technical books and over 200 technical articles on microcontrollers, microprocessors, and related fields. He is a Chartered Electrical Engineer and a Fellow of the Institution of Engineering Technology.

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 communicates with an external microcontroller-based processor, such as Raspberry Pi, Arduino, ESP8266, ESP32, etc.

Dogan Ibrahim

50+ Apps with Raspberry Pi, ESP32 and Arduino

The book is unique in that it is currently the only book that teaches how to develop projects using Wi-Fi and Node-RED with MIT App Inventor. The book is aimed at students, hobbyists, and anyone interested in developing apps for mobile devices. 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 the book. Users should be able to use the projects as they are presented, modifying them to suit their own needs.

LEARN DESIGN SHARE

Dogan Ibrahim 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 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 ●

Cover MIT App Inventer UK 200311.indd Alle pagina's

03-04-20 10:25