Ch2b Programming (Part A) - E
Ch2b Programming (Part A) - E
(Part A)
EEE3453 29/8/2022 1
Arduino Language Reference
◦ https://www.arduino.cc/reference/en/
Useful websites:
◦ http://www.esp32.net/
◦ https://startingelectronics.org/software/arduino/learn-to-program-
course/
◦ https://randomnerdtutorials.com/
◦ https://thestempedia.com/tutorials/getting-started-with-esp32-on-
arduino-ide/
◦ https://www.instructables.com/id/ESP32-With-Arduino-IDE/
◦ https://techexplorations.com/
◦ https://www.arduino.cn/thread-41132-1-1.html
EEE3453 29/8/2022 2
The Waterfall Model Approach
EEE3453 29/8/2022 3
Waterfall Model - a linear, sequential approach to the
software development life cycle (SDLC)
◦ gradual execution of every stage completely
◦ distinct endpoints or goals are set for each stage of
development
◦ the outcome of one stage acts as the input for the next
stage sequentially
EEE3453 29/8/2022 4
6 non-overlapping stages in the waterfall methodology:
◦ Requirements Analysis
◦ System Design
◦ Implementation
◦ Testing
◦ Deployment / Operations
◦ Maintenance
EEE3453 29/8/2022 5
Documentation
EEE3453 29/8/2022 6
Requirement Analysis -> System
Specifications
• User requirements
• System Requirements System Design -> Product model and
• Statuary Requirements business logic -> Design
• Constraints Specifications
• Deadlines • Design models
• Algorithm development
• Technical resources (or even
Implementation -> Prototype Financial resources)
• Program Coding of software logic • Technology options
and requirements • Sample data for testing
• Feasibility or Critical Stage
• Circuit and PCB design and • Project Sizing – man vs time
assembling (Custom-design vs
bought-in)
EEE3453 29/8/2022 7
Testing -> Sign-off and delivery
• Unit Testing -> System Testing ->
Functional Testing
• Field/Site Testing & Commissioning
• Trial Run -> User feedback
• Performance Evaluation Deployment -> Field Operations
• Quality Assurance • The fully function product or
application is deployed to the
live environment
Maintenance -> Patches, Updates or
• Evaluation of user Experiences
New Versions
• Corrective, adaptive and perfective
maintenance - carried out
indefinitely
• Release of patches, updates and
new versions
EEE3453 29/8/2022 8
Documentation is essential to each development stage
EEE3453 29/8/2022 9
Case study: Design and implementation of a Water Tank Level
Control System using a Waterfall Model approach
EEE3453 29/8/2022 10
Some good practices for new programmers
◦ Develop a conceptual model for the target program
E.g. use a chart or diagram to illustrate your design
thinking
◦ Build incrementally
Use meaningful variable names
Get the simplest piece to work first
Add complexity and test at each stage
Save and backup frequently
◦ Comment liberally
EEE3453 29/8/2022 11
EEE3453 29/8/2022 12
Arduino IDE (Integrated Development Environment)
ESP32 Development Module
Driver Board (for Digital and Analog I/O programming)
Source Arduino
Program IDE ESP32
Toolchain Development
Libraries Board
Executable
Code
MicroUSB
Cable
The Program Development
Environment for EEE3453
EEE3453 29/8/2022 13
Key features of ESP32 MCU
EEE3453 29/8/2022 14
RST button – If you press the
RST button, it reboots the
ESP32 kit.
BOOT button – If you hold down the The ESP32 Dev Module
BOOT button and then press the RST piggybacked on the Driver Board
button, the ESP32 kit reboots in
programming mode.
EEE3453 29/8/2022 15
Software download: https://www.arduino.cc/en/Main/Software
Supporting multiple platforms (Windows, Mac and Linux)
Written in Java based on Processing and other open-source
software
Arduino programming language is like C/C++
EEE3453 29/8/2022 16
New
Save
Open
Upload
Verify
EEE3453 29/8/2022 17
Browse the Sketchbook
folder
Configurations of the
currently associated ESP32
target board
EEE3453 29/8/2022 18
Select the Sketchbook folder
- The ‘Sketchbook’ folder is a
working folder to keep the
Arduino sketch projects.
EEE3453 29/8/2022 19
Set the Ident and Font Sizes
for the Editor
EEE3453 29/8/2022 20
Facilities related to sketch
program development
EEE3453 29/8/2022 21
Launch the Serial Monitor
EEE3453 29/8/2022 23
The Arduino IDE offers the following functions for ESP32
program development:
◦ Edit the source program of an ESP32 application
◦ Compile an ESP32 source program to ESP32 object code
◦ Link the ESP32 object code with relevant libraries to
produce ESP32 executable code
◦ Upload ESP32 executable code to the associated target
board for execution
EEE3453 29/8/2022 24
The building processes under Arduino IDE
.ino
ESP32
Target Board
Upload
EEE3453 29/8/2022 25
(1) Basic Structure of a Sketch
EEE3453 29/8/2022 26
Sketch – Arduino IDE refers a program written in Arduino
Language as a ‘sketch’
◦ a unit of code that is edited, compiled, uploaded to and run
on the Arduino/ESP32 target board
Syntactical Elements:
◦ semi-colons ; - end of each statement
◦ // - single line comments
◦ /* */ - multi-line comments
◦ {} - open and closing curly braces
◦ () - parenthesis
EEE3453 29/8/2022 27
◦ Variables are case-sensitive
Example: A variable ‘count’ is different from another
variable ‘Count’
EEE3453 29/8/2022 28
A basic Arduino sketch consists of two required functions:
setup() and loop()
EEE3453 29/8/2022 29
void -> no return values
void setup( ) {
EEE3453 29/8/2022 30
void -> no return values
void loop( ) {
EEE3453 29/8/2022 31
setup() function
◦ needs to be the first function in an Arduino sketch
◦ executed only once
◦ to set up the Arduino board
for example: setting the modes of I/O pins, starting the
system; initializing the Serial Port
◦ no return of any values therefore the reserved word ‘void’
precedes it (i.e. void setup())
EEE3453 29/8/2022 32
loop() function
◦ where the body of a program will reside
◦ executed repeatedly
all the code between the curly braces in loop() is repeated
over and over again – in a loop
◦ no return of any value, therefore the reserved word ‘void’
precedes it (i.e. void loop())
void loop() {
Serial.println(“My name is Superman.”);
delay(1000); // introducing a waiting period of 1000 ms
Serial.println(“I like ice-cream!”);
delay(2000); // introducing a waiting period of 2000 ms
}
EEE3453 29/8/2022 34
Short Question:
EEE3453 29/8/2022 35
A function in a sketch performs some specific task (i.e.
performs a function)
◦ we say that we "call a function" -> we use a function to
perform its specified task Data
◦ some functions may need input parameters or return values
Parameters to be passed
◦ Example: to the function
delay(1000);
Serial.begin(115200);
The ‘delay()’ is a function The ‘begin()’ is a specific
to produce a waiting function to initialize the
period -> waste of time communication speed of
The ‘Serial’ refers an the Serial Port
object which corresponds
to the Serial Port
EEE3453 29/8/2022 36
Some useful functions:
◦ pow(x, y) // the value of a number x raised to a
// power y
◦ sq(k) // square of a number k;
◦ sqrt(k) // square root of a number k;
◦ cos(A) // cosine of an angle A (in radians)
◦ sin(A) // sine of an angle A (in radians)
◦ tan(A) // tangent of angle A (in radians)
◦ random(k) // generate a random number from 0 to k-1
int U, Z; // }
float V, W, Y; // } declare variables of relevant datatypes
int k, t; // }
float p, q; // }
EEE3453 29/8/2022 38
// Program: SerialPrintDemo.ino
void setup() {
Serial.begin(115200);
}
EEE3453 29/8/2022 39
void loop() {
EEE3453 29/8/2022 40
Serial.println(12.3456);
Serial.println(12.3456, 1);
Serial.println(12.3456, 2);
Serial.println(12.3456, 3);
Serial.println(12.3456, 4);
Serial.println(12.3456, 5);
Serial.println(12.3456, 6);
EEE3453 29/8/2022 41
while(1); // Dynamic halt of the program
/*
Examine the program output on the Serial Monitor
*/
EEE3453 29/8/2022 42
String: H e l l o 1
Dec: 72 101 108 108 111 49
Bin: 01001000 01100101 01101100 01101100 01101111 00110001
EEE3453 29/8/2022 43
A programming tips for writing a sketch
◦ the loop() function is executed repeatedly
-> all the code between the curly braces in loop() is
repeated over and over again –> in a loop
-> a sketch program will not be terminated or halted
EEE3453 29/8/2022 44
(2) The Arduino Programming Language
Reference
EEE3453 29/8/2022 45
The Arduino Programming Language can be divided into three
main parts:
◦ variables ( 變 數 ) - Arduino datatypes, variables and
constants
◦ structure (架構) - the elements of Arduino (C/C++) code
◦ functions (函式) - for controlling the Arduino board and
performing specified computations or operations
EEE3453 29/8/2022 46
Arduino Language Reference (1/5)
EEE3453 29/8/2022 47
Arduino Language Reference (2/5)
EEE3453 29/8/2022 48
Arduino Language Reference (3/5)
EEE3453 29/8/2022 49
Arduino Language Reference (4/5)
EEE3453 29/8/2022 50
Arduino Language Reference (5/5)
EEE3453 29/8/2022 51
Classwork:
◦ Browse the Arduino Language Reference and review the
programming information of the Serial object and
associated functions.
EEE3453 29/8/2022 52
(3) Datatypes, Variables and Constants
EEE3453 29/8/2022 53
4 basic types of data:
◦ integers
◦ floating-point values
◦ boolean values
◦ character strings
Integers
◦ no fractional part
Examples: 1, 2, 0, 39, -56 or -343
◦ integer arithmetic results in truncation of integers
EEE3453 29/8/2022 54
Floating-point numbers
◦ Non-zero fractional part
Examples: 1.234, -2.7832
◦ Floating-point arithmetic does not truncate, but has round-
off
Boolean values
◦ A boolean variable holds one of two values, true or false
(Each boolean variable occupies one byte of memory.)
EEE3453 29/8/2022 55
Example: Declaring integer and floating-point variables
EEE3453 29/8/2022 56
Example: Declaring boolean variables
EEE3453 29/8/2022 57
String
◦ a string is traditionally a sequence of characters
◦ a constant string is specified in "double quotes"
Example: “Good Morning!”
◦ a string can be created as an array of type ‘char’ with a null-
termination (‘\0’)
EEE3453 29/8/2022 58
The compiler will automatically
add the null character if it is not
explicitly stated
Example: Different ways to declare strings through array
creation
char firstString[15];
char secondString[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};
char thirdString[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'};
char fourthString[ ] = "arduino";
char fifthString[8] = "arduino";
A null character as
char sixthString[15] = "arduino";
termination – this enables
the Serial.println() to know
the end of the string
// Note: Single quotes or double quotes?
// Strings are always defined inside double quotes ("Abc") and
// characters are always defined inside single quotes('A').
EEE3453 29/8/2022 59
Datatype Size in Description
Bytes
char 1 • Stores 8-bit numerical ASCII value of characters
like alphabets, symbols, etc.
• Also store a signed number that is in range of
-128 to 127.
• Character literals are written in single quotes like
'a', '#' etc. and their ASCII numerical is stored at
corresponding variable location.
unsigned 1 • Stores 8-bit numerical ASCII values of characters,
char symbols.
• Also store any unsigned number in range of 0 to
255.
• Character literals are written in single quotes like
'a', '#' etc. and their ASCII numerical is stored at
corresponding variable location.
EEE3453 29/8/2022 60
Datatype Size in Description
Bytes
int 4 • Stores a 4-byte (32-bit) signed integer value that
is in the range of -2,147,483,648 to 2,147,483,647.
Examples: 1, 2, 23, 0, -465
unsigned 4 • Stores an unsigned 4-byte (32-bit) integer that is
int in the range of 0 to 4,294,967,295 (2^32 – 1).
long 4 • Stores a 4-byte (32-bit) signed integer value that
is in the range of -2,147,483,648 to 2,147,483,647.
unsigned 4 • Stores an unsigned 4-byte (32-bit) integer that is
long in the range of 0 to 4,294,967,295 (2^32 – 1).
EEE3453 29/8/2022 61
Datatype Size in Description
Bytes
float 4 • Stores a signed 4-byte (32-bit) value that is an
integer or a value with decimal point (say 12.15)
that is in the range of -3.4028235E+38 to
3.4028235E+38.
double 8 • Stores a signed 8-byte (64-bit) value that is an
integer or a value with decimal point that is in the
range of -1.7976931348623157E+308 to
1.7976931348623157E+308.
EEE3453 29/8/2022 62
A variable
◦ to store a value or an information that a programmer can
refer and/or manipulate it at a later stage during the life of
an Arduino Sketch
◦ referenced or accessed by its name later in the program
宣告
a variable must be declared before use
Defining/Declaring a variable
◦ Variable_DataType Variable_Name;
EEE3453 29/8/2022 63
Example:
EEE3453 29/8/2022 64
Variable Naming Rules
◦ a variable can consist of any letters (a to z and A to Z)
◦ variables can contain the numbers 0 to 9, but may not start
with a number, e.g. 3var is not allowed, but var3 is allowed
◦ variables may not have the same names as Arduino
language keywords,
Example: You cannot have a variable named ‘int’
◦ variables must have unique names i.e. you cannot have two
variables with the same name
◦ variable names are case-sensitive, so Count and count are
two different variables
◦ variables may not contain any special characters, except the
underscore (_)
EEE3453 29/8/2022 65
It is best to give variables meaningful names
◦ Examples:
Total_Score for a variable to store the total scores of an
examination
WaterLevel for a variable to represent the water level of a
tank
EEE3453 29/8/2022 66
The compound interest formula is given as follows:
A = P (1 + r)n
where A = Amount
P = Principal
r = Interest rate
n = no. of years
EEE3453 29/8/2022 67
Scope of variables
◦ Scope refers to the visibility of a variable
-> In other words, which parts of your program can see or
access the variable
2 levels of visibility:
◦ Global Variable – a variable that is visible (hence accessible)
throughout the program, unless shadowed
generally static variables -> whose extent (lifetime) is the
entire runtime of the program
EEE3453 29/8/2022 68
◦ Local Variable – a variable that is referenced in the function
or block in which it is declared, it will override the same
variable name in the larger scope
EEE3453 29/8/2022 69
// Program: void loop() {
// Global_Local_Var.ino int i, j;
int Total;
j = 2 * i + Total;
void setup() { Serial.print(“i = ”);
int k; Serial.println(i);
Serial.begin(115200); Serial.print(“Total = ”);
Serial.print(“k = ”); Serial.println(Total);
Serial.println(k); Serial.print(“j = ”);
} Serial.println(j);
delay(1000);
Identify the visibility of
variables: Total, i, j and k, while(1);
respectively. }
EEE3453 29/8/2022 70
sizeof() function – a utility which returns the number of bytes
in a variable type, or the number of bytes occupied by an
array
◦ Syntax: sizeof(variable)
Parameter:
variable -> any variable type or array (e.g. int, float,
byte)
Return:
the total number of bytes of the variable
EEE3453 29/8/2022 71
◦ Example:
EEE3453 29/8/2022 72
Constants - predefined expressions in the Arduino
programming language
◦ to make the programs easier to read
EEE3453 29/8/2022 73
Defining Logical levels
◦ two logical (or boolean) constants: true and false
false : defined as 0 (zero).
true : any integer which is non-zero is true;
i.e. -1, 2 and -199 are all defined as true, too, in a
Boolean sense
Note that the true and false constants are typed in lowercase,
unlike HIGH, LOW, INPUT, and OUTPUT
EEE3453 29/8/2022 74
Defining Digital Pins modes
◦ Digital pins can be configured as INPUT, INPUT_PULLUP, or
OUTPUT
Configuring a pin with pinMode() changes the electrical
behavior of the pin.
EEE3453 29/8/2022 75
Pin configured as OUTPUT -> the pin can source (supply
current) or sink (absorb current) current to other
devices/circuits (e.g. LED or Buzzer)
◦ Loads greater than 40 mA (e.g. motors) will require a
transistor or other interface circuitry.
EEE3453 29/8/2022 76
Defining Pin Levels
◦ when reading or writing to a digital pin, two possible values
a pin can take/be-set-to : HIGH or LOW
◦ input or output voltages corresponding to HIGH and LOW
values are dependent on the mode (INPUT or OUTPUT) that
the pin is configured
In EEE3453, consider HIGH = 1 and LOW = 0 in program
development rather than voltage levels
EEE3453 29/8/2022 77
The program is a demo to illustrate the use of constants and
simple configuration of two digital pinouts for input and
output operations.
+Vcc
Pull-up 6 Led
Resistor
R Current Limiting
Button 5 ESP32 Resistor
R
Push-
LED
button
EEE3453 29/8/2022 78
‘Button’ and ‘Led’ are programmer-
defined labels to designate the two digital
pins for programming purpose.
Operations:
◦ Button (pin 5) – configured as a digital input to sense the
state (On or Off) of a push-button
◦ Led (pin 6) – configured as a digital output to drive a LED
Push-button ON (i.e. Button = LOW) -> LED is turned ON
(i.e. LED = HIGH)
Push-button OFF (i.e. Button = HIGH) -> LED is turned OFF
(i.e. LED = LOW)
◦
EEE3453 29/8/2022 79
+Vcc
Pull-up 6 Led
Resistor
R Current Limiting
Button 5 ESP32 Resistor
R
Push-
LED
// Program: SimpleIO.ino
button
void setup () {
EEE3453 29/8/2022 80
void loop() {
EEE3453 29/8/2022 81
Exercise 1:
◦ Learn to use different types of variables
Program: Ex1_VariableType-E.ino
EEE3453 29/8/2022 82
(4) Assignments & Operators
EEE3453 29/8/2022 83
Assigning a value to a variable
◦ Variable_Name = Expression;
◦ The ‘=’ sign is the assignment operator
◦ an Expression will give a valid value that will be assigned to the
variable
Example:
const float myPI = 3.14; // defining a floating-point constant
float C, R;
C = 2.0 * myPI * R;
EEE3453 29/8/2022 84
Example:
int x, y;
x = 3;
y = x;
x = 5;
EEE3453 29/8/2022 85
Arduino offers 5 basic arithmetic operators for mathematical
computations:
EEE3453 29/8/2022 86
Examples: Declaring integer variables and perform arithmetic
operations
EEE3453 29/8/2022 87
Integer arithmetic always produces integers
Example:
(i) int i, j;
i = (2/3) * 4;
j = i + 2;
(ii) int i, j;
i = (2.0/3.0) * 4.0;
j = i + 2;
EEE3453 29/8/2022 88
Floating-point arithmetic preserves the fractional part of
numbers, but it does so approximately
Example:
float w, x, y, z;
w = 3.0;
x = 2.0;
y = w/x;
z = y – 1.5;
EEE3453 29/8/2022 89
Example:
float w, x, y, z;
w = 4.0/3.0;
x = w - 1;
y = 3*x;
z = 1 – y;
EEE3453 29/8/2022 90
Arduino offers 6 relational operators:
EEE3453 29/8/2022 91
A relational operation tests a relation between two variables
◦ the result of a relational operation is either ‘true’ (1) or
‘false’ (0)
EEE3453 29/8/2022 92
// Program: Relational.ino
void setup() {
Serial.begin(115200);
More: RelationalString.ino
}
void loop() {
int x = 200;
if (x >= 100) {
Serial.println(“x >= 100”); }
else {
Serial.println(“x < 100”); }
delay(1000);
while(1);
}
EEE3453 29/8/2022 93
Logical operators evaluate either one or two relational or
logical statements.
EEE3453 29/8/2022 94
// Program: LogicalOp.ino
void setup() {
Serial.begin(115200);
}
void loop() {
bool A = true, B = false;
bool C, D, E;
C = A && B;
D = A || B;
E = !B;
EEE3453 29/8/2022 95
Serial.print("C = A && B = ");
Serial.println(C);
Serial.print("D = A || B = ");
Serial.println(D);
Serial.print("E = !B = ");
Serial.println(E);
What is the value of C, D
and E after the program
while(1); is executed ?
Ans.:
} C ← 0 (false),
D ← 1 (true),
E ← 1 (true)
EEE3453 29/8/2022 96
Increment operator
◦ an arithmetic operator that increments an integer variable
by a value of one
EEE3453 29/8/2022 97
Decrement Operator
◦ an arithmetic operator that decrements an integer variable
by a value of one
EEE3453 29/8/2022 98
Examples: (You may download the ‘IncDecOp.ino’ program and
make a run for comparison.)
int R = 9, S = 5;
int W, Y
R++;
S++;
--R;
S--;
W = R + S--;
Y = ++R + S;
EEE3453 29/8/2022 99
Exercise 2:
◦ Learn to use different arithmetic operations + - * / %
◦ Learn to use increment and decrement ++ --
◦ Learn to use logical operations ! && || ^
◦ Learn to use bitwise operations & |
Program: Ex2_Operator.ino