SlideShare a Scribd company logo
THE IOT ACADEMY
Arduino Code Basics
Arduino programs run on two basic sections:
void setup() {
//setup motors, sensors etc
}
void loop() {
// get information from sensors
// send commands to motors
}
SETUP
The setup section is used for assigning input and
outputs (Examples: motors, LED’s, sensors etc) to
ports on the Arduino
It also specifies whether the device is OUTPUT or
INPUT
To do this we use the command “pinMode”
3
SETUP
void setup() {
pinMode(9, OUTPUT);
}
http://www.arduino.cc/en/Reference/HomePage
port #
Input or Output
LOOP
5
void loop() {
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(1000);
}
Port # from setup
Turn the LED on
or off
Wait for 1 second
or 1000 milliseconds
TASK 1
Using 3 LED’s (red, yellow and green) build a traffic
light that
 Illuminates the green LED for 5 seconds
 Illuminates the yellow LED for 2 seconds
 Illuminates the red LED for 5 seconds
 repeats the sequence
Note that after each illumination period the LED is
turned off!
6
TASK 2
Modify Task 1 to have an advanced green (blinking
green LED) for 3 seconds before illuminating the
green LED for 5 seconds
7
Variables
A variable is like “bucket”
It holds numbers or other values temporarily
8
value
DECLARING A VARIABLE
9
int val = 5;
Type
variable name
assignment
“becomes”
value
Task
Replace all delay times with variables
Replace LED pin numbers with variables
10
USING VARIABLES
11
int delayTime = 2000;
int greenLED = 9;
void setup() {
pinMode(greenLED, OUTPUT);
}
void loop() {
digitalWrite(greenLED, HIGH);
delay(delayTime);
digitalWrite(greenLED, LOW);
delay(delayTime);
}
Declare delayTime
Variable
Use delayTime
Variable
Using Variables
12
int delayTime = 2000;
int greenLED = 9;
void setup() {
pinMode(greenLED, OUTPUT);
}
void loop() {
digitalWrite(greenLED, HIGH);
delay(delayTime);
digitalWrite(greenLED, LOW);
delayTime = delayTime - 100;
delay(delayTime);
} subtract 100 from
delayTime to gradually
increase LED’s blinking
speed
Conditions
To make decisions in Arduino code we use an ‘if’
statement
‘If’ statements are based on a TRUE or FALSE
question
VALUE COMPARISONS
14
GREATER THAN
a > b
LESS
a < b
EQUAL
a == b
GREATER THAN OR EQUAL
a >= b
LESS THAN OR EQUAL
a <= b
NOT EQUAL
a != b
IF Condition
if(true)
{
“perform some action”
}
IF Example
16
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if(counter < 10)
{
Serial.println(counter);
}
counter = counter + 1;
}
Integer: used with integer variables with value between
2147483647 and -2147483647.
Ex: int x=1200;
Character: used with single character, represent value from -
127 to 128.
Ex. char c=‘r’;
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.
Ex. long u=199203;
Floating-point numbers can be as large as 3.4028235E+38and
as low as -3.4028235E+38.They are stored as 32 bits (4 bytes) of
information.
Ex. float num=1.291; [The same as double type]
Data Types and operators
Statement represents a command, it ends with ;
Ex:
int x;
x=13;
Operators are symbols that used to indicate a specific
function:
- Math operators: [+,-,*,/,%,^]
- Logic operators: [==, !=, &&, ||]
- Comparison operators: [==, >, <, !=, <=, >=]
Syntax:
; Semicolon, {} curly braces, //single line comment,
/*Multi-linecomments*/
Statement and operators:
Compound Operators:
++ (increment)
-- (decrement)
+= (compound addition)
-= (compound subtraction)
*= (compound multiplication)
/= (compound division)
Statement and operators:
If Conditioning:
if(condition)
{
statements-1;
…
Statement-N;
}
else if(condition2)
{
Statements;
}
Else{statements;}
Control statements:
Switch case:
switch (var) {
case 1:
//do somethingwhen var equals 1
break;
case 2:
//do somethingwhen var equals 2
break;
default:
// if nothing else matches, do the default
// default is optional
}
Control statements:
Do… while:
do
{
Statements;
}
while(condition); // thestatementsare run at least once.
While:
While(condition)
{statements;}
for
for (int i=0; i <= val; i++){
statements;
}
Loop statements:
Use break statement to stop the loop whenever needed.
Void setup(){}
Used to indicate the initial values of system on starting.
Void loop(){}
Contains the statements that will run whenever the system is powered
after setup.
Code structure:
Led blinking example:
Used functions:
pinMode();
digitalRead();
digitalWrite();
delay(time_ms);
other functions:
analogRead();
analogWrite();//PWM.
Input and output:
Input & Output
 Transferring data from the computer to an Arduino is
done using Serial Transmission
 To setup Serial communication we use the following
25
void setup() {
Serial.begin(9600);
}
Writing to the Console
26
void setup() {
Serial.begin(9600);
Serial.println(“Hello World!”);
}
void loop() {}
IF - ELSE Condition
if( “answer is true”)
{
“perform some action”
}
else
{
“perform some other action”
}
IF - ELSE Example
28
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if(counter < 10)
{
Serial.println(“less than 10”);
}
else
{
Serial.println(“greater than or equal to 10”);
Serial.end();
}
counter = counter + 1;
}
IF - ELSE IF Condition
if( “answer is true”)
{
“perform some action”
}
else if( “answer is true”)
{
“perform some other action”
}
IF - ELSE Example
30
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if(counter < 10)
{
Serial.println(“less than 10”);
}
else if (counter == 10)
{
Serial.println(“equal to 10”);
}
else
{
Serial.println(“greater than 10”);
Serial.end();
}
counter = counter + 1;
}
BOOLEAN OPERATORS - AND
If we want all of the conditions to be true we need to use ‘AND’ logic
(AND gate)
We use the symbols &&
Example
31
if ( val > 10 && val < 20)
BOOLEAN OPERATORS - OR
If we want either of the conditions to be true we need to use ‘OR’
logic (OR gate)
We use the symbols ||
Example
32
if ( val < 10 || val > 20)
TASK
Create a program that illuminates the green LED if the counter is
less than 100, illuminates the yellow LED if the counter is between
101 and 200 and illuminates the red LED if the counter is greater
than 200
33
INPUT
We can also use our Serial connection to get input from the computer
to be used by the Arduino
34
int val = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available() > 0) {
val = Serial.read();
Serial.println(val);
}
}
Task
Using input and output commands find the ASCII values of
35
#
1
2
3
4
5
ASCII
49
50
51
52
53
#
6
7
8
9
ASCII
54
55
56
57
@
a
b
c
d
e
f
g
ASCII
97
98
99
100
101
102
103
@
h
i
j
k
l
m
n
ASCII
104
105
106
107
108
109
110
@
o
p
q
r
s
t
u
ASCII
111
112
113
114
115
116
117
@
v
w
x
y
z
ASCII
118
119
120
121
122
INPUT EXAMPLE
36
int val = 0;
int greenLED = 13;
void setup() {
Serial.begin(9600);
pinMode(greenLED, OUTPUT);
}
void loop() {
if(Serial.available()>0) {
val = Serial.read();
Serial.println(val);
}
if(val == 53) {
digitalWrite(greenLED, HIGH);
}
else {
digitalWrite(greenLED, LOW);
}
}
Task
 Create a program so that when the user enters 1 the green
light is illuminated, 2 the yellow light is illuminated and 3
the red light is illuminated
37
• Create a program so that when the user enters ‘b’ the
green light blinks, ‘g’ the green light is illuminated ‘y’
the yellow light is illuminated and ‘r’ the red light is
illuminated
BOOLEAN VARIABLES
38
boolean done = true;
Run-Once Example
40
boolean done = false;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(!done)
{
Serial.println(“HELLO WORLD”);
done = true;
}
}
TASK
Write a program that asks the user for a number and outputs the
number that is entered. Once the number has been output the
program finishes.
 EXAMPLE:
40
Please enter a number: 1 <enter>
The number you entered was: 1
TASK
Write a program that asks the user for a number and
outputs the number squared that is entered. Once the
number has been output the program finishes.
41
Please enter a number: 4 <enter>
Your number squared is: 16
Important functions
Serial.println(value);
Prints the value to the Serial Monitor on your computer
pinMode(pin, mode);
Configures a digital pin to read (input) or write (output) a digital value
digitalRead(pin);
Reads a digital value (HIGH or LOW) on a pin set for input
digitalWrite(pin, value);
Writes the digital value (HIGH or LOW) to a pin set for output
Using LEDs
void setup()
{
pinMode(77, OUTPUT); //configure pin 77 as output
}
// blink an LED once
void blink1()
{
digitalWrite(77,HIGH); // turn the LED on
delay(500); // wait 500 milliseconds
digitalWrite(77,LOW); // turn the LED off
delay(500); // wait 500 milliseconds
}
Creating infinite loops
void loop() //blink a LED repeatedly
{
digitalWrite(77,HIGH); // turn the LED on
delay(500); // wait 500 milliseconds
digitalWrite(77,LOW); // turn the LED off
delay(500); // wait 500 milliseconds
}
Using switches and buttons
const int inputPin = 2; // choose the input pin
void setup() {
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
int val = digitalRead(inputPin); // read input value
}
Reading analog inputs and scaling
const int potPin = 0; // select the input pin for the potentiometer
void loop() {
int val; // The value coming from the sensor
int percent; // The mapped value
val = analogRead(potPin); // read the voltage on the pot (val ranges from 0 to
1023)
percent = map(val,0,1023,0,100); // percent will range from 0 to 100.
Creating a bar graph using LEDs
const int NoLEDs = 8;
const int ledPins[] = { 70, 71, 72, 73, 74, 75, 76, 77};
const int analogInPin = 0; // Analog input pin const int wait = 30;
const boolean LED_ON = HIGH;
const boolean LED_OFF = LOW;
int sensorValue = 0; // value read from the sensor
int ledLevel = 0; // sensor value converted into LED 'bars'
void setup() {
for (int i = 0; i < NoLEDs; i++)
{
pinMode(ledPins[i], OUTPUT); // make all the LED pins outputs
}
}
Creating a bar graph using LEDs
void loop() {
sensorValue = analogRead(analogInPin); // read the analog in value
ledLevel = map(sensorValue, 0, 1023, 0, NoLEDs); // map to the number of LEDs
for (int i = 0; i < NoLEDs; i++)
{
if (i < ledLevel ) {
digitalWrite(ledPins[i], LED_ON); // turn on pins less than the level
}
else {
digitalWrite(ledPins[i], LED_OFF); // turn off pins higher than the level:
}
}
}
Measuring Temperature
const int inPin = 0; // analog pin
void loop()
{
int value = analogRead(inPin);
float millivolts = (value / 1024.0) * 3300; //3.3V
analog input
float celsius = millivolts / 10; // sensor output is
10mV per degree Celsius
delay(1000); // wait for one second
}
Reading data from Arduino
void setup()
{
Serial.begin(9600);
}
void serialtest()
{
int i;
for(i=0; i<10; i++)
Serial.println(i);
}
Using Interrupts
 On a standard Arduino board, two pins can be used as interrupts:
pins 2 and 3.
 The interrupt is enabled through the following line:
attachInterrupt(interrupt, function, mode)
attachInterrupt(0, doEncoder, FALLING);
Interrupt example
int led = 77;
volatile int state = LOW;
void setup()
{
pinMode(led, OUTPUT);
attachInterrupt(1, blink, CHANGE);
}
void loop()
{
digitalWrite(led, state);
}
void blink()
{
state = !state;
}
Timer functions (timer.h library)
 int every(long period, callback)
 Run the 'callback' every 'period' milliseconds. Returns the ID of
the timer event.
 int every(long period, callback, int repeatCount)
 Run the 'callback' every 'period' milliseconds for a total of
'repeatCount' times. Returns the ID of the timer event.
 int after(long duration, callback)
 Run the 'callback' once after 'period' milliseconds. Returns the ID
of the timer event.
Timer functions (timer.h library)
int oscillate(int pin, long period, int startingValue)
Toggle the state of the digital output 'pin' every 'period' milliseconds.
The pin's starting value is specified in 'startingValue', which should be
HIGH or LOW. Returns the ID of the timer event.
int oscillate(int pin, long period, int startingValue, int repeatCount)
Toggle the state of the digital output 'pin' every 'period' milliseconds
'repeatCount' times. The pin's starting value is specified in
'startingValue', which should be HIGH or LOW. Returns the ID of the
timer event.
Timer functions (Timer.h library)
int pulse(int pin, long period, int startingValue)
Toggle the state of the digital output 'pin' just once after 'period'
milliseconds. The pin's starting value is specified in 'startingValue',
which should be HIGH or LOW. Returns the ID of the timer event.
int stop(int id)
Stop the timer event running. Returns the ID of the timer event.
int update()
Must be called from 'loop'. This will service all the events associated
with the timer.
Example (1/2)
#include "Timer.h"
Timer t;
int ledEvent;
void setup()
{
Serial.begin(9600);
int tickEvent = t.every(2000, doSomething);
Serial.print("2 second tick started id=");
Serial.println(tickEvent);
pinMode(13, OUTPUT);
ledEvent = t.oscillate(13, 50, HIGH);
Serial.print("LED event started id=");
Serial.println(ledEvent);
int afterEvent = t.after(10000, doAfter);
Serial.print("After event started id=");
Serial.println(afterEvent);
}
Example (2/2)
void loop()
{
t.update();
}
void doSomething()
{
Serial.print("2 second tick: millis()=");
Serial.println(millis());
}
void doAfter()
{
Serial.println("stop the led event");
t.stop(ledEvent);
t.oscillate(13, 500, HIGH, 5);
}
Digital I/O
pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Electronic stuff
Output pins can provide 40 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
Arduino Timing
• delay(ms)
– Pauses for a few milliseconds
• delayMicroseconds(us)
– Pauses for a few microseconds
• More commands:
arduino.cc/en/Reference/HomePage
SOFTWARE
SIMULATOR
Masm
SOFTWARE
C
C++
Dot Net
COMPILER
RIDE
KEIL
Real-Time Operating System
 An OS with response for time-controlled and event-controlled
processes.
 Very essential for large scale
embedded systems.
Real-Time Operating System
 Function
1. Basic OS function
2. RTOS main functions
3. Time Management
4. Predictability
5. Priorities Management
6. IPC Synchronization
7. Time slicing
8. Hard and soft real-time operability
When RTOS is necessary
 Multiple simultaneous tasks/processes with hard time lines.
 Inter Process Communication is necessary.
 A common and effectiveway of handling of the hardware
source calls from the interrupts
 I/O managementwith devices, files, mailboxes becomes
simple using an RTOS
 Effectivelyscheduling and running and blocking of the tasks
in cases of many tasks.
The IoT Academy IoT Training Arduino Part 3 programming

More Related Content

What's hot (20)

PPTX
Alternator
Smile Hossain
 
PPTX
Vector diagram and phasor diagram of synchronous motor
karthi1017
 
PPTX
COMBINE CYCLE POWER PLANT PPT summer training
Debasish Das
 
PDF
Wheel alignment;Alignment terminology
Sam Thai Aladeen
 
PPTX
Ais 041(rev.1)
Dhruv Upadhaya
 
PPTX
Energy Management of a Series Hybrid Electric Powertrain (this one)
Saifuddin Abdul Halim
 
PPTX
Cng ppt
Shivam Kumar
 
PDF
BEV ( Battery Operated Electric Vehicles) PPT
Pranav Mistry
 
PPTX
Steam Turbines
Amir Ayad
 
PPTX
Eps-Electronic power steering
Raja Lakshmanan
 
PDF
Turbine Governing System
Salil Vaidya
 
PPTX
Measuring of different parameter of IC engine
bhavesh patwa
 
PPTX
stepper motor
Sumanthkumar Rakesh
 
PPTX
Vapour absorption refrigeration systems
Akshay Mistri
 
PPTX
Hybrid Electric Vehicles
Colloquium
 
PPTX
Electronic Controller Of A Car
Brian Cole
 
PPT
Motors
Akash Maurya
 
PDF
HP LP Bypass system of 110 MW Steam Turbine
RAVI PAL SINGH
 
DOC
vinay kumar actuators report
Akash Maurya
 
PDF
2012 Toyota Prius Hybrid System
Jerry's Toyota
 
Alternator
Smile Hossain
 
Vector diagram and phasor diagram of synchronous motor
karthi1017
 
COMBINE CYCLE POWER PLANT PPT summer training
Debasish Das
 
Wheel alignment;Alignment terminology
Sam Thai Aladeen
 
Ais 041(rev.1)
Dhruv Upadhaya
 
Energy Management of a Series Hybrid Electric Powertrain (this one)
Saifuddin Abdul Halim
 
Cng ppt
Shivam Kumar
 
BEV ( Battery Operated Electric Vehicles) PPT
Pranav Mistry
 
Steam Turbines
Amir Ayad
 
Eps-Electronic power steering
Raja Lakshmanan
 
Turbine Governing System
Salil Vaidya
 
Measuring of different parameter of IC engine
bhavesh patwa
 
stepper motor
Sumanthkumar Rakesh
 
Vapour absorption refrigeration systems
Akshay Mistri
 
Hybrid Electric Vehicles
Colloquium
 
Electronic Controller Of A Car
Brian Cole
 
Motors
Akash Maurya
 
HP LP Bypass system of 110 MW Steam Turbine
RAVI PAL SINGH
 
vinay kumar actuators report
Akash Maurya
 
2012 Toyota Prius Hybrid System
Jerry's Toyota
 

Similar to The IoT Academy IoT Training Arduino Part 3 programming (20)

PPT
Arduino-arduino arduino programming hhhh
AbdalkreemZuod
 
PPT
Arduino-2 (1).ppt
HebaEng
 
PPT
Arduin0.ppt
GopalRathinam1
 
PDF
Syed IoT - module 5
Syed Mustafa
 
PDF
Arduino reference
Marcos Henrique
 
PDF
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
Jayanthi Kannan MK
 
PDF
Arduino - Module 1.pdf
razonclarence4
 
PDF
Intro to Arduino Programming.pdf
HimanshuDon1
 
PPTX
Introduction to Arduino Microcontroller
Mujahid Hussain
 
PDF
Introduction to Arduino Programming
James Lewis
 
PPT
Arduino_CSE ece ppt for working and principal of arduino.ppt
SAURABHKUMAR892774
 
PPTX
Introduction to the Arduino
Wingston
 
PPTX
Arduino programming
MdAshrafulAlam47
 
PDF
Lecture 2
Mohamed Zain Allam
 
PPTX
INTODUCTION OF IOT AND INTERFACING WITH ARDUINO UNO
vasankarponnapalli2
 
PPTX
Arduino Programming Familiarization
Amit Kumer Podder
 
PDF
Arduino reference
Roberth Mamani Moya
 
PPTX
Introduction to Arduino
Amarjeetsingh Thakur
 
PPTX
Introduction to Arduino
Amarjeetsingh Thakur
 
Arduino-arduino arduino programming hhhh
AbdalkreemZuod
 
Arduino-2 (1).ppt
HebaEng
 
Arduin0.ppt
GopalRathinam1
 
Syed IoT - module 5
Syed Mustafa
 
Arduino reference
Marcos Henrique
 
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
Jayanthi Kannan MK
 
Arduino - Module 1.pdf
razonclarence4
 
Intro to Arduino Programming.pdf
HimanshuDon1
 
Introduction to Arduino Microcontroller
Mujahid Hussain
 
Introduction to Arduino Programming
James Lewis
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
SAURABHKUMAR892774
 
Introduction to the Arduino
Wingston
 
Arduino programming
MdAshrafulAlam47
 
INTODUCTION OF IOT AND INTERFACING WITH ARDUINO UNO
vasankarponnapalli2
 
Arduino Programming Familiarization
Amit Kumer Podder
 
Arduino reference
Roberth Mamani Moya
 
Introduction to Arduino
Amarjeetsingh Thakur
 
Introduction to Arduino
Amarjeetsingh Thakur
 
Ad

More from The IOT Academy (20)

PPTX
Embedded Systems Programming
The IOT Academy
 
PDF
Introduction to Digital Marketing Certification Course.pdf
The IOT Academy
 
PDF
Google SEO 2023: Complete SEO Guide
The IOT Academy
 
PDF
Embedded C The IoT Academy
The IOT Academy
 
PPTX
Basics of c++ Programming Language
The IOT Academy
 
PPTX
MachineLlearning introduction
The IOT Academy
 
PDF
IoT Node-Red Presentation
The IOT Academy
 
PDF
IoT Introduction Architecture and Applications
The IOT Academy
 
PDF
UCT IoT Deployment and Challenges
The IOT Academy
 
PDF
UCT Electrical Vehicle Infrastructure
The IOT Academy
 
PDF
Uct 5G Autonomous Cars
The IOT Academy
 
PDF
Fdp uct industry4.0_talk
The IOT Academy
 
PDF
Success ladder to the Corporate world
The IOT Academy
 
PDF
The iot academy_lpwan_lora
The IOT Academy
 
PDF
The iot academy_embeddedsystems_training_circuitdesignpart3
The IOT Academy
 
PDF
The iot academy_embeddedsystems_training_basicselectronicspart2
The IOT Academy
 
PDF
The iot academy_embeddedsystems_training_basicelectronicspart1
The IOT Academy
 
PPTX
The iot academy_lpwan
The IOT Academy
 
PDF
The iotacademy industry4.0_talk_slideshare
The IOT Academy
 
PDF
The iot acdemy_awstraining_part4_aws_lab
The IOT Academy
 
Embedded Systems Programming
The IOT Academy
 
Introduction to Digital Marketing Certification Course.pdf
The IOT Academy
 
Google SEO 2023: Complete SEO Guide
The IOT Academy
 
Embedded C The IoT Academy
The IOT Academy
 
Basics of c++ Programming Language
The IOT Academy
 
MachineLlearning introduction
The IOT Academy
 
IoT Node-Red Presentation
The IOT Academy
 
IoT Introduction Architecture and Applications
The IOT Academy
 
UCT IoT Deployment and Challenges
The IOT Academy
 
UCT Electrical Vehicle Infrastructure
The IOT Academy
 
Uct 5G Autonomous Cars
The IOT Academy
 
Fdp uct industry4.0_talk
The IOT Academy
 
Success ladder to the Corporate world
The IOT Academy
 
The iot academy_lpwan_lora
The IOT Academy
 
The iot academy_embeddedsystems_training_circuitdesignpart3
The IOT Academy
 
The iot academy_embeddedsystems_training_basicselectronicspart2
The IOT Academy
 
The iot academy_embeddedsystems_training_basicelectronicspart1
The IOT Academy
 
The iot academy_lpwan
The IOT Academy
 
The iotacademy industry4.0_talk_slideshare
The IOT Academy
 
The iot acdemy_awstraining_part4_aws_lab
The IOT Academy
 
Ad

Recently uploaded (20)

PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 

The IoT Academy IoT Training Arduino Part 3 programming

  • 2. Arduino Code Basics Arduino programs run on two basic sections: void setup() { //setup motors, sensors etc } void loop() { // get information from sensors // send commands to motors }
  • 3. SETUP The setup section is used for assigning input and outputs (Examples: motors, LED’s, sensors etc) to ports on the Arduino It also specifies whether the device is OUTPUT or INPUT To do this we use the command “pinMode” 3
  • 4. SETUP void setup() { pinMode(9, OUTPUT); } http://www.arduino.cc/en/Reference/HomePage port # Input or Output
  • 5. LOOP 5 void loop() { digitalWrite(9, HIGH); delay(1000); digitalWrite(9, LOW); delay(1000); } Port # from setup Turn the LED on or off Wait for 1 second or 1000 milliseconds
  • 6. TASK 1 Using 3 LED’s (red, yellow and green) build a traffic light that  Illuminates the green LED for 5 seconds  Illuminates the yellow LED for 2 seconds  Illuminates the red LED for 5 seconds  repeats the sequence Note that after each illumination period the LED is turned off! 6
  • 7. TASK 2 Modify Task 1 to have an advanced green (blinking green LED) for 3 seconds before illuminating the green LED for 5 seconds 7
  • 8. Variables A variable is like “bucket” It holds numbers or other values temporarily 8 value
  • 9. DECLARING A VARIABLE 9 int val = 5; Type variable name assignment “becomes” value
  • 10. Task Replace all delay times with variables Replace LED pin numbers with variables 10
  • 11. USING VARIABLES 11 int delayTime = 2000; int greenLED = 9; void setup() { pinMode(greenLED, OUTPUT); } void loop() { digitalWrite(greenLED, HIGH); delay(delayTime); digitalWrite(greenLED, LOW); delay(delayTime); } Declare delayTime Variable Use delayTime Variable
  • 12. Using Variables 12 int delayTime = 2000; int greenLED = 9; void setup() { pinMode(greenLED, OUTPUT); } void loop() { digitalWrite(greenLED, HIGH); delay(delayTime); digitalWrite(greenLED, LOW); delayTime = delayTime - 100; delay(delayTime); } subtract 100 from delayTime to gradually increase LED’s blinking speed
  • 13. Conditions To make decisions in Arduino code we use an ‘if’ statement ‘If’ statements are based on a TRUE or FALSE question
  • 14. VALUE COMPARISONS 14 GREATER THAN a > b LESS a < b EQUAL a == b GREATER THAN OR EQUAL a >= b LESS THAN OR EQUAL a <= b NOT EQUAL a != b
  • 16. IF Example 16 int counter = 0; void setup() { Serial.begin(9600); } void loop() { if(counter < 10) { Serial.println(counter); } counter = counter + 1; }
  • 17. Integer: used with integer variables with value between 2147483647 and -2147483647. Ex: int x=1200; Character: used with single character, represent value from - 127 to 128. Ex. char c=‘r’; 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. Ex. long u=199203; Floating-point numbers can be as large as 3.4028235E+38and as low as -3.4028235E+38.They are stored as 32 bits (4 bytes) of information. Ex. float num=1.291; [The same as double type] Data Types and operators
  • 18. Statement represents a command, it ends with ; Ex: int x; x=13; Operators are symbols that used to indicate a specific function: - Math operators: [+,-,*,/,%,^] - Logic operators: [==, !=, &&, ||] - Comparison operators: [==, >, <, !=, <=, >=] Syntax: ; Semicolon, {} curly braces, //single line comment, /*Multi-linecomments*/ Statement and operators:
  • 19. Compound Operators: ++ (increment) -- (decrement) += (compound addition) -= (compound subtraction) *= (compound multiplication) /= (compound division) Statement and operators:
  • 21. Switch case: switch (var) { case 1: //do somethingwhen var equals 1 break; case 2: //do somethingwhen var equals 2 break; default: // if nothing else matches, do the default // default is optional } Control statements:
  • 22. Do… while: do { Statements; } while(condition); // thestatementsare run at least once. While: While(condition) {statements;} for for (int i=0; i <= val; i++){ statements; } Loop statements: Use break statement to stop the loop whenever needed.
  • 23. Void setup(){} Used to indicate the initial values of system on starting. Void loop(){} Contains the statements that will run whenever the system is powered after setup. Code structure:
  • 24. Led blinking example: Used functions: pinMode(); digitalRead(); digitalWrite(); delay(time_ms); other functions: analogRead(); analogWrite();//PWM. Input and output:
  • 25. Input & Output  Transferring data from the computer to an Arduino is done using Serial Transmission  To setup Serial communication we use the following 25 void setup() { Serial.begin(9600); }
  • 26. Writing to the Console 26 void setup() { Serial.begin(9600); Serial.println(“Hello World!”); } void loop() {}
  • 27. IF - ELSE Condition if( “answer is true”) { “perform some action” } else { “perform some other action” }
  • 28. IF - ELSE Example 28 int counter = 0; void setup() { Serial.begin(9600); } void loop() { if(counter < 10) { Serial.println(“less than 10”); } else { Serial.println(“greater than or equal to 10”); Serial.end(); } counter = counter + 1; }
  • 29. IF - ELSE IF Condition if( “answer is true”) { “perform some action” } else if( “answer is true”) { “perform some other action” }
  • 30. IF - ELSE Example 30 int counter = 0; void setup() { Serial.begin(9600); } void loop() { if(counter < 10) { Serial.println(“less than 10”); } else if (counter == 10) { Serial.println(“equal to 10”); } else { Serial.println(“greater than 10”); Serial.end(); } counter = counter + 1; }
  • 31. BOOLEAN OPERATORS - AND If we want all of the conditions to be true we need to use ‘AND’ logic (AND gate) We use the symbols && Example 31 if ( val > 10 && val < 20)
  • 32. BOOLEAN OPERATORS - OR If we want either of the conditions to be true we need to use ‘OR’ logic (OR gate) We use the symbols || Example 32 if ( val < 10 || val > 20)
  • 33. TASK Create a program that illuminates the green LED if the counter is less than 100, illuminates the yellow LED if the counter is between 101 and 200 and illuminates the red LED if the counter is greater than 200 33
  • 34. INPUT We can also use our Serial connection to get input from the computer to be used by the Arduino 34 int val = 0; void setup() { Serial.begin(9600); } void loop() { if(Serial.available() > 0) { val = Serial.read(); Serial.println(val); } }
  • 35. Task Using input and output commands find the ASCII values of 35 # 1 2 3 4 5 ASCII 49 50 51 52 53 # 6 7 8 9 ASCII 54 55 56 57 @ a b c d e f g ASCII 97 98 99 100 101 102 103 @ h i j k l m n ASCII 104 105 106 107 108 109 110 @ o p q r s t u ASCII 111 112 113 114 115 116 117 @ v w x y z ASCII 118 119 120 121 122
  • 36. INPUT EXAMPLE 36 int val = 0; int greenLED = 13; void setup() { Serial.begin(9600); pinMode(greenLED, OUTPUT); } void loop() { if(Serial.available()>0) { val = Serial.read(); Serial.println(val); } if(val == 53) { digitalWrite(greenLED, HIGH); } else { digitalWrite(greenLED, LOW); } }
  • 37. Task  Create a program so that when the user enters 1 the green light is illuminated, 2 the yellow light is illuminated and 3 the red light is illuminated 37 • Create a program so that when the user enters ‘b’ the green light blinks, ‘g’ the green light is illuminated ‘y’ the yellow light is illuminated and ‘r’ the red light is illuminated
  • 39. Run-Once Example 40 boolean done = false; void setup() { Serial.begin(9600); } void loop() { if(!done) { Serial.println(“HELLO WORLD”); done = true; } }
  • 40. TASK Write a program that asks the user for a number and outputs the number that is entered. Once the number has been output the program finishes.  EXAMPLE: 40 Please enter a number: 1 <enter> The number you entered was: 1
  • 41. TASK Write a program that asks the user for a number and outputs the number squared that is entered. Once the number has been output the program finishes. 41 Please enter a number: 4 <enter> Your number squared is: 16
  • 42. Important functions Serial.println(value); Prints the value to the Serial Monitor on your computer pinMode(pin, mode); Configures a digital pin to read (input) or write (output) a digital value digitalRead(pin); Reads a digital value (HIGH or LOW) on a pin set for input digitalWrite(pin, value); Writes the digital value (HIGH or LOW) to a pin set for output
  • 43. Using LEDs void setup() { pinMode(77, OUTPUT); //configure pin 77 as output } // blink an LED once void blink1() { digitalWrite(77,HIGH); // turn the LED on delay(500); // wait 500 milliseconds digitalWrite(77,LOW); // turn the LED off delay(500); // wait 500 milliseconds }
  • 44. Creating infinite loops void loop() //blink a LED repeatedly { digitalWrite(77,HIGH); // turn the LED on delay(500); // wait 500 milliseconds digitalWrite(77,LOW); // turn the LED off delay(500); // wait 500 milliseconds }
  • 45. Using switches and buttons const int inputPin = 2; // choose the input pin void setup() { pinMode(inputPin, INPUT); // declare pushbutton as input } void loop(){ int val = digitalRead(inputPin); // read input value }
  • 46. Reading analog inputs and scaling const int potPin = 0; // select the input pin for the potentiometer void loop() { int val; // The value coming from the sensor int percent; // The mapped value val = analogRead(potPin); // read the voltage on the pot (val ranges from 0 to 1023) percent = map(val,0,1023,0,100); // percent will range from 0 to 100.
  • 47. Creating a bar graph using LEDs const int NoLEDs = 8; const int ledPins[] = { 70, 71, 72, 73, 74, 75, 76, 77}; const int analogInPin = 0; // Analog input pin const int wait = 30; const boolean LED_ON = HIGH; const boolean LED_OFF = LOW; int sensorValue = 0; // value read from the sensor int ledLevel = 0; // sensor value converted into LED 'bars' void setup() { for (int i = 0; i < NoLEDs; i++) { pinMode(ledPins[i], OUTPUT); // make all the LED pins outputs } }
  • 48. Creating a bar graph using LEDs void loop() { sensorValue = analogRead(analogInPin); // read the analog in value ledLevel = map(sensorValue, 0, 1023, 0, NoLEDs); // map to the number of LEDs for (int i = 0; i < NoLEDs; i++) { if (i < ledLevel ) { digitalWrite(ledPins[i], LED_ON); // turn on pins less than the level } else { digitalWrite(ledPins[i], LED_OFF); // turn off pins higher than the level: } } }
  • 49. Measuring Temperature const int inPin = 0; // analog pin void loop() { int value = analogRead(inPin); float millivolts = (value / 1024.0) * 3300; //3.3V analog input float celsius = millivolts / 10; // sensor output is 10mV per degree Celsius delay(1000); // wait for one second }
  • 50. Reading data from Arduino void setup() { Serial.begin(9600); } void serialtest() { int i; for(i=0; i<10; i++) Serial.println(i); }
  • 51. Using Interrupts  On a standard Arduino board, two pins can be used as interrupts: pins 2 and 3.  The interrupt is enabled through the following line: attachInterrupt(interrupt, function, mode) attachInterrupt(0, doEncoder, FALLING);
  • 52. Interrupt example int led = 77; volatile int state = LOW; void setup() { pinMode(led, OUTPUT); attachInterrupt(1, blink, CHANGE); } void loop() { digitalWrite(led, state); } void blink() { state = !state; }
  • 53. Timer functions (timer.h library)  int every(long period, callback)  Run the 'callback' every 'period' milliseconds. Returns the ID of the timer event.  int every(long period, callback, int repeatCount)  Run the 'callback' every 'period' milliseconds for a total of 'repeatCount' times. Returns the ID of the timer event.  int after(long duration, callback)  Run the 'callback' once after 'period' milliseconds. Returns the ID of the timer event.
  • 54. Timer functions (timer.h library) int oscillate(int pin, long period, int startingValue) Toggle the state of the digital output 'pin' every 'period' milliseconds. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW. Returns the ID of the timer event. int oscillate(int pin, long period, int startingValue, int repeatCount) Toggle the state of the digital output 'pin' every 'period' milliseconds 'repeatCount' times. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW. Returns the ID of the timer event.
  • 55. Timer functions (Timer.h library) int pulse(int pin, long period, int startingValue) Toggle the state of the digital output 'pin' just once after 'period' milliseconds. The pin's starting value is specified in 'startingValue', which should be HIGH or LOW. Returns the ID of the timer event. int stop(int id) Stop the timer event running. Returns the ID of the timer event. int update() Must be called from 'loop'. This will service all the events associated with the timer.
  • 56. Example (1/2) #include "Timer.h" Timer t; int ledEvent; void setup() { Serial.begin(9600); int tickEvent = t.every(2000, doSomething); Serial.print("2 second tick started id="); Serial.println(tickEvent); pinMode(13, OUTPUT); ledEvent = t.oscillate(13, 50, HIGH); Serial.print("LED event started id="); Serial.println(ledEvent); int afterEvent = t.after(10000, doAfter); Serial.print("After event started id="); Serial.println(afterEvent); }
  • 57. Example (2/2) void loop() { t.update(); } void doSomething() { Serial.print("2 second tick: millis()="); Serial.println(millis()); } void doAfter() { Serial.println("stop the led event"); t.stop(ledEvent); t.oscillate(13, 500, HIGH, 5); }
  • 58. Digital I/O pinMode(pin, mode) Sets pin to either INPUT or OUTPUT digitalRead(pin) Reads HIGH or LOW from a pin digitalWrite(pin, value) Writes HIGH or LOW to a pin Electronic stuff Output pins can provide 40 mA of current Writing HIGH to an input pin installs a 20KΩ pullup
  • 59. Arduino Timing • delay(ms) – Pauses for a few milliseconds • delayMicroseconds(us) – Pauses for a few microseconds • More commands: arduino.cc/en/Reference/HomePage
  • 61. Real-Time Operating System  An OS with response for time-controlled and event-controlled processes.  Very essential for large scale embedded systems.
  • 62. Real-Time Operating System  Function 1. Basic OS function 2. RTOS main functions 3. Time Management 4. Predictability 5. Priorities Management 6. IPC Synchronization 7. Time slicing 8. Hard and soft real-time operability
  • 63. When RTOS is necessary  Multiple simultaneous tasks/processes with hard time lines.  Inter Process Communication is necessary.  A common and effectiveway of handling of the hardware source calls from the interrupts  I/O managementwith devices, files, mailboxes becomes simple using an RTOS  Effectivelyscheduling and running and blocking of the tasks in cases of many tasks.