0% found this document useful (0 votes)
69 views

Ch2b Programming (Part A) - E

The document provides an overview of programming with Arduino IDE for an ESP32 development board. It discusses the Arduino IDE software, useful programming resources, the basic structure of an Arduino sketch, and the required setup() and loop() functions. Key features of the ESP32 microcontroller are also outlined.

Uploaded by

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

Ch2b Programming (Part A) - E

The document provides an overview of programming with Arduino IDE for an ESP32 development board. It discusses the Arduino IDE software, useful programming resources, the basic structure of an Arduino sketch, and the required setup() and loop() functions. Key features of the ESP32 microcontroller are also outlined.

Uploaded by

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

Programming using Arduino IDE

(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

 Each stage must be completed and the defined set of goals


are achieved before the next stage can begin

EEE3453 29/8/2022 5
Documentation

Software Development - The Waterfall Model

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)

The Waterfall Model – Tasks & deliverables in each stage (1)

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

The Waterfall Model – Tasks & deliverables in each stage (2)

EEE3453 29/8/2022 8
 Documentation is essential to each development stage

 Use cases of the Waterfall approach


◦ ideal for projects that have specific documentation, fixed
requirements, ample resources, an established timeline and
well-understood technology
◦ also applicable to system development comprising
hardware and software -> This applies to the integrated
project of EEE3453

EEE3453 29/8/2022 9
 Case study: Design and implementation of a Water Tank Level
Control System using a Waterfall Model approach

Water Tank Level Control System

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.

ESP32 Dev Module

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

Pre-installed examples for


learning Arduino programming

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.

Fill in the URL for


downloading the Board
Manager for new ESP32 target
boards

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

The ESP32 target board


currently associated with the
Arduino IDE

The Com Port currently


connecting the Arduino IDE
and the ESP32 target board
EEE3453 29/8/2022 22
Various help or reference
information are available
under the [Help] tab

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’

◦ Keywords (or reserved words)


 pre-defined words for specific use;
 Examples: for, if, if-else, while, HIGH, LOW, setup, loop,
Serial, begin, delay, …
 not to be used by programmers as variable names

EEE3453 29/8/2022 28
 A basic Arduino sketch consists of two required functions:
setup() and loop()

Click this icon


to launch the
Serial Monitor

EEE3453 29/8/2022 29
void -> no return values

empty -> no input parameters

void setup( ) {

// body of the function Opening and closing braces


enclose the body of the function
}

EEE3453 29/8/2022 30
void -> no return values

empty -> no input parameters

void loop( ) {

// Body of the function Opening and closing braces


enclose the body of the function
}

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

 Program statements in the setup() and loop() functions are


executed from top to bottom
◦ the top-to-bottom execution can be altered only by flow
control statements (e.g. for, if, if-else, while)
EEE3453 29/8/2022 33
// Program: BasicSketch.ino
void setup() {
Serial.begin(115200); // initialize the Serial Port with a
// communication speed of 115200 bps
Serial.println(“Running a simple program.”);
}

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:

◦ Refer the example ‘BasicSketch.ino’, the loop() function will


execute repeatedly. How can we stop the loop() function to
execute ?

◦ What is the program behavior if the loop() function is


empty ??

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

◦ Each function returns a calculated value of an appropriate


datatype
EEE3453 29/8/2022 37
 Examples:

int U, Z; // }
float V, W, Y; // } declare variables of relevant datatypes
int k, t; // }
float p, q; // }

U = sq(k); // calculate the square of integer k


V = sq(p); // calculate the square of floating-point p
W = sqrt(q); // calculate the square root of q
Y = cos(3.14 * 65.0/180.0); // calculate cos65o
Z = random(50); // generate a random number in the range
// of 0 to 49

EEE3453 29/8/2022 38
// Program: SerialPrintDemo.ino

/* This is a demo program to illustrate the printout formats


associated with the print() and println() functions of the
Serial Port.
*/

void setup() {

Serial.begin(115200);
}

EEE3453 29/8/2022 39
void loop() {

Serial.println("Printout from Serial Port:");


Serial.print("Print without a [New Line].");
Serial.print("Print with a [New Line] explicitly added .\n ");
Serial.println("Print using the println() function.");

Serial.println('Hello1'); // <- Observe the program output


Serial.println("Hello2");
Serial.println(65, BIN);
Serial.println(65, DEC);
Serial.println(65, HEX);

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

Serial.println("Examine the printout for each statement and


evaluate the syntax used.");

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

Bin: 01101100 01101100 01101111 00110001 (on ESP32)


Dec: 1819045681

Bin: 01101111 00110001 (on Arduino Uno)


Dec: 28465

Sample printout for the


‘SerialPrintDemo.ino’ program
- Examine the format of each
line printed out and evaluate
the syntax used.
- How many time does the
program run ??

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

◦ If you need to run your sketch only once, use a ‘while(1);’ as


the last statement of the loop() function to terminate the
program -> a Dynamic Halt

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

 Arduino Language Reference -> a dictionary of Arduino


Programming Language
◦ Navigate the [Help] menu under the Arduino IDE to access a
local copy of the Arduino Language Reference

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

int c; // single declaration


int i, j, k; // multiple declarations
int p = 5; // single declaration and assignment
int r = 3, s = -9; // multiple declarations and assignments

float f; // single declaration


float x, y, z; // multiple declarations

float m = 0.0, n = 1.245e3, q = 2.468e-4;


// multiple declarations and assignment with ‘e’ notation

EEE3453 29/8/2022 56
 Example: Declaring boolean variables

boolean raining; // boolean is a ‘non-standard’


type alias for bool defined by Arduino
bool alarm; // declaration
bool running = false; // declaration and assignment
bool tankFull = true; // declaration and assignment

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:

int count; // declaring an integer variable with a


// name ‘count’

float Average; // declaring a floating-point variable with


// a name ‘Average’

float Interest = 0.05; // declaring a floating-point variable


// with a name ‘Interest’ and
// assigning it with an initial value
// of 0.05

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

Write an Arduino Sketch (CompoundInterest.ino) to calculate


the amount when the principal, interest rate and no. of years
are given.
You may apply sample data to test your sketch and print out the
calculated amount on the Serial Monitor.

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:

int F, Y, Q; // F, Y and Q are integer variables


float G; // G is a floating-point variable

Y = sizeof(F); // get the no. of bytes in the integer


// variable F
Q = sizeof(G); // get the no. of bytes in the floating-point
// variable G

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.

 Pin configured as INPUT -> appropriate pull-up or pull-down


resistor is needed for interfacing external devices (e.g.
switches, push buttons or sensors)

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.

 INPUT_PULLUP – to be used in relevant digital pinouts with


internal pull-up, NOT to be discussed in EEE3453

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

Simple Digital I/O with a Push-button and a LED

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

int Button = 5; // Button is mapped to pin 5


int Led = 6; // Led is mapped to pin 6

void setup () {

pinMode(Button, INPUT); // set the Button pin as input


pinMode(Led, OUTPUT); // set the Led pin as output

EEE3453 29/8/2022 80
void loop() {

if (digitalRead(Button) == LOW) // if Button pressed


{
digitalWrite(Led, HIGH); // -> turn ON Led
delay(1000); // delay for 1000 ms
}
else {
digitalWrite(Led, LOW); // -> turn OFF Led
delay(1000); // delay for 1000 ms
}

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;

(Note: A PI constant has been pre-defined with a value of 3.14159… .)

EEE3453 29/8/2022 84
 Example:

Consider the following sequence of statements:

int x, y;
x = 3;
y = x;
x = 5;

What are the values of x and y after the program segment is


executed ?

EEE3453 29/8/2022 85
 Arduino offers 5 basic arithmetic operators for mathematical
computations:

Operations Symbol Example


Addition + Y = a + b;
Subtraction - Y = b – a;
Multiplication * Y = a * b;
Division / Y = b/a;
Remainder / Modulo % Y = a % b;

EEE3453 29/8/2022 86
 Examples: Declaring integer variables and perform arithmetic
operations

int Num1 = 15;


int Num2 = 3;
int Sum = Num1 + Num2;
int Difference = Num1 - Num2;
int Product = Num1 * Num2;
int Quotient = Num1 / Num2;
int Remainder = Num1 % Num2;
// What are the results for each arithmetic operation ??

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;

What values are stored in i and j in each case ?


Ans.: (i) i ← 0, j ← 2 (ii) i ← 2, j ← 4

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;

What values are stored in y and z ??


Ans.: y ← 1.5, z ← 0.0

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;

What values are stored in w, x, y and z ??


Ans.: w ← 1.333, x ← 0.333, y ← 1.000, z ← -0.000

EEE3453 29/8/2022 90
 Arduino offers 6 relational operators:

Relational Operations Symbols Example


Less than < currentYear < 2020
Less than or equal to <= currentYear <= 2020
Not equal to != nextYear != 2021
Equal to == nextYear == 2020
Greater than > currentYear > 2018
Greater than or equal to >= currentYear >= 2019

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.

 There are 3 logical operators in Arduino IDE:


Logical Operation Symbol Example
OR || Y = A || B;
AND && Y = A && B;
NOT ! Y = !B;

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

 Two possible structures of increment operator:


◦ Variable_Name++ : a post-increment operation
 the variable is first used in the statement and
incremented after the statement execution
◦ ++Variable_Name : a pre-increment operation
 the variable is incremented before execution of the
statement

EEE3453 29/8/2022 97
 Decrement Operator
◦ an arithmetic operator that decrements an integer variable
by a value of one

 Two possible structures of increment operator:


◦ Variable_Name – – : a post-decrement operation
 this means that the variable is first used in the statement
and decremented after the statement execution
◦ – – Variable_Name : a pre-decrement operation
 this means that the variable is decremented before
execution of the statement

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;

What are the values of R, S, W and Y after the program segment is


executed ??

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

EEE3453 29/8/2022 100

You might also like