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

Arduino Workshop With SLN

Here are the key points about data types in C/C++: - Boolean data type holds one of two values, true or false, occupying 1 byte. - Char data type takes 1 byte to store a character value represented by its ASCII code. It allows arithmetic operations on characters. - byte and uint_8 both store an unsigned 8-bit number from 0 to 255, occupying 1 byte. - Common data types include int, long, float, and double to store different sizes of integer and floating-point numbers. - Choosing the appropriate data type depending on the value range and storage space required is important for efficient memory usage and avoiding errors. - The ASCII table maps character codes to

Uploaded by

Tan Li Kar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Arduino Workshop With SLN

Here are the key points about data types in C/C++: - Boolean data type holds one of two values, true or false, occupying 1 byte. - Char data type takes 1 byte to store a character value represented by its ASCII code. It allows arithmetic operations on characters. - byte and uint_8 both store an unsigned 8-bit number from 0 to 255, occupying 1 byte. - Common data types include int, long, float, and double to store different sizes of integer and floating-point numbers. - Choosing the appropriate data type depending on the value range and storage space required is important for efficient memory usage and avoiding errors. - The ASCII table maps character codes to

Uploaded by

Tan Li Kar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Contents

Arduino – Basic...............................................................................................................................2
Board Description........................................................................................................................3
Program Structure........................................................................................................................6
C / C++ – Basic................................................................................................................................8
Naming Conventions...................................................................................................................9
Data Types.................................................................................................................................10
Variables & Constants...............................................................................................................16
Operators....................................................................................................................................19
Control Statement......................................................................................................................23
Loops.........................................................................................................................................32
Arrays........................................................................................................................................37
Char Arrays / Strings.................................................................................................................40
Functions....................................................................................................................................44
Working of default arguments...............................................................................................45
Arduino – Function Libraries........................................................................................................48
I/O Functions.............................................................................................................................49
Time...........................................................................................................................................52
Pulse Width Modulation............................................................................................................62
Sensors.......................................................................................................................................67
Arduino – Basic
Board Description
17 15
16

14

13

12
4

3 11

7 8 9 10

5 6

1. Power USB
Arduino board can be powered by using the USB cable from your computer. This is also used for
flashing program into the Arduino and serial communication between your computer and the
Arduino.

2. Power (Barrel Jack)


Arduino boards can be powered directly from the AC mains power supply by connecting it
to the Barrel Jack (2). The recommended input voltage for this jack is 7 to 12 volts.

3. Voltage Regulator
It is used to regulate the voltage of power supple input from Barrel Jack and Vin pin to 5V.
4. Crystal Oscillator
The crystal oscillator determines the clock frequency of the Arduino.

5. Arduino Reset
To reset your Arduino board, i.e., start your program from the beginning. You can
reset the UNO board in two ways.
 by using the reset button (17) on the board.
 connect an external reset button to the Arduino pin labelled RESET (5).

(6. 7. 8. 9.) Pins (3.3, 5, GND, Vin)


 3.3V (6): Supply 3.3 output volt
 5V (7): Supply 5 output volt
 GND (8) (Ground): There are several GND pins on the Arduino, any of which can be
used to ground your circuit.
 Vin (9): This pin also can be used to power the Arduino board from an external power
source. The recommended input voltage for this jack is 7 to 12 volts. Unlike the Barrel
Jack, the Vin pin don’t have reverse polarity protection.

QUESTION:
What will happen when you connect both Power USB and Power (Barrel Jack / Vin Pin) at
the same time?

Ans : Arduino will select Power to be used as the supply. This is because there is a
MOSFET in the supply circuit. When Power have voltage flowing through, it will switch on
the MOSFET stopping disconnecting the supply from Power USB.

10. Analog pins


The Arduino UNO board has five analog input pins A0 through A5. These pins can read the
signal from an analog sensor like the humidity sensor or temperature sensor and convert it into a
digital value that can be read by the microprocessor. These pins can also be configured for digital
inputs.

11. Main microcontroller


It is the brain of the board.

12. ICSP pin


ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of MOSI, MISO,
SCK, RESET, VCC, and GND. These pins enable the user to program the Arduino boards’
firmware in case of damage / missing bootloader. It is can also be used for SPI (Serial Peripheral
Interface).
13. Power LED indicator
This LED indicate that your board is powered up correctly. If this light does not turn on, then
there is something wrong with the connection.

14. TX and RX LEDs


On your board, you will find two labels: TX (transmit) and RX (receive). They appear in two
places on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate the pins
responsible for serial communication. Second, the TX and RX led (13). The TX led flashes with
different speed while sending the serial data. The speed of flashing depends on the baud rate
used by the board. RX flashes during the receiving process.

15. Digital I / O
The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse Width
Modulation) output. These pins can be configured to work as input digital pins to read logic
values (0 or 1) or as digital output pins to drive different modules like LEDs, relays, etc. The
pins labeled “~” can be used to generate PWM.

16. AREF
AREF stands for Analog Reference. It is sometimes, used to set an external reference voltage
(between 0 and 5 Volts) as the upper limit for the analog input pins.
Program Structure
Software structure consist of two main functions:
 Setup( ) function
 Loop( ) function

void setup () {

 Purpose: The setup() function is used to initialize the variables, pin modes, start using
libraries, etc. The setup function will only run once, after each power up or reset of the
Arduino board.
void loop() {

 Purpose: The loop() function loops consecutively, allowing your program to change and
respond.
C / C++ – Basic
Naming Conventions
Why should we have a naming convention and what are its advantages?
Naming conventions result in improvements in terms of "four Cs":
 communication
 code integration
 consistency
 Clarity

The name that you give to the variable should be self-explanatory.


Examples: roomNum, humiSensor

Common Naming Conventions


 Camel Case
First letter with a lower case and every first letter of next word is capitalized with no spaces or
symbols between words.
Examples: userAccount, fedEx, fileName

 Pascal Case
Identical to Camel Case but every first latter of the words are capitalized with no spaces or
symbols between words
Examples: UserAccount, FedEx, FileName

 Snake Case
Words within phrases or compound words are separated with an underscore.
Examples: first_name, error_message, account_balance
Data Types
Boolean
A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte of
memory.
Example

bool val = false ; // declaration of variable with type boolean and initialize it with false

bool state = true ; // declaration of variable with type boolean and initialize it with true

Char
A data type that takes up one byte (from -127 to 127) of memory that stores a character value.
The characters are stored as numbers. This means that it is possible to do arithmetic operations
on characters, in which the ASCII value of the character is used.

Example

char char_a = ‘a’ ; // declaration of variable with type char and initialize it with character a

char chr_c = 97 ; //declaration of variable with type char and initialize it with character 97
Try It Out

void setup() {
Serial.begin(9600);

char firstChar = 'a';


char secondChar = 97;

Serial.print("this is first char : ");


Serial.println(firstChar);
Serial.print("this is second char : ");
Serial.println(secondChar);

void loop() {

}
Test Yourself

Try printing the character ‘o’ in serial monitor using the number of the character.

Hint
Refer to the ASCII table.

Ans
void setup() {
Serial.begin(9600);

char secondChar = 111;


Serial.println(secondChar);

void loop() {

byte / uint_8
both byte and uint_8 store an 8-bit unsigned number, from 0 to 255.

Example

byte m = 25 ; //declaration of variable with type byte and initialize it with 25

uint_8 = 25 ; //declaration of variable with type uint_8 and initialize it with 25

int
Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value for
Arduino Uno. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a
maximum value of (2^15) - 1).

Example

int counter = 32 ; // of variable with type int and initialize it with 32


long
Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from
2,147,483,648 to 2,147,483,647.

Example

long velocity = 102346 ; //declaration of variable with type Long and initialize it with 102346
unsigned char
Same as char. However, it only stores positive number ranging from 0 to 255.

Example

unsigned char char_a = ‘a’ ; // declaration of variable with type char and initialize it with
character a

unsigned char chr_c = 97 ; //declaration of variable with type char and initialize it with
character 97

unsigned int
Same as int. However, it only stores positive number ranging from 0 to 65535 (2^16) - 1).

Example

unsigned int counter= 60 ; // declaration of variable with type unsigned int and initialize it with
60

unsigned long
Same as long. However, it only stores positive number ranging from 0 to 4,294,967,295 (2^32 -
1).

Example

unsigned long velocity = 101006 ; // declaration of variable with type Unsigned Long and
initialize it with 101006
float / double
Data type for floating-point number is a number that has a decimal point. In Arduino Uno, the
size of float and double is the same with the range of -3.4028235E+38 and 3.4028235E+38.

Example

float num = 1.352; //declaration of variable with type float and initialize it with 1.352

double num = 45.352 ; // declaration of variable with type double and initialize it with 45.352

Type Casting
Typecasting is making a variable of one type, such as an int, act like another type, a char, for one
single operation.

Syntax

(dataType) variableName ;

// or

static_cast<dataType> ( variableName ) ;
Variables & Constants
What is Variable Scope?
There are three places where variables can be declared. They are:
 Inside a function or a block, which is called local variables.
 In the definition of function parameters, which is called formal parameters.
 Outside of all functions, which is called global variables.

Local Variable
Variables that are declared inside a function or block are local variables. They can be used only
by the statements that are inside that function or block of code. Local variables are not known to
function outside their own.
Example

void setup(){

void loop(){

int x, y, z; // these are local variable

}
Try It Out
void setup() {
Serial.begin(9600);

char firstChar = 'a'; //these are local variables


char secondChar = 97;

void loop() {

Serial.print("this is first char : ");


Serial.println(firstChar);
Serial.print("this is second char : ");
Serial.println(secondChar);
}

//the above code will result in an error because firstChar and secondChar are local variable. The
firstChar and secondChar have no value assign to it in the loop function

Global Variable

Global variables are defined outside of all the functions, usually at the top of the program. The
global variables will hold their value throughout the life-time of your program.

A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration.

Example

int x, y, z; // these are global variable

void setup(){

void loop(){

}
Formal parameters

Formal parameters define information that is passed to a function.

Example

formal
int sum_func (int x, int y) // function declaration {
parameters
int z = 0;
z = x+y ;
return z; // return the value
}

void setup () {

int result = 0 ;
result = sum_func (5,6) ; // function call
actual parameters

void loop () {

Constants
Constants are expressions with a fixed value. The naming convention for constants is all
characters are capitalized.

Syntax

const dataType variableName = yourValue ;

const int WIDTH = 10 ;

//or

# define variableName yourValue


#define WIDTH 10
Operators
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then –
Operator Operator Description Example
name Symbol

assignment = Stores the value to the right of the A=B


operator equal sign in the variable to the left of
the equal sign.

addition + Adds two operands A + B will give 30

subtraction - Subtracts second operand from the A - B will give -10


first

multiplication * Multiply both operands A * B will give 200

division / Divide numerator by denominator B / A will give 2

modulo % Modulus Operator and remainder of B % A will give 0


after an integer division

Comparison Operators

Assume variable A holds 10 and variable B holds 20 then –

Operator Operator Description Example


name Symbol

equal to == Checks if the value of two operands is (A == B) is not


equal or not, if yes then condition true
becomes true.

not equal to != Checks if the value of two operands is (A != B) is true


equal or not, if values are not equal
then condition becomes true.

less than < Checks if the value of left operand is (A < B) is true
less than the value of right operand, if
yes then condition becomes true.

greater than > Checks if the value of left operand is (A > B) is not true
greater than the value of right
operand, if yes then condition
becomes true.

less than or <= Checks if the value of left operand is (A <= B) is true
equal to less than or equal to the value of right
operand, if yes then condition
becomes true.

greater than >= Checks if the value of left operand is (A >= B) is not
or equal to greater than or equal to the value of true
right operand, if yes then condition
becomes true.

Boolean Operators

Assume variable A holds 10 and variable B holds 20 then –

Operator Operator Description Example


name Symbol

and && Called Logical AND operator. If both (A && B) is true


the operands are non-zero then then
condition becomes true.

or || Called Logical OR Operator. If any of (A || B) is true


the two operands is non-zero then
then condition becomes true.

not ! Called Logical NOT Operator. Use to !(A && B) is false


reverses the logical state of its
operand. If a condition is true then
Logical NOT operator will make
false.
Bitwise Operators

Assume variable A holds 10 (0000 1010 in binary) and variable B holds 20 (0001 0100 in
binary) then –

Operator Operator Description Example


name Symbol

and & Binary AND Operator copies a bit to (A & B) will give 0
the result if it exists in both operands. which is 0000 0000

or | Binary OR Operator copies a bit if it (A | B) will give 30


exists in either operand. which is 0001 1110

xor ^ Binary XOR Operator copies the bit if (A ^ B) will give 30


it is set in one operand but not both. which is 0001 1110

not ~ Binary Ones Complement Operator is (~A ) will give -11


unary and has the effect of 'flipping' which is 1111 1010
bits.

shift left << Binary Left Shift Operator. The left A << 2 will give 40
operands value is moved left by the which is 0010 1000
number of bits specified by the right
operand.

shift right >> Binary Right Shift Operator. The left A >> 2 will give 2
operands value is moved right by the which is 0000 0010
number of bits specified by the right
operand.
Compound Operators

Assume variable A holds 10 and variable B holds 20 then –

Operator Operator Description Example


name Symbol

increment ++ Increment operator, increases integer A++ will give 11


value by one.

Decrement -- Decrement operator, decreases integer A-- will give 9


value by one

Compound += Add AND assignment operator. It B += A is equivalent


addition adds right operand to the left operand to B = B+ A
and assign the result to left operand

Compound -= Subtract AND assignment operator. It B - = A is equivalent


subtraction subtracts right operand from the left to B = B - A
operand and assign the result to left
operand

Compound *= Multiply AND assignment operator. It B*= A is equivalent


multiplication multiplies right operand with the left to B = B* A
operand and assign the result to left
operand

Compound /= Divide AND assignment operator. It B /= A is equivalent


division divides left operand with the right to B = B / A
operand and assign the result to left
operand

Compound %= Modulus AND assignment operator. It B %= A is equivalent


modulo takes modulus using two operands and to B = B % A
assign the result to left operand

Compound |= Bitwise inclusive OR and assignment A |= 2 is same as


bitwise or operator A=A|2

Compound &= Bitwise AND assignment operator A &= 2 is same as


bitwise and A=A&2
Control Statement
Control Statements are elements in Source Code that control the flow of program execution.
They are:
 If statement
 If … else statement
 If … else if … else statement
 Switch case statement
 Conditional Operator ? :

if statement
If the expression is true then the statement or block of statements gets executed otherwise these
statements are skipped.

if statement syntax

if (condition) statement; //this will only execute the statement if the if statement is true

if (condition){

// this will execute the statement1, statement2, statement3 if the if statement is true
statement1;
statement2;
statement3;

}
if Statement – Execution Sequence

Condition

True

Statement False

if … else statement
An if statement can be followed by an optional else statement, which executes when the
expression is false.

if … else Statement Syntax

if (condition){

Block of statements;
}
else{

Block of statements;
}
if…else Statement – Execution Sequence

Condition False

True

Statement Statement
if … else if … else statement
The if statement can be followed by an optional else if...else statement.

When using if … else if … else statements,

 An if can have zero or one else statement and it must come after any else if's.
 An if can have zero to many else if statements and they must come before the else.

if (condition_1){

Block of statements;

}
else{
Block of statements; // the else come before the else if, this is incorrect

}else if (condition_2) {

Block of statements; // the else if come after the else, this is incorrect
}

 Once an else if succeeds, none of the remaining else if or else statements will be tested.

if (condition_1){

Block of statements; // if condition_1 is false then it will check for condition_2

}else if (condition_2) {

Block of statements; // if condition_2 is true then it will skip all the remaining if …
else statement

}else if (condition_3) {

Block of statements;
} These if … else statement will be
else{ skipped if condition_2 is True

Block of statements;

}
if … else if …else Statements Syntax

if (condition_1){

Block of statements;

}else if (condition_2) {

Block of statements;

}
.
.
.
else{

Block of statements;

}
if … else if … else Statement Execution Sequence

Condition_1 False

Condition_2 False

True

True

Statement Statement Statement

Switch Case Statement

A switch statement compares the value of a variable to the values specified in the case
statements. When a case statement is found whose value matches that of the variable, the code in
that case statement is run.

The break keyword makes the switch statement exit, and is typically used at the end of each
case. Without a break statement, the switch statement will continue executing the following
expressions until a break, or the end of the switch statement is reached.
Switch Case Statement Syntax

switch (variable)
{
case constant_1:
// statements
break;

case constant_2:
// statements
break;

default:
// statements
break;

}
Switch Case Statement Execution Sequence

Switch
(Conditional Expression)

Statement
Case Co nstant_1 True
break;

False

Statement
Case Co nstant_2 True
break;

False

Default True Default Statement

Conditional Operator ? :

The ? is called a ternary operator because it requires three operands and can be used to replace if-
else statements.

? : conditional operator Syntax

expression1 ? expression2 : expression3

Expression1 is evaluated first. If its value is true, then expression2 is evaluated and expression3
is ignored. If expression1 is evaluated as false, then expression3 evaluates and expression2 is
ignored. The result will be a value of either expression2 or expression3 depending upon which of
them evaluates as True.

Example 1

if(y < 10) {


var = 30;
} else {
var = 40;
}

is equate to

var = (y < 10) ? 30 : 40;

Example 2

((bar > bash) ? bar : bash) = foo

In this example, 'foo' is assigned to 'bar' or 'bash', again depending on which is bigger.
Loops
A loop statement allows us to execute a statement or group of statements multiple times. C
programming language provides the following types of loops to handle looping requirements.

 while loop
 do … while loop
 for loop
 nested loop
 infinite loop

while loop
while loops will loop continuously, and infinitely, until the condition inside the parenthesis, ()
becomes false.

while loop Syntax

while (condition) {

Block of Statement;

while loop Execution Sequence

False condition

True

statement
do … while loop

The do…while loop is similar to the while loop. In the while loop, the loop-continuation
condition is tested at the beginning of the loop before performed the body of the loop. The do…
while statement tests the loop-continuation condition after performed the loop body. Therefore,
the loop body will be executed at least once.

do…while loop Syntax

do{

Block of Statements;

}while(condition)

do … while loop Execution Sequence

statement

True

condition

False
for loop

A for loop executes statements a predetermined number of times. The control expression for the
loop is initialized, tested and manipulated entirely within the for loop parentheses.

for loop Syntax

for ( initialize; control; increment or decrement)


{
// statement block
}

Example

for(int counter=2;counter <=9;counter++){

//statements block

for loop Execution Sequence


Counter = 2

False Counter <= 9

True
Counter = counter +1

Statement in the for


loop

Nested loop
One loop inside another loop.

Nested while loop Syntax

while (condition_1){

//statement block

while (condition_2){
//statement block
}

Nested do … while loop Syntax

do{
//statement block

do{
//statement block

}while(condition_2)

}while(condition_1)

Nested for loop Syntax

for ( initialize ;control; increment or decrement)


{
// statement block
for ( initialize ;control; increment or decrement)
{
// statement block
}
}

Infinite loop
It is the loop having no terminating condition, so the loop becomes infinite.

infinite loop Syntax


1. Using for loop

for(;;){

//statement block

2. Using while loop

while(1){

//statement block
}

3. Using do … while loop

do{

//statement block

}while(1)
Arrays
An array is a consecutive group of memory locations that are of the same type. To refer to a
particular location or element in the array, we specify the name of the array and the position
number of the particular element in the array.

Declaring Arrays
Arrays occupy space in memory. To specify the type of the elements and the number of elements
required by an array, use a declaration of the form:

dataType arrayName [ arraySize ] ;

Example

int a[10] ; //declaring an array of variable type int with a size of 10 named a
Initializing Array
1. Using for loop

int n[10] ;

for (int x = 0; x < 10 ; x++){

n[x] = 0 ; // this will fill all the element of n with 0

2. Using and initializer list

int n[10] = { 0 , 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;

Multidimensional Arrays
Arrays with two dimensions often represent tables of values consisting of information arranged
in rows and columns. To declare a multidimensional array, use a declaration of the form:

dataType arrayName [ arraySize1 ] [ arraySize2 ] … [ arraySizeN ] ;

Two-Dimensional Array
Two - dimensional array is the simplest form of a multidimensional array.
1. The basic form of declaring a two-dimensional array of size x, y:

data_type array_name[ arraySize1 ][ arraySize2 ] ;

Example

int x [ 3 ][ 3 ] ;
This will result in an array as the figure below:

Initializing 2D Array
1. Using for loop

int x[3][4] ;

for (int i = 0; i < 3 ; i ++){

for (int j = 0; j < 4 ; j ++){

x[i][j] = 0 ;

}
}

2. Using and initializer list

int n[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } ;

// or

int n[3][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10 ,11}
};
Char Arrays / Strings
Strings are used to store text. A string is an array of char variables. A string is a special array that
has one extra element at the end of the string, which always has the value of 0 (zero). This is
known as a "null terminated string".

Declaring and initializing char arrays / String


This example will show how to make a string.

char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

//or

char myword[] = "Hello";

//or

char myword[6] ;

myword [0] = 'H'; // the string consists of 5 characters


myword [1] = 'e';
myword [2] = 'l';
myword [3] = 'l';
myword [4] = 'o';
myword [5] = '\0'; // 6th array element is a null terminator

//or

String myword = “Hello” ;


Manipulating char arrays / String
We can alter a string array within a sketch as shown in the following sketch.
Example

void setup(){

char like[] = "I like coffee and cake"; // create a string


Serial.begin(9600);
// (1) print the string
Serial.println(like);

// (2) delete part of the string, however this only stop the characters after element 13 from
printing, the characters after element 13 are still exist in the memory.

like[13] = '\0';
Serial.println(like);

void loop(){

Test yourself
1. Change the “cake” in the char array to “tea”
2. Using String instead of char array to do the above example
Hint: for replacing like[13] in string use the syntax: myString.substring(from, to).
where:
 myString: a variable of type String
 from: the index to start the substring at
 to: the index to end the substring before
FYI: https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/
3. Change the “cake” in your string to “tea”
Hint: the element in the string can be accessed and change as in arrays. You can also
perform + operation on string.
ANS
1)
void setup(){

char like[] = "I like coffee and cake"; // create a string


Serial.begin(9600);
// (1) print the string

like[18]='t';
like[19]='e';
like[20]='a';
like[21]='\0';

Serial.println(like);

void loop(){

2)
void setup(){

String like = "I like coffee and cake"; // create a string


Serial.begin(9600);

like = like.substring(0, 13);

Serial.println(like);

void loop(){

}
3)
void setup(){

String like = "I like coffee and cake"; // create a string


Serial.begin(9600);

like=like.substring(0, 18);

like = like + "tea";

Serial.println(like);

void loop(){

}
Functions
Functions allow structuring the programs in segments of code to perform individual tasks. The
typical case for creating a function is when one needs to perform the same action multiple times
in a program.

Functions have several advantages:

 Functions help the programmer stay organized.


 Functions codify one action in one place so that the function only has to be thought about
and debugged once.
 This also reduces chances for errors in modification, if the code needs to be changed.
 Functions make the whole sketch smaller and more compact because sections of code are
reused many times.
 They make it easier to reuse code in other programs.

Type of value Identifier by which Parameters


returned by the the function can be passed to
function called function

ReturnType function_name (argument1, argument2, « ^

statements

Statements or
function body

Function Declaration
A function is declared outside any other functions, above or below the loop function. A function
prototype is optional for Arduino IDE. The Arduino IDE will create the function prototype
automatically. If the function return nothing, the ReturnType is void.
Example
int sum_func (int x, int y) ; // this is function prototype, this is optional

void setup () {
Serial.begin(9600);

int result;
result = sum_func(5,6); // function call
Serial.println(result);

void loop () {

int sum_func (int x, int y) {

int sum;
sum = x + y ;
return sum; // return the value

Working of default arguments


In C++ programming, you can provide default values for function parameters. If a function is
called by passing argument/s, those arguments are used by the function but if the argument/s are
not passed while invoking a function then, the default values are used. The default argument
must be declared after the arguments with no default argument.

Common mistakes when using Default argument


1. void add(int a, int b = 3, int c, int d = 4); //this is incorrect as int c is in between 2 default
arguments.
Example
int sum_func (int x, int y, int z = 0) {

int sum;
sum = x + y + z ;
return sum; // return the value

void setup () {
Serial.begin(9600);

int result;
result = sum_func(5,6); // this called the sum_func with x = 6 , y = 6, z = 0
Serial.println(result);
result = sum_func(5, 6, 7); // this called the sum_func with x = 6 , y = 6, z = 7
Serial.println(result);

void loop () {

Apply Your Knowledge


 Create a function called “alphabet” which print the character from ‘a’ to ‘z’
Hint:
 Use “for loop”
 Use ASCII table
 Remember characters in char are stored in numbers
 You need to type cast to display characters
Ans:
int alphabet () {

char a = 97;

for(int x = 0; x<26; x++){


Serial.print(char(a+x));
}

void setup () {
Serial.begin(9600);
alphabet();

void loop () {

}
Arduino – Function
Libraries
I/O Functions
pinMode() Function
The pinMode() function is used to configure a specific pin to behave either as an
input or an output. It is possible to enable the internal pull-up resistors with the
mode INPUT_PULLUP.
pinMode () Function Syntax

void setup ()
{
pinMode (pin , mode);
}

 pin: the number of the pin whose mode you wish to set
 mode: INPUT, OUTPUT, or INPUT_PULLUP.

Pins Configured as INPUT


Pins can be configured as INPUT by using:

pinMode(pin, INPUT) ;

pinMode(3,INPUT) ; // set pin to input without using built in pull up resistor

Pull-up Resistors
Pull-up resistors are often useful to steer an input pin to a known state if no input is present. In
Arduino there are built-in pull-up resistors in its pins. These built-in pull-up resistors are
accessed by setting the pinMode() as INPUT_PULLUP. This effectively inverts the behavior of
the INPUT mode (Active High --> Active Low), where HIGH means the sensor is OFF and
LOW means the sensor is ON.

pinMode(pin ,INPUT_PULLUP) ;

pinMode(3 ,INPUT_PULLUP) ; // set pin to input using built in pull up resistor


Question
Why do we bother using the pull-up resistors anyway?

Pins Configured as OUTPUT


Pins can be configured as OUTPUT by using:

pinMode(pin ,OUTPUT) ;

pinMode(3 ,OUTPUT) ; // set pin to output

digitalWrite() Function
The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin.

digitalWrite() Function Syntax


void loop()
{
digitalWrite (pin ,value);
}

 pin: the number of the pin whose mode you wish to set
 value: HIGH, or LOW.

digitalRead() Function
the digitalRead() function reads the value from a specified digital pin, either HIGH or LOW.

digitalRead() Function Syntax


int x;
void loop()
{
x = digitalRead(pin)
}
 pin: the Arduino pin number you want to read
analogRead( ) function
By using the analogRead() function, we can read the voltage applied to one of the pins. This
function returns a number between 0 and 1023, which represents voltages between 0 and 5 volts.
For example, if there is a voltage of 2.5 V applied to pin number A0, analogRead(A0) returns
512.

analogRead() function Syntax


analogRead(pin);
 pin: the number of the analog input pin to read from A0 to A5
Example
int analogPin = A3;//potentiometer wiper (middle terminal) connected to analog pin 3
int val = 0; // variable to store the value read

void setup(){

Serial.begin(9600); // setup serial


}

void loop(){

val = analogRead(analogPin); // read the input pin


Serial.println(val); // debug value

}
Time
Arduino provides four different time manipulation functions. They are-
 delay () function
 delayMicroseconds () function
 millis () function
 micros () function

delay() function
It accepts a single integer (or number) argument. This number represents the time (measured in
milliseconds). The program should wait until moving on to the next line of code when it
encounters this function. However, the problem is, the delay() function is not a good way to
make your program wait, because it is known as a “blocking” function.

Question:
How do we solve this limitation of delay() function ?

delay() function Syntax


delay (ms) ;
where, ms is the time in milliseconds to pause (unsigned long).

delayMicroseconds() function
Same as the delay() function with the only different is that delayMicroseconds() functions
represents the time in microseconds instead of milliseconds.

delay() function Syntax


delayMicroseconds (us) ;
where, us is the number of microseconds to pause (unsigned int)

millis() function
This function is used to return the number of milliseconds at the time, the Arduino board begins
running the current program.

millis() function Syntax


millis () ;

micros() function
Same as the millis() function with the only different is that micros() function return the number
of microseconds at the time, the Arduino board begins running the current program.

Non-Blocking delay
By using the millis() function, it enable us to perform non-blocking in our code.
Example
const int ledPin = 13;// the number of the LED pin

// Variables will change:


int ledState = LOW; // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0; // will store last time LED was updated

// constants won't change:


const long interval = 1000; // interval at which to blink (milliseconds)

void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}

void loop() {

unsigned long currentMillis = millis(); // get the current run time

if (currentMillis - previousMillis >= interval) {


//everything inside this “if” statement will be non-blocking
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}

// set the LED with the ledState of the variable:


digitalWrite(ledPin, ledState);
}
}
Project - Blinking LED
Components Required
You will need the following components -
 1x Breadboard
 1x Arduino Uno R3
 1x LED
 1x 330Ω Resistor
 2x Jumper

Circuit Diagram
Arduino Code

void setup()
{
// initialize digital pin 13 as an output.
pinMode(2, OUTPUT);
}
// the loop function runs over and over again forever
void loop()
{
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

Challenge
 add an additional LED to the circuit and modify your code so that one LED blink every
one second while the other LED blink every 3 second.
 Both LED are blinking simultaneously

Hint:
 use non-blocking delay

Ans
const int ledPin1 = 8;// the number of the LED pin
const int ledPin2 = 9;// the number of the LED pin

// Variables will change:


int ledState_led1 = LOW; // ledState used to set the LED
int ledState_led2 = LOW; // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis_led1 = 0; // will store last time LED was updated
unsigned long previousMillis_led2 = 0; // will store last time LED was updated

// constants won't change:


const long interval = 1000; // interval at which to blink (milliseconds)
const long interval_3sec = 3000; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
}

void loop() {

unsigned long currentMillis = millis(); // get the current run time

if (currentMillis - previousMillis_led1 >= interval) {


//everything inside this “if” statement will be non-blocking
// save the last time you blinked the LED
previousMillis_led1 = currentMillis;

// if the LED is off turn it on and vice-versa:


if (ledState_led1 == LOW) {
ledState_led1 = HIGH;
} else {
ledState_led1 = LOW;
}
}

if (currentMillis - previousMillis_led2 >= interval_3sec) {


//everything inside this “if” statement will be non-blocking
// save the last time you blinked the LED
previousMillis_led2 = currentMillis;

// if the LED is off turn it on and vice-versa:


if (ledState_led2 == LOW) {
ledState_led2 = HIGH;
} else {
ledState_led2 = LOW;
}
}

// set the LED with the ledState of the variable:


digitalWrite(ledPin1, ledState_led1);
digitalWrite(ledPin2, ledState_led2);
}
Project – Running LED
Components Required
You will need the following components -
 1x Breadboard
 1x Arduino Uno R3
 8x LED
 8x 330Ω Resistor
 9x Jumper

Circuit Diagram
Arduino Code
//this code allow the LED to blink from left to right
int PIN_NUM = 8;
int pins[PIN_NUM] = {3, 4, 5, 6, 7, 8, 9, 10};

void setup () {

for(int x = 0; x < PIN_NUM; x++){


pinMode(pins[x], OUTPUT);
}

void loop() {

for(int x = 0; x < PIN_NUM; x++){


digitalWrite(pins[x], HIGH);
delay(500);
digitalWrite(pin[x], LOW);
delay(500);
}
}
Challenge

 Modify the code so that the LED blink from right to left.

Hint
 Access the array from the right most index to the left most index

Project - Reading Analog Voltage


Components Required
You will need the following components:
 1x Breadboard
 1x Arduino Uno R3
 1x 10K variable resistor (potentiometer)
 3x Jumper

Circuit Diagram
Arduino Code

void setup()
{
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

void loop()
{
// read the input on analog pin 0:
int sensorValue = analogRead(A0);

// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// float voltage = map(sensorValue, 0, 1023, 0 5); //you can also use this

// print out the value you read:


Serial.println(voltage);
}

Pulse Width Modulation


PWM has many applications such as controlling servos and speed controllers, limiting the
effective power of motors and LEDs.

Basic Principle of PWM


Pulse width modulation is basically, a square wave with a varying high and low time. A basic
PWM signal is shown in the following figure.
 On-Time (Ton): Duration of time signal is high.
 Off-Time (Toff): Duration of time signal is low.
 Period (Ttotal): It is represented as the sum of on-time and off-time of PWM signal.
 Duty Cycle (D): It is represented as the percentage of time signal that remains on during
the period of the PWM signal.

T total =T on+T off

T on T on
D= =
T on+T off T total
PWM syntax
analogWrite(pin, value)
 pin: the Arduino pin to write to. Allowed data types: int.
 value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types:
int.

Project - Fading LED


Components Required
You will need the following components-
 1x Breadboard
 1x Arduino Uno R3
 1x LED
 1x 330Ω Resistor
 2x Jumper Wire

Circuit Diagram
Arduino Code
int led = 3; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

void setup()
{
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop()
{
// set the brightness of pin 9:
analogWrite(led, brightness);

// change the brightness for next time through the loop:


brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:


if (brightness == 0 || brightness == 255){
fadeAmount = -fadeAmount ;
}

// wait for 30 milliseconds to see the dimming effect


delay(300);
}

Apply your Knowledge


 Make a circuit that adjust the brightness of a LED according to the analog voltage input
from a potentiometer.

Hint:
 You may need to refer to the Reading Analog Voltage project and Fading LED
project.
 It’s a combination of the Reading Analog Voltage project and Fading LED project.

Ans
const int pwmPin = 6;

void setup()
{
// initialize serial communication at 9600 bits per second:
pinMode(pwmPin, OUTPUT);

void loop()
{
// read the input on analog pin 0:
int sensorValue = analogRead(A0);

float voltage = map(sensorValue, 0, 1023, 0, 255);

analogWrite(pwmPin, voltage);
}
Sensors
Sensors are mainly categorized into 2 main group, analog sensor and digital sensor. Digital
sensors can be further categorized by the different communication protocol used by the sensors.

Analog sensors:
 Produce analog output
 Required the used of an Analog to Digital Converter (ADC) to read the reading
 Resolution of reading depends on the ADC, which mean that the resolution of the sensor
changed with resolution of the ADC.

Digital Sensors:
 Produce digital output
 Resolution of reading depends on the digital output resolution of the sensors. It is fixed.
 Communication protocol:
o Direct input to digital pin (High or Low)
o Serial Communication:
 One Wire (only for Dallas sensor)
 Universal Asynchronous Receiver – Transmitter (UART)
 Inter Integrated Circuit (I2C)
 Serial Peripheral Interface (SPI)
o Parallel Communication

Project – Temperature Sensor


Technical Specifications
 Calibrated directly in Celsius (Centigrade)
 Linear + 10-mV/°C scale factor
 0.5°C ensured accuracy (at 25°C)
 Rated for full −55°C to 150°C range
 Suitable for remote applications
Components Required
You will need the following components:
 1x Breadboard
 1x Arduino Uno R3
 1x LM35 sensor
 3x Jumper Wire

Circuit Diagram
Arduino Code
float temp, reading;
int tempPin = A0;

void setup(){
Serial.begin(9600);
}
void loop(){

// read analog volt from sensor and save to variable temp


temp = analogRead(tempPin);

//convert reading from ADC to voltage


reading = temp*1023/5000;

//convert voltage to temperature


reading = reading / 10 ;

// convert the analog volt to its temperature equivalent


Serial.print("TEMPERATURE = ");
Serial.print(reading); // display temperature value
Serial.print("*C");
Serial.println();
delay(1000); // update sensor reading each one second

You might also like