0% found this document useful (0 votes)
55 views58 pages

Sehs3317 L5

Here are the key steps: 1. Define variables and assign values 2. Use relational and equality operators in if conditions to check relationships between variables 3. The body of the if statement will execute if the condition is true For example: int x = 5; int y = 3; if (x > y) { // body of if statement } This checks if x is greater than y, and if so, executes the body of the if statement.

Uploaded by

李里奧
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)
55 views58 pages

Sehs3317 L5

Here are the key steps: 1. Define variables and assign values 2. Use relational and equality operators in if conditions to check relationships between variables 3. The body of the if statement will execute if the condition is true For example: int x = 5; int y = 3; if (x > y) { // body of if statement } This checks if x is greater than y, and if so, executes the body of the if statement.

Uploaded by

李里奧
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/ 58

Lecture 5: Basic Arduino

programming using C/C++

1
Objectives
• In this lecturer, we will introduce the Arduino
Programming
– Revision on C/C++ language
– Arduino functions

2
History of C
• Evolved by Ritchie from two previous programming
languages, BCPL and B
• Used to develop UNIX
• Used to write modern operating systems
• Hardware/platform independent and portable
• It supports low-level manipulation
• By late 1970's C had evolved to "Traditional C“
• In 1985, it was revolute into C++ for adding object-
oriented programming to C language
Procedural Programming
• One of the most common forms of programming
in high-level languages is called procedural
programming
– Instructions are run sequentially
– Instructions are structured so that they can be tested
and debugged easily
• In procedural programming, computer
instructions are often grouped into logical units
called procedures
• In C programming, procedures are referred to as
functions
Object Oriented Programming (OOP)

• Object is programming code and data that can be


treated as an individual unit or component
• Reusable software components that model items in the
real world
• Meaningful software units
– Date objects, time objects, paycheck objects, invoice objects,
audio objects, video objects, file objects, record objects, etc.
– Any noun can be represented as an object
• More understandable, better organized, and easier to
maintain than procedural programming
• Favor modularity
Basics of a Typical C Program Development Environment
Program is created in
the editor and stored
Editor
• Phases of C++ Programs: Disk on disk.
Preprocessor program
Preprocessor Disk processes the code.
1. Edit Compiler creates
Compiler Disk object code and stores
2. Preprocess it on disk.
Linker Disk Linker links the object
3. Compile Primary Memory
code with the libraries

Loader
4. Link Loader puts program
in memory.
Disk ..

5. Load ..
..

Primary Memory
CPU takes each
6. Execute CPU instruction and
executes it, possibly
7. Debug ..
storing new data
.. values as the program
..
executes.
Data Types (1)
• A data type is the specific
category of information
that a variable contains
• It determines how much
memory to allocate for
the data, as well as the
types of operations that
can be performed on a
variable
Data types (2)
• C data types:
– Integer (int) is a positive or negative number with no
decimal places
• Can be unsigned (unsigned int): always positive
• Can use decimal, octal and hexadecimal number system
• E.g. int a = 123;
– floating-point number (float, double) contains decimal
places or is written using exponential notation
• Can use scientific and exponential notation
• E.g. float a = 1.234;
Data types (3)
• C data types (cont.):
– Character (char) variable is used to store a single
character
• E.g. char a = ‘a’;
– String (a char array) variable is used to a character
strings
• E.g. char str[] = “Hello world!”;
– Boolean (bool) variable can store true or false logic
value only
• E.g. bool t = true;
Type Casting
• Casting, or type casting, copies the value
contained in a variable of one data type into a
variable of another data type
• The C++ syntax for casting variables is
variable = new_type (old_variable);
– E.g. float a = 1000.123;
int b = (int) a; //b = 1000
Constant
• There are two methods of creating constants in
C: the #define statement or the const keyword
• The #define statement is a preprocessor
directive that defines a constant
• You place a #define statement at the beginning
of a file, just as you do with the #include
statement
Arithmetic (1)
• Arithmetic calculations
– Use * for multiplication and / for division
– Integer division truncates remainder
• 7 / 5 evaluates to 1
– Modulus operator(%) returns the remainder
• 7 % 5 evaluates to 2
• Operator precedence
– Some arithmetic operators act before others (i.e., multiplication
before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Arithmetic (2)
• Arithmetic operators:
C operation Arithmetic operator Algebraic expression C expression

Addition + f+7 f + 7

Subtraction - p–c p - c

Multiplication * bm b * m

Division / x/y x / y

Modulus % r mod s r % s

• Rules of operator precedence:


Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is
evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not
nested), they are evaluated left to right.

*, /, or % Multiplication,Division, Evaluated second. If there are several, they are


Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.
Decision Making: Equality and Relational Operators (1)
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7; (Leftm ost multip lic ation)
2 * 5 is 10

Step 2. y = 10 * 5 + 3 * 5 + 7; (Leftm ost multip lic ation)


10 * 5 is 50

Step 3. y = 50 + 3 * 5 + 7; (Multip lic ation before ad dition)


3 * 5 is 15

Step 4. y = 50 + 15 + 7; (Leftm ost ad dition)


50 + 15 is 65

Step 5. y = 65 + 7; (Last a dd ition)


65 + 7 is 72

Step 6. y = 72; (Last op era tio n—p la c e 72 in y)


Decision Making: Equality and Relational Operators (2)

• Executable statements
– Perform actions (calculations, input/output of data)
– Perform decisions
• May want to print "pass" or "fail" given the value of a test grade
• if control statement
– Simple version in this section, more detail later
– If a condition is true, then the body of the if statement
executed
• 0 is false, non-zero is true
– Control always resumes after the if structure
• Keywords
– Special words reserved for C
– Cannot be used as identifiers or variable names
Decision Making: Equality and Relational Operators (3)

Standard algebraic equality C equality or Example of C Meaning of C condition


operator or relational operator relational operator condition
Equality Operators
= == x == y x is equal to y

 != x != y x is not equal to y

Relational Operators
> > x > y x is greater than y
< < x < y x is less than y
>= >= x >= y x is greater than or equal to y
<= <= x <= y x is less than or equal to y
Decision Making: Equality and Relational Operators (4)

Operators Associativity
* / % left to right
+ - left to right
< <= > >= left to right
== != left to right
= right to left
Fig. 2.14 Precedence and associativity of the operators discussed so far.

Keywords

auto double int struct

break else long switch


case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Fig. 2.15 C’s reserved keywords.
Adding Comments to a Program
• Comments are nonexecuting
lines that you place in your
code that contain various
types of remarks

– Important in program
development in team and
maintenance

• C supports block comments


(/* */) only but usually also
support line comments (//)
Control Structures
• Sequential execution
– Statements executed one after the other in the order written
• Transfer of control
– When the next statement executed is not the next one in
sequence
– Instruction jump is occurred
• All programs written in terms of 3 control structures
– Sequence structures: Built into C. Programs executed
sequentially by default
– Selection structures: C has three types: if and if…else
– Repetition structures: C has three types: while, do…while and
for

19
The if Selection Statement
• Selection structure:
– Used to choose among alternative courses of action
– Pseudocode:
If student’s grade is greater than or equal to 60
Print “Passed”
– C code:
if ( grade >= 60 )
printf( "Passed\n" );
• If condition true
– Print statement executed and program goes on to next
statement
– If false, print statement is ignored and the program goes
onto the next statement
– Indenting makes programs easier to read
• C ignores whitespace characters
20
The if…else Selection
Statement (1)
• if
– Only performs an action if the condition is true
• if…else
– Specifies an action to be performed both when the condition is
true and when it is false
• Psuedocode:
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
• C code:
if ( grade >= 60 )
printf( "Passed\n");
else
printf( "Failed\n");
The if…else Selection
Statement (2)
– Pseudocode for a nested if…else statement
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
The if…else Selection
Statement (3)
• Compound statement:
– Set of statements within a pair of braces
– Example:
if ( grade >= 60 )
printf( "Passed.\n" );
else {
printf( "Failed.\n" );
printf( "You must take this course
again.\n" );
}
– Without the braces, the statement
printf( "You must take this course
again.\n" );
would be executed automatically
The Essentials of Repetition (1)
• Loop
– Group of instructions computer executes repeatedly
while some condition remains true
• Counter-controlled repetition
– Definite repetition: know how many times loop will
execute
– Control variable used to count repetitions
• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not known
– Sentinel value indicates "end of data"
Essentials of Counter-Controlled
Repetition (2)
• Counter-controlled repetition requires
– The name of a control variable (or loop counter)
– The initial value of the control variable
– An increment (or decrement) by which the control
variable is modified each time through the loop
– A condition that tests for the final value of the control
variable (i.e., whether looping should continue)
The while Repetition Statement
• Repetition structure
– Programmer specifies an action to be repeated while
some condition remains true
– Psuedocode:
While there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false
• Example:
int product = 2;
while ( product <= 1000 )
product = 2 * product;
The for Repetition Statement
• Format when using for loops
for ( initialization; loopContinuationTest; increment )
statement
• For loops can usually be rewritten as while loops:
initialization;
while ( loopContinuationTest ) {
statement;
increment;
}
• Initialization and increment
– Can be comma-separated lists
– Example:
for (int i = 0, j = 0; j + i <= 10; j++, i++)
printf( "%d\n", j + i );
– "Increment" may be negative (decrement)
– If the loop continuation condition is initially false
• The body of the for statement is not performed
• Control proceeds with the next statement after the for statement
The break and continue
Statements
• break
– Causes immediate exit from a while, for, do…while
or switch statement
– Program execution continues with the first statement
after the structure
– Common uses of the break statement
• Escape early from a loop
• Skip the remainder of a switch statement
The break and continue
Statements
• continue
– Skips the remaining statements in the body of a
while, or for statement
• Proceeds with the next iteration of the loop
– while
• Loop-continuation test is evaluated immediately after the
continue statement is executed
– for
• Increment expression is executed, then the loop-continuation
test is evaluated
Logical Operators (1)
• && ( logical AND )
– Returns true if both conditions are true
• || ( logical OR )
– Returns true if either of its conditions are true
• ! ( logical NOT, logical negation )
– Reverses the truth/falsity of its condition
– Unary operator, has one operand
• Useful as conditions in loops
Expression Result
true && false false
true || false true
!false true
Logical Operators (2)
expression1 expression2 expression1 && expression2
0 0 0
0 nonzero 0
nonzero 0 0
nonzero nonzero 1
Fig. 4.13 Truth table for the && (logical AND) operator.

expression1 expression2 expression1 || expression2


0 0 0
0 nonzero 1
nonzero 0 1
nonzero nonzero 1
Fig. 4.14 Truth table for the logical OR (||) operator.

expression ! expression
0 1
nonzero 0
Fig. 4.15 Truth table for operator ! (logical negation).
Logical Operators (3)
Operators Associativity Type
++ -- + - ! (type) right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
, left to right comma
Fig. 4.16 Operator precedence and associativity.
Confusing Equality (==) and
Assignment (=) Operators (1)
• Dangerous error
– Does not ordinarily cause syntax errors
– Any expression that produces a value can be used in
control structures
– Nonzero values are true, zero values are false
– Example using ==:
if ( payCode == 4 )
printf( "You get a bonus!\n" );
• Checks payCode, if it is 4 then a bonus is awarded
Confusing Equality (==) and
Assignment (=) Operators (2)
– Example, replacing == with =:
if ( payCode = 4 )
printf( "You get a bonus!\n" );
• This sets payCode to 4
• 4 is nonzero, so expression is true, and bonus awarded no
matter what the payCode was
– Logic error, not a syntax error
Confusing Equality (==) and
Assignment (=) Operators (3)
• lvalues
– Expressions that can appear on the left side of an equation
– Their values can be changed, such as variable names
• x = 4;

• rvalues
– Expressions that can only appear on the right side of an
equation
– Constants, such as numbers
• Cannot write 4 = x;
• Must write x = 4;
– lvalues can be used as rvalues, but not vice versa
• y = x;
Assignment Operators (1)
• Assignment operators abbreviate assignment
expressions
c = c + 3;
can be abbreviated as c += 3; using the addition assignment
operator
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Examples of other assignment operators:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Assignment Operators (2)
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
Assignment operator Sample expression Explanation Assigns
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
/= f /= 3 f = f / 3 2 to f
%= g %= 9 g = g % 9 3 to g
Fig. 3.11 Arithmetic assignment operators.
Increment and Decrement
Operators (1)
• Increment operator (++)
– Can be used instead of c+=1
• Decrement operator (--)
– Can be used instead of c-=1
• Preincrement
– Operator is used before the variable (++c or --c)
– Variable is changed before the expression it is in is evaluated
• Postincrement
– Operator is used after the variable (c++ or c--)
– Expression executes before the variable is changed
Increment and Decrement
Operators (2)
• If c equals 5, then
printf( "%d", ++c );
– Prints 6
printf( "%d", c++ );
– Prints 5
– In either case, c now has the value of 6
• When variable not in an expression
– Preincrementing and postincrementing have the same effect
++c;
printf( “%d”, c );
– Has the same effect as
c++;
printf( “%d”, c );
Increment and Decrement
Operators (3)
Operator Sample expression Explanation
++ ++a Increment a by 1 then use the new value of a in the expression in
which a resides.
++ a++ Use the current value of a in the expression in which a resides, then
increment a by 1.
-- --b Decrement b by 1 then use the new value of b in the expression in
which b resides.
-- b-- Use the current value of b in the expression in which b resides, then
decrement b by 1.
Fig. 3.12 The increment and decrement operators

Operators Associativity Type


++ -- + - (type) right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
?: right to left conditional
= += -= *= /= right to left assignment
Fig. 3.14 Precedence of the operators encountered so far in the text.
Program Modules in C
• Functions
– Modules in C
– Programs combine user-defined functions with library
functions
• C standard library has a wide variety of functions
• Function calls
– Invoking functions
• Provide function name and arguments (data)
• Function performs operations or manipulations
• Function returns results
Functions
• Functions
– Modularize a program
– All variables defined inside functions are local variables
• Known only in function defined
– Parameters
• Communicate information between functions
• Local variables
• Benefits of functions
– Divide and conquer
• Manageable program development
– Software reusability
• Use existing functions as building blocks for new programs
• Abstraction - hide internal details (library functions)
– Avoid code repetition
Function Definitions (1)
• Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Function-name: any valid identifier
– Return-value-type: data type of the result (default int)
• void – indicates that the function returns nothing
– Parameter-list: comma separated list, declares
parameters
• A type must be listed explicitly for each parameter unless, the
parameter is of type int
Function Definitions (2)
• Function definition format (continued)
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Definitions and statements: function body (block)
• Variables can be defined inside blocks (can be nested)
• Functions can not be defined inside other functions
– Returning control
• If nothing returned
– return;
– or, until reaches right brace
• If something returned
– return expression;
Calling Functions: Call by Value
and Call by Reference
• Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify argument
• Avoids accidental changes
• Call by reference
– Passes original argument
– Changes in function effect original
– Only used with trusted functions
Storage Classes (1)
• Storage class specifiers
– Storage duration – how long an object exists in
memory
– Scope – where object can be referenced in program
• Automatic storage
– Object created and destroyed within its block
– auto: default for local variables
auto double x, y;

– register: tries to put variable into high-speed


registers
• Can only be used for automatic variables
register int counter = 1;
Storage Classes (2)
• Static storage
– Variables exist for entire program execution
– Default value of zero
– static: local variables defined in functions.
• Keep value after function ends
• Only known in their own function
– extern: default for global variables and functions
• Known in any function
Scope Rules (1)
• File scope
– Identifier defined outside function, known in all
functions
– Used for global variables, function definitions, function
prototypes
• Function scope
– Can only be referenced inside a function body
– Used only for labels (start:, case: , etc.)
Scope Rules (2)
• Block scope
– Identifier declared inside a block
• Block scope begins at definition, ends at right brace
– Used for variables, function parameters (local
variables of function)
– Outer blocks "hidden" from inner blocks if there is a
variable with the same name in the inner block
• Function prototype scope
– Used for identifiers in parameter list
Arduino built in functions (1)
• For controlling the Arduino board and performing
computations.
• Reference: https://www.arduino.cc/reference/en/
– Digital I/O – Zero, Due & MKR Family
• digitalRead() • analogReadResolution()
• digitalWrite() • analogWriteResolution()
• pinMode()
– Advanced I/O
– Analog I/O
• noTone()
• analogRead()
• analogReference() • pulseIn()
• analogWrite() • pulseInLong()
• shiftIn()
• shiftOut()
• tone()
Arduino built in functions (2)
– Time – Characters
• delay() • isAlpha()
• delayMicroseconds() • isAlphaNumeric()
• micros() • isAscii()
• millis() • isControl()
– Math • isDigit()
• abs() • isGraph()
• constrain() • isHexadecimalDigit()
• map() • isLowerCase()
• max() • isPrintable()
• min() • isPunct()
• pow() • isSpace()
• sq() • isUpperCase()
• sqrt() • isWhitespace()
– Trigonometry – Random Numbers
• cos() • random()
• sin() • randomSeed()
• tan()
Arduino built in functions (3)
– Bits and Bytes – Interrupts
• bit() • interrupts()
• bitClear() • detachinterrupt()
• bitRead() – Communication
• bitSet() • Serial
• bitWrite() • Stream
• highByte()
– USB
• lowByte()
• Keyboard
– External Interrupts • Mouse
• attachInterrupt()
• detachInterrupt()
Arduino variables
• Other than the conventional C/C++ data types,
Arduino has:
– Constants:
• HIGH | LOW
• INPUT | OUTPUT | INPUT_PULLUP
• LED_BUILTIN
– Data types:
• Word
– Utilities
• PROGMEM

53
Additional Arduino libraries
• Some devices require addition libraries for
controls
• They are required to be installed to Arduino
software separately.
• They can be downloaded at the web site:
– https://www.arduino.cc/en/Reference/Libraries
• Install the library in the library manager of
Arduino IDE
– Menu -> Include -> Mange Libraries OR
– Menu -> Include -> Add .Zip Library… OR
– Manual installation
Arduino example
• Description:
– This example shows the simplest thing you can do
with an Arduino to see physical output: it blinks an
LED.
• Hardware Required
– Arduino Board
– LED
– Resistor, anything between 220 ohm to 1K ohm

55
Circuit & Schematic

56
Sketch
• // the setup function runs once when you press reset or power
the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH
is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by
making the voltage LOW
delay(1000); // wait for a second
}

57
Summary
• In this lecture, the Arduino progamming are
introduced
– Revision on C/C++ language
– Arduino functions
• In next lecture, we will discuss the advanced
Arduino programming

END
58

You might also like