Arduino Workshop With SLN
Arduino Workshop With SLN
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.
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).
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.
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
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);
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);
void loop() {
byte / uint_8
both byte and uint_8 store an 8-bit unsigned number, from 0 to 255.
Example
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
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(){
}
Try It Out
void setup() {
Serial.begin(9600);
void loop() {
//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
void setup(){
void loop(){
}
Formal parameters
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
//or
Comparison Operators
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 (0000 1010 in binary) and variable B holds 20 (0001 0100 in
binary) then –
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
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
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 (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.
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){
}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
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
Conditional Operator ? :
The ? is called a ternary operator because it requires three operands and can be used to replace if-
else statements.
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
is equate to
Example 2
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 (condition) {
Block of Statement;
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{
Block of Statements;
}while(condition)
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.
Example
//statements block
True
Counter = counter +1
Nested loop
One loop inside another loop.
while (condition_1){
//statement block
while (condition_2){
//statement block
}
do{
//statement block
do{
//statement block
}while(condition_2)
}while(condition_1)
Infinite loop
It is the loop having no terminating condition, so the loop becomes infinite.
for(;;){
//statement block
while(1){
//statement block
}
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:
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] ;
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:
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:
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] ;
x[i][j] = 0 ;
}
}
// 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".
//or
//or
char myword[6] ;
//or
void setup(){
// (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(){
like[18]='t';
like[19]='e';
like[20]='a';
like[21]='\0';
Serial.println(like);
void loop(){
2)
void setup(){
Serial.println(like);
void loop(){
}
3)
void setup(){
like=like.substring(0, 18);
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.
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;
sum = x + y ;
return sum; // return the value
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 () {
char a = 97;
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.
pinMode(pin, INPUT) ;
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(pin ,OUTPUT) ;
digitalWrite() Function
The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin.
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.
void setup(){
void loop(){
}
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 ?
delayMicroseconds() function
Same as the delay() function with the only different is that delayMicroseconds() functions
represents the time in microseconds instead of milliseconds.
millis() function
This function is used to return the number of milliseconds at the time, the Arduino board begins
running the current program.
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
// 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
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}
void loop() {
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
// 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
void loop() {
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 () {
void loop() {
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
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
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.
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);
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);
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
Circuit Diagram
Arduino Code
float temp, reading;
int tempPin = A0;
void setup(){
Serial.begin(9600);
}
void loop(){