0% found this document useful (0 votes)
9 views18 pages

23oct 44IOTG Lab 1

The document outlines the objectives and procedures for Lab 1 at Ngee Ann Polytechnic's School of Engineering, focusing on the development board and environment setup for Internet of Things (IoT) applications using the ESP32 microcontroller. It covers the setup of the Arduino IDE, understanding the hardware and software components of embedded systems, and provides instructions for testing the kitset and ensuring proper driver installation. Additionally, it includes preparation questions and information about the ESP32's capabilities and connections for IoT applications.

Uploaded by

danzel1585
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

23oct 44IOTG Lab 1

The document outlines the objectives and procedures for Lab 1 at Ngee Ann Polytechnic's School of Engineering, focusing on the development board and environment setup for Internet of Things (IoT) applications using the ESP32 microcontroller. It covers the setup of the Arduino IDE, understanding the hardware and software components of embedded systems, and provides instructions for testing the kitset and ensuring proper driver installation. Additionally, it includes preparation questions and information about the ESP32's capabilities and connections for IoT applications.

Uploaded by

danzel1585
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Ngee Ann Polytechnic

School of Engineering
Internet of Things (IoT) 44IOTG-012628

LAB 1: Development Board and Environment Setup 221028a


Understand embedded systems, our development board & environment

Name: ____________________________________________ Lab Grp: ___________ Date: ____________


IMPORTANT:
 Show your completed PREPARATION section to your supervisor
 Complete the open-book lab 2 quiz.

OBJECTIVES
 Setup Arduino IDE for the target MCU
 Understand the Arduino environment
 Understand IO pins on the target MCU board
 Use the Serial monitor for program testing and debugging
 Observe the problem of delay() for a responsive system
 Try out a responsive demo program

EQUIPMENT
 Sign out for the semester: ESP32 IoT kitset + LED-PB board + Grove potentiometer + USB cable
 I2C Expansion board with OLED, RTC & MPU6050 for use during the lab session only
 AC lamp with Grove control (very limited units)

PREPARATION

1. Processor based system hardware and software


An embedded system is a program-controlled system consisting of
1. Hardware: Physical part of the system that you can see and feel.
2. Software: The logical program executed by the hardware and is “invisible”.

Hardware
The hardware includes system mechanical casing, power and various connections, if any, user input (e.g.
buttons, keyboard, touch screen) and outputs (LED, displays).
Below is a “teardown” of a mobile phone which is a often part of an IoT system. It is both an embedded
system and a powerful computer. It has connectivity through WiFi and Bluetooth. There are printed circuit
boards (PCBs) that connect components together, wiring and mechanical parts.

IOTG Lab 1 Oct 2023 Page 1 of 18


Source: https://www.ifixit.com/Teardown/iPhone+13+Pro+Teardown/144928

Processor-based System Architecture


The basic processor based system architecture consists of CPU (Central Processing Unit), memory, input-
output (IO) interfaces as shown below.

Memory: IO Mass Storage


CPU
ROM & RAM Interface USB interface to
external devices,
Address bus etc
Data bus
Control bus
The CPU communicates with other components through address, data and control buses. Many advanced
microcontroller units (MCUs) integrate CPU, memory and advanced IO interfaces into a single chip, called
System-On-a-Chip (SOC).

Software
Once you have a reliable hardware, the system intelligence and reliability are determined by the software
run by the processor. Software is an extremely important part of modern electronic systems.
Software makes the system very versatile. It can be easily updated without changing the hardware to
enhance the system behaviour, performance, or remove software bugs (errors). On the other hand, any
hardware change is very costly involving a recall and physical modifications that require specialized skills.

CPU
Many modern SOC has multiple CPUs in a single chip, allowing multiple tasks to be run in parallel
simultaneously. These are called multi-core processor. This feature speeds up the execution of programs,
improves the system performance. More advanced unit has multi-core GPUs (Graphics Processing Unit).

Memory
There are two types of memory: ROM, a read-only memory, is typically a “Flash Memory”, and RAM, a
read-write memory. ROM are non-volatile, i.e. its contents remains when the power is switched off. RAM
are volatile as its contents are lost when the power is removed.

Firmware and Operating System

IOTG Lab 1 Oct 2023 Page 2 of 18


Upon power-up, the CPU runs the program in the ROM. This software in the ROM, the non-volatile
memory, is called “firmware”.
In higher-end systems, the firmware loads in an operating system (OS, e.g. Android) in the mass storage
(e.g. SD card) into the RAM and run it. The OS takes over the control of the whole system, managing the
system resources (memory, hardware, mass storage …) and can load in various applications in the mass
storage into the RAM to be run by the CPU. The mass storage is also used to store permanent data.
On the other hand, a simple system may not have any mass storage and only the firmware in the ROM is
run by the CPU. The SOC may contain all the necessary ROM and RAM. The permanent data can be store in
the flash memory (ROM) or “EEPROM”.
Temporal data used in a running program is usually stored in the RAM which is volatile.
QUESTION:
SOC is a “System-on-a-chip”. What is it?

What is meant by RAM is volatile?

Firmware is a software. True / False It is stored in __________________ memory


In a high-end system, the OS is loaded from the mass storage into ROM. True / False
Why hardware update is costly?

WEB SEARCH:
RAM is a read-write memory. The name “RAM” stands for __________________________
You may want to find out the differences between CPU and GPU.
The Apple A15 Bionic has ___________ 64-bit CPU cores and ________ GPU cores.

2. Our Target Processor: ESP32


The MCU used in our labs is ESP32, a low-cost high-performance processor. Refer to http://esp32.net/ and
you may watch this video: https://youtu.be/A5CB4t9sukM
QUESTION:
ESP32 has _________ cores. How much SRAM it has? ___________________
Which ESP32 built-in module will allow Internet connection? ______________________
Which built-in module can provide another wireless communication? ____________________
One of the reasons ESP32 is very suitable for IoT application is its ultra-low power (ULP) operation.
Give a reason why low-power consumption is important in IoT application?
__________________________________________________________________________________
__________________________________________________________________________________

IOTG Lab 1 Oct 2023 Page 3 of 18


The ESP32 IoT kit used in our lab is shown below. The LED-PB board is plugged into connector at G:

Main board with ESP32


B DevKitC Module Pins used

C LED-PB board
P23 P19 P18
A D
LED_R LED_Y LED_G
E
UART
F
I2C

G
I Push
Plug into here PB1 PB2 buttons
H P27 P25

A ESP32 DevKitC module; the processor is enclosed in the metallic case (WROOM32 module) with PCB
antenna.
B to F are 4-pin Grove connectors with pins shown in table below.
Grove Purpose Pin 1 2 3 4
Connectors

G0 (B) Analog in or digital IO A5 (P33) - 3V3 GND

G1 (C) Digital IO or Touch P15 (T3#) *P25 3V3 GND

G2 (D) Analog in, digital IO or Touch A4 (P32) *P27 (T7#) 3V3 GND

UART (E) or G3 UART or digital IO RX2 TX2 (P17) 3V3 GND


(P16)

I2C (F) or G4 I2C or digital IO SCL (P22) SDA (P21) 3V3 GND

* LED-PB board uses P25 and P27. # These pins can be used as touch inputs
G The LED-PB board is plug into this 8-pin header socket.
H Capacitive Touch (pin P4)
I MCU Reset Button. Press this to restart the program in the MCU. No need to do Arduino upload.

The ESP32 Module


You may refer here for the ESP32 DevKitC Module pin out:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/esp32/get-started-devkitc.html
The WROOM32 module there has 4 MBytes flash memory and 520 kBytes RAM.
Some info on the ESP32 GPIO (General Purpose IO or just IO) pins:
 In general, all GPIO pins can be used as either digital (high/low only) input or outputs (IO). Some can
be used for analog in or has other special functions, e.g. touch, PWM (Pulse-Width Modulation) and
I2C interface for sensors connection (we’ll learn this).

IOTG Lab 1 Oct 2023 Page 4 of 18


 When configured as a digital input, the pin can have an internal pull-up or pull-down resistor enabled,
and can generate interrupt to the processor.
 Exceptions: P36 and P39 (not used in our board) can only be used for digital inputs (with no internal
pull-up/down, but can generate interrupts) or analog inputs.

ESP32 and IoT


ESP32 has a lot of resources IoT applications. It allows easily connections to sensors, to collect and process
sensors data. It has built-in WiFi allowing sending or receiving data with the internet.
Sensors like motion sensor can be connected to digital inputs. Relays can be connected to the digital
outputs. Sensors like temperature and light sensors can be connected to the analog input. Some pins allow
PWM output for the motor speed or LED brightness control.
SPI, I2C and UART are wired serial communication that can communicate with sensors like the MPU6050
inertia measurement unit (IMU). Bluetooth (BLE) allows another means of wireless communication.
QUESTION:
Almost all the GPIO pins can be used for digital input or output. True / False
Some GPIO pins can be configured to be used as analog or touch input. True / False
Some GPIO pins has special alternate function like I2C, SPI or UART. True / False
Pin number for Red LED:______ Yellow LED: ______ Green LED: ______ PB1: ______ PB2: ______

3. The Arduino Environment


Host Computer & Target Processor Platform
The Arduino Integrated Development Environment (IDE) is a software tool running on a “host” computer
(e.g. Windows, Mac and Linux) for developing applications for other “target” processor platform.
Diagram below shows a host computer running the Arduino IDE. The developed program will run in the
target ESP32 processor platform. There are many hardware platforms that support Arduino.

Host computer running Arduino IDE with ESP32 add-on:


Edit program
Compile and generate codes for ESP32 processor
Download codes to target ESP32 platform
Interact with the running program thru Serial Monitor

ESP32 Target
Processor platform

C++ Cross Compiler


C++ programming language is used in the Arduino framework. C++ is a powerful object-oriented language
that makes Arduino libraries very versatile, scalable, extensible and most importantly very easy to use.
For the ESP32 processor, we will need the ESP32 compiler to generate codes for our target board. If we
have a different target, e.g. AVR processor, we would need the AVR compiler. Different processors have
different architectures and instruction sets. As these compilers generate codes not to be run on the host
computer, but on another platform, they are called cross-compilers.
In our lab, the ESP32 tools are normally store in folder below where xxx is the user name.

IOTG Lab 1 Oct 2023 Page 5 of 18


C:\Users\xxx\AppData\Local\Arduino15\packages\esp32\hardware\esp32\

Arduino IDE
The Arduino IDE allows us to edit the program, build (compile …) and upload the codes generated to the
target processor board. It also allows the developer to interact with the target board through the “Serial
Monitor”, a useful tool to verify correct program execution, and investigation error (debugging).
There are other IDEs that support Arduino programming. Examples are “Atom” and “Visual Studio Code”.

The Libraries
There are 3 sets of libraries in the Arduino IDE environment. You don’t need to bother with the first 2.
1. Standard Arduino Libraries that comes with the Arduino IDE. These libraries are general and is usable
for different hardware platforms. Example: C:\arduino-1.8.19\libraries.
2. Platform specific library that comes with the target processor installed. These libraries are specific to
the platform. In our lab, the installed ESP32 libraries are stored in (xxx is user name)
C:\Users\xxx\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.5\libraries
3. User installed library which are downloaded from various sources. These libraries can be general or
platform specific. In our lab it will be located in D:\arduino-iot\libraries
Each of the above libraries come with the C++ source codes and often with examples. It is a great learning
experience studying these codes. You can easily extend the C++ classes to meet your needs.
How to access a library in a program? Just use the include statement to include the header file in the
library subfolder. Example below includes the header found in “D:\arduino-iot\libraries\_delays”.
#include <delays.h>

Sketch = Program
The programs we write in Arduino are called “sketch” in Arduino. An usual name.
The sketches has file extension .ino and must be stored in a folder of a similar name.
For example, folder “…\xyz” must have sketch name “…\xyz\xyz.ino”
QUESTION:
Why different processor needs different compiler?
_________________________________________________________________________________
What is a cross compiler?
_________________________________________________________________________________
Where will be the location of the user library in our lab?
_______________________________________________
A program written in Arduino IDE is call a ______________________________
CHECKPOINT 1: Show to your supervisor the preparation section ________________

IOTG Lab 1 Oct 2023 Page 6 of 18


PROCEDURE

A. Testing the Kitset


Test the Kitset Using the Pre-loaded program: The kitset you sign out has a pre-loaded program that
allows you to test the given hardware.
a. Do not touch the touchpad (bottom right white circle) and do not press any of the push-Buttons.

3 LEDs and 2 Push-Buttons

Rotary potentiometer

MCU Reset Button

b. Connect the ESP32 kitset to the laptop USB port to power the unit.
c. Rotate the rotary from one extreme end to another and the 3 LEDs starts to “run” from left to
right.
d. Adjust the rotary to increase the running speed for easier observation for the next step. If the
speed can’t be changed by the rotary, repeat the above by resetting the MCU.
e. Press all these to start/stop the running LEDs: 2 push-buttons (near to the LEDs) and the touchpad.
f. Press the MCU reset button. Ensure that the program is re-started.
The above confirms that the following are working: the rotary potentiometer, 3 LEDs, 2 PBs, touchpad
and the MCU reset button. It is important that all these are working.

B. USB-UART converter driver


2. COM Port for the USB-UART: The ESP32 DevKitC has a CP2102 USB-UART converter. When you were
doing the previous step, the system might have auto-installed the device driver.
Run the Windows “Device manager”. If in order, there’s an entry in “Ports (COM & LPT)” shown below.
If not successful, see the next step.

Your COM number could be


different

For your case, it could be a different COM number. Yours is ____________________________


3. Update USB-UART Driver: If the driver was not installed properly shown below, do the following.

Download the driver from here: https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers


IOTG Lab 1 Oct 2023 Page 7 of 18
Click the “DOWNLOADS” tab and download “CP210x Universal Windows Driver”.
Unzip the file into a folder of your choice. Note the folder name as you need it to do the update.
Right click at the invalid device in the Device Manager and update it using the driver folder above. See
steps in link below. (Do not download the driver through a link there as that is a very old driver.)
https://exploreembedded.com/wiki/Cp2102_Usb-to-Serial_Driver_Installation
Write down the COM number in the space provided in the previous step.

C. Arduino IDE
You used Arduino in the past semesters. If your version is already 1.8.19 skip this section. We will not use
the recently available version 2.0 which has some major differences. You may try that on your own.
If your version is not 2.0.14, you may uninstall the older version and do the following, otherwise skip this
section. (The installation below can co-exist with the older version, however, it may be confusing.)
4. Download the IDE zip file: Go here to get the latest version of Windows Arduino IDE installation file:
https://www.arduino.cc/en/software. Scroll down to look for version 1.8.19 and download the ZIP file.

Choose ZIP file to download

5. Open the zip file using Windows File Explorer. Do not use WinRAR, WinZip nor 7zip. If necessary, right
click the zip file and select Windows File Explorer. The content is a folder shown below.
Open the ZIP file using
Windows File explorer
The content in the ZIP file is a
folder containing Arduino IDE

Select that single content “arduino-1.8.19”. Use Ctrl-C to copy (to Windows clipboard). Go to C:\ and
paste (Ctrl-V). You get “c:\arduino-1.8.19\”. We assume that your IDE is in this folder from now.

D. Shortcut at Taskbar to Arduino


6. Location of the Arduino IDE: Locate the Arduino IDE program (.exe file) in your system. Record here:
________________________________________________________________________________
Note that you need to ensure that at the View ribbon of the File Explorer, the “File name extensions”
is checked in order to view the .exe extension.

Under View Check this in order to see file


extensions

IOTG Lab 1 Oct 2023 Page 8 of 18


7. Shortcut at the Taskbar: Run the “arduino.exe”. Create a shortcut at the Windows “taskbar” (bottom
line of Windows screen) for easy quick access. (How to do it? Find out yourself.) An example:

If your Arduino is running, quit by pressing Ctrl-Q and test the shortcut at the taskbar to start Arduino.

E. ESP32 Add-on Tools


8. ESP32 Add-on & the Board: We will install ESP32 for Arduino version 2.05 (or above).

a. Set the Additional Board Manager URL: In menu “File > Preferences”, click the icon at the
very end of "Additional Boards Manager URLs:" text box and enter (below is a single line):
“https://espressif.github.io/arduino-esp32/package_esp32_index.json”.
Check to ensure that your URL above is correct first by opening the URL in your browser. You
should observe a JSON file, otherwise, your URL is incorrect probably due to typo.
If you already have an ESP32 URL in your Arduino preference but is different, change it!
If you already have other URLs that are not for ESP32, add the above in a new line.

Sketchbook location (do this later)

1. Click this to set the


Boards Manager URLs

3. Check this

https://
espressif.githu

ESP32 Boards Manager URL


Your preferences info is stored here

This example has an existing URL. Leave it.


2. URL for ESP32 in a new
line

b. Go to menu “Tools > Board: ... > Board manager …”. It may take a little while to update.
c. In the Boards Manager dialog, and enter “esp32” and press ENTER. Select “esp32 by Espressif
Systems version …” (version 2.0.5 or higher). Click “Install” (or “update” if your version is older).

IOTG Lab 1 Oct 2023 Page 9 of 18


Search for esp32

If first time, it is “install”, otherwise


“update” or “remove”

IMPORTANT: The older ESP32 version 1.0.x is not compatible with some of codes used in the lab.
This will take a while to complete as it has to download the ESP32 compilers (there’re different
versions of ESP32) which are quite large, examples programs, etc.
Site below is for your reference only. No need to watch the video there, nor “Testing the installation”.
https://randomnerdtutorials.com/installing-the-esp32-board-in-arduino-ide-windows-instructions/

F. My Sketchbook location
Arduino uses the term “sketch” to refer to a program.
9. Create Folder for our sketches: Create a folder d:\arduino-iot (or c:) that will be our default folder to
store our programs.
10. Sketchbook Location in Preferences: Select menu File > Preferences. Set “sketchbook location” to
“d:\arduino-iot”, then OK.
11. Quit Arduino IDE (Ctrl-Q) & Start the IDE again: This will cause Arduino to create a default user library
location for you – see next section.

G. User Libraries location & Libraries Installation


12. User Libraries Folder: When you restart Arduino in the previous step, it auto-create the user libraries
folder – in our case, d:\arduino-iot\libraries. If not, create that libraries folder yourself. Make sure the
spelling is correct! We will install libraries there.
13. Installing a Library using Library Manager: Select menu “Sketch” > “Include Library” > “Manage
Libraries …”. Search for “esp32 analogwrite”. Select the one by Abdelouahed. Click “Install”.
For Arduino 2.0.x, choose the one by ERROPiX.
Do check to ensure that you have the library installed as below. If not, there’s something wrong with
your previous steps and you should rectify the problem.

FI: You can also download a library as a zip file from e.g. github and install through: “Sketch” > “Include
Library” > “Manage Libraries …” > “Add .ZIP library …”. We won’t do that.
Procedures above allow installation of a single library at a time, but we have many libraries.
14. Download “IOT-libraries.zip” file from the BrightSpace under “Module Information” > “Lab Exercises”
> “Lab 1”
Use Windows File Explorer to open the zip file and you should see something shown below. Select all
the items in there. Ctrl-C to copy them all to Windows clipboard.
IOTG Lab 1 Oct 2023 Page 10 of 18
Open the ZIP file in
Windows File Explorer
Contents of the ZIP file with many more
others libraries. Copy them all.

Go to folder d:\arduino-iot\libraries and use Ctrl-V to paste all in there. You should now have these:

Your Arduino user library folder


is now populated with new
libraries

15. Restart Arduino IDE in order for these libraries to be recognized. Reason: Manually copying libraries
into the folder is not recognized by the IDE until it is restarted.
16. List the .h and .cpp files found in d:\arduino-iot\libraries\_input\
_________________________________________________________
A reference on library installation: https://learn.sparkfun.com/tutorials/installing-an-arduino-library/all

H. Examples in the Libraries


17. Examples in the libraries: Most of the libraries come with examples. Try this …
“File” > “Examples” > Under Examples from Custom libraries “ESP32 AnalogWrite” > “ledFade”. This
example comes with the library we installed earlier. We will not try it. You may close it.
The examples are grouped as below
 Built-in Examples
 Examples for any board – should work for all Arduino compatible hardware platforms
 Examples for ESP32 Dev Module – Comes with ESP32 installation
 Examples from Custom Libraries – User installed as in the previous step.

I. Codes for the lab & The Blink


18. Download the “lab1codes.zip” from BS. Unzip to folder D:\arduino-iot\ and get “D:\arduino-iot\
lab1\...”.
19. Open the Blink sketch in D:\arduino-iot\lab1\. (This should be the same as File > Examples > 0.1Basics
> Blink)
Write down the specific folder where the “Blink” sketch is stored, e.g. d:\arduino-iot\...
______________________________________________________________________________
We assume that you had checked the “File name extensions” in a previous step for the File Explorer.
Write down the actual sketch file name (with extension .ino”) in that folder, e.g. d:\arduino-iot\...
______________________________________________________________________________
Question: If we were to save a sketch as “abc” in a folder “d:\arduino-iot\lab1”.
The sketch folder name would be: ___________________________________________________
The sketch file name would be: _____________________________________________________
IOTG Lab 1 Oct 2023 Page 11 of 18
20. What is in Blink.ino? In the File explorer, use a text editor (not Word) to open the Blink.ino file. You
can use either Windows notepad or notepad++ available here https://notepad-plus-plus.org/download
Blink.ino is basically a plain text file. Nothing special and is editable using any text editor.
Do not use Microsoft Word to edit the file as it will add in all sorts of formatting data into the file,
corrupting the program.
When you use the text editor, it is possible to set the text to bold or italic? ____________
Close the notepad and go back to Arduino IDE showing the Blink sketch.
What are the names of the 2 functions found in Blink.ino? ____________________________________
One of the functions in Blink.ino that will only be executed once at the beginning. It is _____________
The other function would be executed repeatedly non-stop. It is _______________________________

J. Test the Blink program


21. Choose the Board: Select “Tools” > “Board: …” > “ESP32 Arduino” > “ESP32 Dev Module”.

Yours?

DO NOT choose ESP32S3, ESP32C2 nor ESP32S2. THEY ARE DIFFERENT BOARDS!
22. Choose COM port: Select “Tools” > “Port” > followed by the COM port which you recorded earlier.
Observe the board and COM port info at the bottom right of the Arduino window.
Can I run the “blink” sketch now? Yes. We had selected the correct board and COM port.
Do not change the original program. That is, the variable “led” remains assigned with 13.
What is the unit for time (s, ms or us?) indicated as 1000 in “delay(1000);”? ________________
Study the program and summarize what it does:
___________________________________________________________________________________
___________________________________________________________________________________
Upload the program using one of the methods below. It will build (compile …) first and if there’s no
error, upload the generated codes to the board. The compilation may take some time! Be patient.
- “Sketch” > “Upload”
- Ctrl-U (shortcut, which is the most convenient)

- Click icon near the top left of the IDE.


DO NOT use the compile (or Ctrl-R) unless we don’t have the hardware to test. Reason: Upload
always starts the compile and if no error, upload the codes to run.
If all goes well, at the message window (bottom of the IDE), you should see a message
“Hardware resetting via RTS pin …”
NOTHING LOOKS VISIBLY WORKING! NO LED is blinking! What has gone wrong? We will learn to do
debugging in the next step.
Scroll up to the top of the message window and record these info:
How many bytes does your program codes take up in the flash memory (ROM)? __________________
IOTG Lab 1 Oct 2023 Page 12 of 18
This is ______________ % of program storage. Maximum is ___________________________ bytes
How many bytes does your program global variables take up in the RAM? _______________________
This is ___________ % of available RAM and still has ________________________ bytes available

K. Program Debugging using Serial Monitor & Printing


Before you can troubleshoot what is wrong in a program, you must know the expectation. Some possible
reasons for not getting the behaviour we expected:
- the program logic is wrong or careless mistakes, e.g. it is not running in the sequence we expected,
- we made certain wrong assumptions, or
- hardware problem (component not working, wrong connections, etc).
IMPORTANT: A basic method to debug a program is to see what is going on in the program by having the
program sending useful “debug messages” at different parts of the program to the “Serial Monitor”.

23. Serial Monitor: Open the Serial monitor by clicking icon at the top right (or menu “Tools > Serial
Monitor” or short cut Ctrl-Shift-M). The Serial Monitor Window is shown below. Make sure that the
baud rate is set to 115200.

Always use 115200 Clear Serial Monitor


for our lab content when necessary
Check this as we normally
we want to autoscroll

There is no message in that window.


Press the MCU Reset button. You see something but still not helpful.
24. Arduino IDE and Serial Windows side by side: DO NOT close the Serial Monitor window. Leave it side
by side with the IDE editor as shown so that we can immediately see the debug messages after
program upload. You may resize the IDE window a bit to your comfort.

Arduino Edit Window Serial Monitor Window

25. Modify the Blink sketch to that as shown below. We only added in the Serial object functions to tell us
what is going on in the program.
Note that we have a delay(500) immediately after Serial.begin() for the Serial hardware to settle. If
not, the initial program messages sent by Serial may not appear at the Serial Monitor.
int led = 13;

void setup() {
Serial.begin(115200); // communicate with serial monitor at 115200bps
delay(500); // wait for the Serial hardware to settle
Serial.print("\nProgram started");
Serial.print("\nSet pin ");
Serial.print(led);
Serial.print(" to OUTPUT");
// Above 4 statements can be done using single Serial.printf()below
// Serial.printf("\nSet pin %d to OUTPUT",led);

IOTG Lab 1 Oct 2023 Page 13 of 18


pinMode(led, OUTPUT);
}

void loop() {
Serial.printf("\nOutput HIGH to pin %d for 1s",led);
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
Serial.printf("\nOutput LOW to pin %d for 1s",led);
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

You should observe the messages at the Serial Monitor window non-stop:

Note that the program Serial object bit rate must match the Serial Monitor bit rate at 115200bps.
26. Comment/Uncomment lines: To comment out a line or multiple lines, place the cursor at the line or
select multiple lines, then press Ctrl-/. To uncomment, do the same (toggle effect).
Comment out the 4 Serial.print() statements in setup() and uncomment the Serial.printf() statement.
Test the program. Do you get the same output at the Serial Monitor? ____________
27. Serial Printing functions: The program above uses Serial.print() and Serial.printf() functions.
(Serial.println() which does the same as Serial.print() but adds a newline at the end of printing.)
What are the differences for Serial.print() and Serial.printf()?
The printf() is the standard C/C++ formatted print function allowing printing of text and data in a single
statement. The format specifier (e.g. “%d”) must match the data type. (If mismatch? …)
Question: What printf() format specifier to use when printing a float _______, to print a string _______
On the other hand, the print() and println() functions are very special in the sense that they
understands the data type received and print it appropriately. In the above example, the print() was
used to print string and integer. If you pass a float to print(), it will also print correctly. It can print
complex data types like IP address object, e.g. “192.168.1.92”.
FI only: Serial object uses C++ “function overloading”. Behind the scene, there are actually many
print() functions implemented for different number of input data and data types. During compilation,
the compiler automatically picks up the right one to use based on the input parameters. This C++
feature is not available in C.
So which one to use? print() or printf()?
For convenience, printf() is preferred if we want to print data with text. However, we have to be
careful with the data format specifiers. Some Arduino platforms (e.g. Uno) do not support printf().
Use print() if we want to print special object types like an IP address
28. Correct the LED pin number: From the messages at the Serial Monitor, the program looks fine but the
LED pin number is incorrect. Change the led value from 13 to 23. Test the program.
Which LED is blinking now? __________________.

IOTG Lab 1 Oct 2023 Page 14 of 18


29. Remember pinMode(): If the above program do not have “pinMode(led,OUTPUT);” in setup(), the
program would never work! BEWARE! This is a common mistake.
Comment out the pinMode() statement in setup(). Test the program. Does the LED blink? __________

L. Value to On Red LED


30. HIGH or LOW to on Red LED? The comment in the program states that it is HIGH to on the LED.
Modify the program so that ALL digitalWrite() functions would only output HIGH. Test the program.
Observe the LED. Now try output LOW only.
Conclusion: The LED requires a _____________ to turn on.
By the way, what is HIGH or LOW? They are actually just 1 and 0.
Restore the program to blink as before.
CHECKPOINT 2: Show to your working program to the
supervisor, and share how you verify if it is HIGH or LOW to on the LED________________

M. Header file for the Kitset


31. Download program Blink2.ino from BS. Store it in folder d:\arduino-iot\lab1\Blink2\
The codes is shown below. Open the sketch and test it.
// Blink2.ino
#include "npsoe_iot_kit.h"
//------------------------------------
void setup() {
Serial.begin(115200);
delay(500); // wait for Serial to settle
Serial.printf("\n---------------\nSet pin %d to OUTPUT",LED_Y);
pinMode(LED_Y, OUTPUT);
}
//------------------------------------
void loop() {
Serial.printf("\nOut %d to pin %d to ON LED for 1s", LED_Y_ON_VAL, LED_Y);
digitalWrite(LED_Y, LED_Y_ON_VAL); // turn the LED on
delay(1000); // wait for a second
Serial.printf("\nOut %d to pin %d to OFF LED for 1s", LED_Y_OFF_VAL, LED_Y);
digitalWrite(LED_Y, LED_Y_OFF_VAL); // turn the LED off
delay(1000); // wait for a second
}

Which LED is blinking? ____________________ LED_Y = _______ the pin number for that LED.
What are these values? LED_Y_ON_VAL = ________________ LED_Y_OFF_VAL = ________________
32. Examine npsoe_iot_kit.h: Determine & record the exact path of the header file npsoe_iot_kit.h. (Hint:
Look at the libraries folder)
___________________________________________________________________________________
Open the file using a text editor (not Word) and determine these pin numbers for the 3 LEDs:
LED_R = _______________ LED_Y = ________________ LED_G = ___________________
What is the value for these LED to be turned on? _________ Thus, they are turn off with value _______
Push buttons: PB1 = _________ PB2 = ________ They are connected to input/output (delete one) pins.
What is the value at the push button when it is pressed? __________ Thus, when released, it is ______

IOTG Lab 1 Oct 2023 Page 15 of 18


N. Blinking 3 LEDs
33. Save Blink2 as Blink3 and change the program to that below. Some comments are removed for
conciseness. You can leave them in your program. The blinkY1() function does a dedicated job to blink
the Yellow LED once. This is “modular programming” – writing small functions to do very specific task,
a very important programming practice.
Make sure that your program works as before.
// Blink3.ino
#include "npsoe_iot_kit.h"
//------------------------------------
void setup() {
... // no change for setup()
}
//------------------------------------
void blinkY1() { // 1 means blink once
digitalWrite(LED_Y, LED_Y_ON_VAL); // turn the LED on
delay(1000); // wait for a second
digitalWrite(LED_Y, LED_Y_OFF_VAL); // turn the LED off
delay(1000); // wait for a second
}
//------------------------------------
void loop() {
blinkY1();
}

34. Add in another 2 functions and update the setup() and loop(). The intention of the program is to blink
3 LEDs independently at different rates. Ensure that your program is neatly formatted with proper
indentation, another important programming practice. Use Cltr-T to auto-indent when necessary.
Remember to use copy-paste-modify to be productive.
- setup() will initialize the pins for Red and Yellow LED as OUTPUT.
- Function blinkR1() will blink the Red LED once with 0.5s on and 0.5s off.
- Function blinkG1() that will blink the Green LED once with 0.25s on and 0.25s off.
Modify loop() to call ONLY blinkG1(). Test the program. What is the blink rate for the Green LED?
That is, How many blinks per second? _________
You can estimate from observation & the codes in blinkG1() function.
35. Modify loop() to call all the 3 blink functions.
Do the 3 LEDs blink at as their intended rates (e.g. Green LED blink rate same as before)? ___________
When delay(1000) is called, how long will it take for it to complete and return back? ____________
How long do these functions take before returning back to loop() after been called?
blinkY1(): __________________ blinkR1(): __________________ blinkG1(): __________________
Due to the use of delay(), all the 3 functions are “blocking” as they don’t return quickly. Thus the 3
LEDs cannot blink independently at the intended rates. The three functions have to WAIT for one
another to complete before its turn to blink once!
We will show you how to overcome this problem in the next lab. The demo program in the next section
is an example of a responsive system.
CHECKPOINT 3: Show to your supervisor your new “non-working” program ______________________

IOTG Lab 1 Oct 2023 Page 16 of 18


O. Demo Program (Optional – if you have time)
For this demo program, you need the I2C Expansion Board that comes with an OLED display, MPU6050
accelerometer + gyroscope and a Real-Time clock. It demonstrates a responsive system.
36. Connect the I2C Expansion Board to the I2C Grove connector. You have to remove the LED-PB board
before the connection. Plug back the LED-PB board after that and double check that it is aligned to the
socket properly.
If a grove AC lamp is available, connect it to Grove connector G1 and the lamp to the AC mains.

The optional AC lamp is


safely enclosed. DO NOT
open the enclosure.
It is controlled by a solid-
Optional AC lamp state relay in the enclosure,
electrically isolated from the
grove cable.

I2C Expansion Board

OLED RTC

MPU6050 has an accelerometer, a


gyroscope and a temperature
sensor
MPU6050

37. Open iotg_esp32Demo sketch in lab1 folder. Ensure that the Serial Monitor is open and is beside the
Arduino IDE window.
Notice that this program consists of multiple files. Each of the .cpp file serves specific purpose –
modular programming by splitting a program into multiple files.

Upload the program. It may take quite some time to build the program.
Refer to the OLED display: IP address given by the ASUS_0603 Router: __________________________
If “NO CONNECTION” shown, check with your supervisor to resolve the issue.
Last resort: Use your own mobile phone hotspot SSID & password by changing these 2 lines in
iotg_esp32Demo file.
const char *r_ssid = "ASUS_0603"; // router or your a hotspot
const char *r_password = "asus0603";
Run and note the IP address given to ESP32 shown at the OLED.
Observation at the yellow LED: _____________________________________________
Connect your laptop WiFi to ASUS_0603 router (or a hotspot). At the Web browser enter the ESP32 IP
address as the URL. The ESP32 is running a web server and may take time to respond. Press F5 to
refresh if necessary. If hotspot is used, minimize the use of data on your laptop! You may also try to
use browser on your mobile phone connected to the same SSID.

IOTG Lab 1 Oct 2023 Page 17 of 18


Ensure that you can view both the browser and Serial Monitor at the same time on your computer.
38. At the Serial Monitor, observe that in every 10s, it shows how many times the loop() function was
called during the past 10s. Averagely, how many times is the loop() function called a second?
__________________________________________________________________________________
39. At the laptop browser, click the two buttons multiple times. Observe the ESP32 and Serial Monitor:
__________________________________________________________________________________
__________________________________________________________________________________
Press ESP32 PB1, P2 and the touch pad multiple times. Observations at the ESP32 and the browser
display.
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
40. The date and time shown at the display comes from the Real-Time Clock at the I2C Expansion board.
Try to set the time shown at the OLED by entering command at the Serial Monitor of format and send
(or press ENTER): “*YYMMDDHHMMSS#” (without double quotes) YY=year, MM=month …
Are you able to change the date and time? _____________________
If there is a battery at the RTC module, you may power off the unit by disconnecting the USB cable,
wait a little while and plug-in again. The time should be correct as the battery keeps the clock running.
41. What other things do you observe at the OLED display concerning MPU6050? Accelerometer reading is
in “g” and gyroscope reading is in “deg/s”. You may tilt the I2C Expansion Board orientation to see the
effect. You may gently touch the MPU6050 IC to attempt to increase its temperature.
__________________________________________________________________________________
__________________________________________________________________________________
42. List the functions called in loop(): _______________________________________________________
__________________________________________________________________________________
Averagely how long does it take to execute all these functions once? __________________________
IMPORTANT OBSERVATION of the demo program:
The system is doing multiple tasks responsively: blinking Yellow LED; monitors and responds to PB1,
PB2, touch pad and browser requests; periodically reading and update OLED on RTC and MPU readings.
It manages to execute the loop() function >450 times a second.
In the future labs, we will attempt to show you how to some of these.
CHECKPOINT 4: (OPTIONAL) If you’ve done this, show your recordings to your supervisor: __________

IOTG Lab 1 Oct 2023 Page 18 of 18

You might also like