Sehs3317 L5
Sehs3317 L5
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)
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
• 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)
!= 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
– Important in program
development in team and
maintenance
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.
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
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