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

HART COMMUNICATION
HART  COMMUNICATIONHART  COMMUNICATION
HART COMMUNICATIONKBR-AMCDE
 
Digital logic design DLD Logic gates
Digital logic design DLD Logic gatesDigital logic design DLD Logic gates
Digital logic design DLD Logic gates
Salman Khan
 
Sequential circuit
Sequential circuitSequential circuit
Sequential circuit
Brenda Debra
 
And gate
And gateAnd gate
And gate
Anupam Narang
 
Laporan sistem bilngan dan gerbang logika dasar
Laporan sistem bilngan dan gerbang logika dasarLaporan sistem bilngan dan gerbang logika dasar
Laporan sistem bilngan dan gerbang logika dasar
M Kawakib
 
Timer And Counter in 8051 Microcontroller
Timer And Counter in 8051 MicrocontrollerTimer And Counter in 8051 Microcontroller
Timer And Counter in 8051 Microcontroller
Jay Makwana
 
Embedded c
Embedded cEmbedded c
Embedded c
Nandan Desai
 
Decoders
DecodersDecoders
DecodersRe Man
 
Flip flop
Flip flopFlip flop
Flip flop
JAGMIT Jamkhandi
 
Laporan1 sr&d flip-flop_kurniawan suganda_1_nk1_14
Laporan1 sr&d flip-flop_kurniawan suganda_1_nk1_14Laporan1 sr&d flip-flop_kurniawan suganda_1_nk1_14
Laporan1 sr&d flip-flop_kurniawan suganda_1_nk1_14
Kurniawan Suganda
 

What's hot (12)

Logic families
Logic  familiesLogic  families
Logic families
 
HART COMMUNICATION
HART  COMMUNICATIONHART  COMMUNICATION
HART COMMUNICATION
 
Digital logic design DLD Logic gates
Digital logic design DLD Logic gatesDigital logic design DLD Logic gates
Digital logic design DLD Logic gates
 
Pickleball
PickleballPickleball
Pickleball
 
Sequential circuit
Sequential circuitSequential circuit
Sequential circuit
 
And gate
And gateAnd gate
And gate
 
Laporan sistem bilngan dan gerbang logika dasar
Laporan sistem bilngan dan gerbang logika dasarLaporan sistem bilngan dan gerbang logika dasar
Laporan sistem bilngan dan gerbang logika dasar
 
Timer And Counter in 8051 Microcontroller
Timer And Counter in 8051 MicrocontrollerTimer And Counter in 8051 Microcontroller
Timer And Counter in 8051 Microcontroller
 
Embedded c
Embedded cEmbedded c
Embedded c
 
Decoders
DecodersDecoders
Decoders
 
Flip flop
Flip flopFlip flop
Flip flop
 
Laporan1 sr&d flip-flop_kurniawan suganda_1_nk1_14
Laporan1 sr&d flip-flop_kurniawan suganda_1_nk1_14Laporan1 sr&d flip-flop_kurniawan suganda_1_nk1_14
Laporan1 sr&d flip-flop_kurniawan suganda_1_nk1_14
 

Similar to The IoT Academy IoT Training Arduino Part 3 programming

Arduin0.ppt
Arduin0.pptArduin0.ppt
Arduin0.ppt
GopalRathinam1
 
Arduino-2 (1).ppt
Arduino-2 (1).pptArduino-2 (1).ppt
Arduino-2 (1).ppt
HebaEng
 
Arduino cic3
Arduino cic3Arduino cic3
Arduino cic3
Jeni Shah
 
Arduino Programming
Arduino ProgrammingArduino Programming
Arduino Programming
Dr Karthikeyan Periasamy
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Demetrio Siragusa
 
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
4 IOT 18ISDE712  MODULE 4 IoT Physical Devices and End Point-Aurdino  Uno.pdf4 IOT 18ISDE712  MODULE 4 IoT Physical Devices and End Point-Aurdino  Uno.pdf
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
Jayanthi Kannan MK
 
Arduino for Beginners
Arduino for BeginnersArduino for Beginners
Arduino for Beginners
Sarwan Singh
 
第二回 冬のスイッチ大勉強会 - FullColorLED & MPU-6050編 -
第二回 冬のスイッチ大勉強会 - FullColorLED & MPU-6050編 -第二回 冬のスイッチ大勉強会 - FullColorLED & MPU-6050編 -
第二回 冬のスイッチ大勉強会 - FullColorLED & MPU-6050編 -
Wataru Kani
 
Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016
Svet Ivantchev
 
Arduino: Analog I/O
Arduino: Analog I/OArduino: Analog I/O
Arduino: Analog I/OJune-Hao Hou
 
What will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdfWhat will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdf
SIGMATAX1
 
Edge_AI_Assignment_3.pdf
Edge_AI_Assignment_3.pdfEdge_AI_Assignment_3.pdf
Edge_AI_Assignment_3.pdf
ShivamMishra603376
 
Arduino - Module 1.pdf
Arduino - Module 1.pdfArduino - Module 1.pdf
Arduino - Module 1.pdf
razonclarence4
 
Arduino based applications part 1
Arduino based applications part 1Arduino based applications part 1
Arduino based applications part 1
Jawaher Abdulwahab Fadhil
 
Syed IoT - module 5
Syed  IoT - module 5Syed  IoT - module 5
Syed IoT - module 5
Syed Mustafa
 
Temperature Sensor with LED matrix Display BY ►iRFAN QADOOS◄ 9
Temperature Sensor with LED matrix Display BY ►iRFAN QADOOS◄ 9Temperature Sensor with LED matrix Display BY ►iRFAN QADOOS◄ 9
Temperature Sensor with LED matrix Display BY ►iRFAN QADOOS◄ 9Irfan Qadoos
 
Arduino coding class part ii
Arduino coding class part iiArduino coding class part ii
Arduino coding class part ii
Jonah Marrs
 
Arduino programming
Arduino programmingArduino programming
Arduino programming
MdAshrafulAlam47
 
Lecture 2
Lecture 2Lecture 2

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

Arduin0.ppt
Arduin0.pptArduin0.ppt
Arduin0.ppt
 
Arduino-2 (1).ppt
Arduino-2 (1).pptArduino-2 (1).ppt
Arduino-2 (1).ppt
 
Arduino cic3
Arduino cic3Arduino cic3
Arduino cic3
 
Arduino Programming
Arduino ProgrammingArduino Programming
Arduino Programming
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
 
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
4 IOT 18ISDE712  MODULE 4 IoT Physical Devices and End Point-Aurdino  Uno.pdf4 IOT 18ISDE712  MODULE 4 IoT Physical Devices and End Point-Aurdino  Uno.pdf
4 IOT 18ISDE712 MODULE 4 IoT Physical Devices and End Point-Aurdino Uno.pdf
 
Arduino for Beginners
Arduino for BeginnersArduino for Beginners
Arduino for Beginners
 
第二回 冬のスイッチ大勉強会 - FullColorLED & MPU-6050編 -
第二回 冬のスイッチ大勉強会 - FullColorLED & MPU-6050編 -第二回 冬のスイッチ大勉強会 - FullColorLED & MPU-6050編 -
第二回 冬のスイッチ大勉強会 - FullColorLED & MPU-6050編 -
 
Arduino Workshop 2011.05.31
Arduino Workshop 2011.05.31Arduino Workshop 2011.05.31
Arduino Workshop 2011.05.31
 
Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016Gaztea Tech Robotica 2016
Gaztea Tech Robotica 2016
 
Arduino: Analog I/O
Arduino: Analog I/OArduino: Analog I/O
Arduino: Analog I/O
 
What will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdfWhat will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdf
 
Edge_AI_Assignment_3.pdf
Edge_AI_Assignment_3.pdfEdge_AI_Assignment_3.pdf
Edge_AI_Assignment_3.pdf
 
Arduino - Module 1.pdf
Arduino - Module 1.pdfArduino - Module 1.pdf
Arduino - Module 1.pdf
 
Arduino based applications part 1
Arduino based applications part 1Arduino based applications part 1
Arduino based applications part 1
 
Syed IoT - module 5
Syed  IoT - module 5Syed  IoT - module 5
Syed IoT - module 5
 
Temperature Sensor with LED matrix Display BY ►iRFAN QADOOS◄ 9
Temperature Sensor with LED matrix Display BY ►iRFAN QADOOS◄ 9Temperature Sensor with LED matrix Display BY ►iRFAN QADOOS◄ 9
Temperature Sensor with LED matrix Display BY ►iRFAN QADOOS◄ 9
 
Arduino coding class part ii
Arduino coding class part iiArduino coding class part ii
Arduino coding class part ii
 
Arduino programming
Arduino programmingArduino programming
Arduino programming
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 

More from The IOT Academy

Embedded Systems Programming
Embedded Systems ProgrammingEmbedded Systems Programming
Embedded Systems Programming
The IOT Academy
 
Introduction to Digital Marketing Certification Course.pdf
Introduction to Digital Marketing Certification Course.pdfIntroduction to Digital Marketing Certification Course.pdf
Introduction to Digital Marketing Certification Course.pdf
The IOT Academy
 
Google SEO 2023: Complete SEO Guide
Google SEO 2023: Complete SEO GuideGoogle SEO 2023: Complete SEO Guide
Google SEO 2023: Complete SEO Guide
The IOT Academy
 
Embedded C The IoT Academy
Embedded C The IoT AcademyEmbedded C The IoT Academy
Embedded C The IoT Academy
The IOT Academy
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
The IOT Academy
 
MachineLlearning introduction
MachineLlearning introductionMachineLlearning introduction
MachineLlearning introduction
The IOT Academy
 
IoT Node-Red Presentation
IoT  Node-Red PresentationIoT  Node-Red Presentation
IoT Node-Red Presentation
The IOT Academy
 
IoT Introduction Architecture and Applications
IoT Introduction Architecture and ApplicationsIoT Introduction Architecture and Applications
IoT Introduction Architecture and Applications
The IOT Academy
 
UCT IoT Deployment and Challenges
UCT IoT Deployment and ChallengesUCT IoT Deployment and Challenges
UCT IoT Deployment and Challenges
The IOT Academy
 
UCT Electrical Vehicle Infrastructure
UCT Electrical Vehicle InfrastructureUCT Electrical Vehicle Infrastructure
UCT Electrical Vehicle Infrastructure
The IOT Academy
 
Uct 5G Autonomous Cars
Uct 5G Autonomous CarsUct 5G Autonomous Cars
Uct 5G Autonomous Cars
The IOT Academy
 
Fdp uct industry4.0_talk
Fdp uct industry4.0_talkFdp uct industry4.0_talk
Fdp uct industry4.0_talk
The IOT Academy
 
Success ladder to the Corporate world
Success ladder to the Corporate worldSuccess ladder to the Corporate world
Success ladder to the Corporate world
The IOT Academy
 
The iot academy_lpwan_lora
The iot academy_lpwan_loraThe iot academy_lpwan_lora
The iot academy_lpwan_lora
The IOT Academy
 
The iot academy_embeddedsystems_training_circuitdesignpart3
The iot academy_embeddedsystems_training_circuitdesignpart3The iot academy_embeddedsystems_training_circuitdesignpart3
The iot academy_embeddedsystems_training_circuitdesignpart3
The IOT Academy
 
The iot academy_embeddedsystems_training_basicselectronicspart2
The iot academy_embeddedsystems_training_basicselectronicspart2The iot academy_embeddedsystems_training_basicselectronicspart2
The iot academy_embeddedsystems_training_basicselectronicspart2
The IOT Academy
 
The iot academy_embeddedsystems_training_basicelectronicspart1
The iot academy_embeddedsystems_training_basicelectronicspart1The iot academy_embeddedsystems_training_basicelectronicspart1
The iot academy_embeddedsystems_training_basicelectronicspart1
The IOT Academy
 
The iot academy_lpwan
The iot academy_lpwanThe iot academy_lpwan
The iot academy_lpwan
The IOT Academy
 
The iotacademy industry4.0_talk_slideshare
The iotacademy industry4.0_talk_slideshareThe iotacademy industry4.0_talk_slideshare
The iotacademy industry4.0_talk_slideshare
The IOT Academy
 
The iot acdemy_awstraining_part4_aws_lab
The iot acdemy_awstraining_part4_aws_labThe iot acdemy_awstraining_part4_aws_lab
The iot acdemy_awstraining_part4_aws_lab
The IOT Academy
 

More from The IOT Academy (20)

Embedded Systems Programming
Embedded Systems ProgrammingEmbedded Systems Programming
Embedded Systems Programming
 
Introduction to Digital Marketing Certification Course.pdf
Introduction to Digital Marketing Certification Course.pdfIntroduction to Digital Marketing Certification Course.pdf
Introduction to Digital Marketing Certification Course.pdf
 
Google SEO 2023: Complete SEO Guide
Google SEO 2023: Complete SEO GuideGoogle SEO 2023: Complete SEO Guide
Google SEO 2023: Complete SEO Guide
 
Embedded C The IoT Academy
Embedded C The IoT AcademyEmbedded C The IoT Academy
Embedded C The IoT Academy
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
MachineLlearning introduction
MachineLlearning introductionMachineLlearning introduction
MachineLlearning introduction
 
IoT Node-Red Presentation
IoT  Node-Red PresentationIoT  Node-Red Presentation
IoT Node-Red Presentation
 
IoT Introduction Architecture and Applications
IoT Introduction Architecture and ApplicationsIoT Introduction Architecture and Applications
IoT Introduction Architecture and Applications
 
UCT IoT Deployment and Challenges
UCT IoT Deployment and ChallengesUCT IoT Deployment and Challenges
UCT IoT Deployment and Challenges
 
UCT Electrical Vehicle Infrastructure
UCT Electrical Vehicle InfrastructureUCT Electrical Vehicle Infrastructure
UCT Electrical Vehicle Infrastructure
 
Uct 5G Autonomous Cars
Uct 5G Autonomous CarsUct 5G Autonomous Cars
Uct 5G Autonomous Cars
 
Fdp uct industry4.0_talk
Fdp uct industry4.0_talkFdp uct industry4.0_talk
Fdp uct industry4.0_talk
 
Success ladder to the Corporate world
Success ladder to the Corporate worldSuccess ladder to the Corporate world
Success ladder to the Corporate world
 
The iot academy_lpwan_lora
The iot academy_lpwan_loraThe iot academy_lpwan_lora
The iot academy_lpwan_lora
 
The iot academy_embeddedsystems_training_circuitdesignpart3
The iot academy_embeddedsystems_training_circuitdesignpart3The iot academy_embeddedsystems_training_circuitdesignpart3
The iot academy_embeddedsystems_training_circuitdesignpart3
 
The iot academy_embeddedsystems_training_basicselectronicspart2
The iot academy_embeddedsystems_training_basicselectronicspart2The iot academy_embeddedsystems_training_basicselectronicspart2
The iot academy_embeddedsystems_training_basicselectronicspart2
 
The iot academy_embeddedsystems_training_basicelectronicspart1
The iot academy_embeddedsystems_training_basicelectronicspart1The iot academy_embeddedsystems_training_basicelectronicspart1
The iot academy_embeddedsystems_training_basicelectronicspart1
 
The iot academy_lpwan
The iot academy_lpwanThe iot academy_lpwan
The iot academy_lpwan
 
The iotacademy industry4.0_talk_slideshare
The iotacademy industry4.0_talk_slideshareThe iotacademy industry4.0_talk_slideshare
The iotacademy industry4.0_talk_slideshare
 
The iot acdemy_awstraining_part4_aws_lab
The iot acdemy_awstraining_part4_aws_labThe iot acdemy_awstraining_part4_aws_lab
The iot acdemy_awstraining_part4_aws_lab
 

Recently uploaded

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 

Recently uploaded (20)

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 

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.