SlideShare ist ein Scribd-Unternehmen logo
1 von 64
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Morse code (-- --- .-. ... . -.-. --- -.. .)
Morse code (-- --- .-. ... . -.-. --- -.. .)Morse code (-- --- .-. ... . -.-. --- -.. .)
Morse code (-- --- .-. ... . -.-. --- -.. .)Tushar Swami
 
Digital Communication: Channel Coding
Digital Communication: Channel CodingDigital Communication: Channel Coding
Digital Communication: Channel CodingDr. Sanjay M. Gulhane
 
8086-instruction-set-ppt
 8086-instruction-set-ppt 8086-instruction-set-ppt
8086-instruction-set-pptjemimajerome
 
8051 microcontroller and embedded system
8051 microcontroller and embedded system8051 microcontroller and embedded system
8051 microcontroller and embedded systemsb108ec
 
MPMC Microprocessor
MPMC MicroprocessorMPMC Microprocessor
MPMC MicroprocessorA.S. Krishna
 
Input Output programming in AVR microcontroller
Input  Output  programming in AVR microcontrollerInput  Output  programming in AVR microcontroller
Input Output programming in AVR microcontrollerRobo India
 
Digital t carriers and multiplexing power point (laurens)
Digital t carriers and multiplexing power point (laurens)Digital t carriers and multiplexing power point (laurens)
Digital t carriers and multiplexing power point (laurens)Laurens Luis Bugayong
 
Digital modulation techniqes (Phase-shift keying (PSK))
Digital modulation techniqes (Phase-shift keying (PSK))Digital modulation techniqes (Phase-shift keying (PSK))
Digital modulation techniqes (Phase-shift keying (PSK))Mohamed Sewailam
 
verilog code for logic gates
verilog code for logic gatesverilog code for logic gates
verilog code for logic gatesRakesh kumar jha
 
introduction to microprocessors
introduction to microprocessorsintroduction to microprocessors
introduction to microprocessorsvishi1993
 
Timing Diagram.pptx
Timing Diagram.pptxTiming Diagram.pptx
Timing Diagram.pptxISMT College
 
Analog communication
Analog communicationAnalog communication
Analog communicationPreston King
 
Gnu Radio and the Universal Software Radio Peripheral
Gnu Radio and the Universal Software Radio PeripheralGnu Radio and the Universal Software Radio Peripheral
Gnu Radio and the Universal Software Radio PeripheralAlexandru Csete
 
Assembly language programming_fundamentals 8086
Assembly language programming_fundamentals 8086Assembly language programming_fundamentals 8086
Assembly language programming_fundamentals 8086Shehrevar Davierwala
 
8086 memory segmentation
8086 memory segmentation8086 memory segmentation
8086 memory segmentationSridari Iyer
 

Was ist angesagt? (20)

Morse code (-- --- .-. ... . -.-. --- -.. .)
Morse code (-- --- .-. ... . -.-. --- -.. .)Morse code (-- --- .-. ... . -.-. --- -.. .)
Morse code (-- --- .-. ... . -.-. --- -.. .)
 
Digital Communication: Channel Coding
Digital Communication: Channel CodingDigital Communication: Channel Coding
Digital Communication: Channel Coding
 
8086-instruction-set-ppt
 8086-instruction-set-ppt 8086-instruction-set-ppt
8086-instruction-set-ppt
 
8051 microcontroller and embedded system
8051 microcontroller and embedded system8051 microcontroller and embedded system
8051 microcontroller and embedded system
 
MPMC Microprocessor
MPMC MicroprocessorMPMC Microprocessor
MPMC Microprocessor
 
Input Output programming in AVR microcontroller
Input  Output  programming in AVR microcontrollerInput  Output  programming in AVR microcontroller
Input Output programming in AVR microcontroller
 
DMA operation
DMA operationDMA operation
DMA operation
 
Digital t carriers and multiplexing power point (laurens)
Digital t carriers and multiplexing power point (laurens)Digital t carriers and multiplexing power point (laurens)
Digital t carriers and multiplexing power point (laurens)
 
Digital modulation techniqes (Phase-shift keying (PSK))
Digital modulation techniqes (Phase-shift keying (PSK))Digital modulation techniqes (Phase-shift keying (PSK))
Digital modulation techniqes (Phase-shift keying (PSK))
 
verilog code for logic gates
verilog code for logic gatesverilog code for logic gates
verilog code for logic gates
 
Assembly fundamentals
Assembly fundamentalsAssembly fundamentals
Assembly fundamentals
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
introduction to microprocessors
introduction to microprocessorsintroduction to microprocessors
introduction to microprocessors
 
Processor powerpoint 2
Processor powerpoint 2Processor powerpoint 2
Processor powerpoint 2
 
Timing Diagram.pptx
Timing Diagram.pptxTiming Diagram.pptx
Timing Diagram.pptx
 
Analog communication
Analog communicationAnalog communication
Analog communication
 
Gnu Radio and the Universal Software Radio Peripheral
Gnu Radio and the Universal Software Radio PeripheralGnu Radio and the Universal Software Radio Peripheral
Gnu Radio and the Universal Software Radio Peripheral
 
Assembly language programming_fundamentals 8086
Assembly language programming_fundamentals 8086Assembly language programming_fundamentals 8086
Assembly language programming_fundamentals 8086
 
8086 memory segmentation
8086 memory segmentation8086 memory segmentation
8086 memory segmentation
 
8085 Architecture
8085 Architecture8085 Architecture
8085 Architecture
 

Ähnlich wie The IoT Academy IoT Training Arduino Part 3 programming

Arduino-2 (1).ppt
Arduino-2 (1).pptArduino-2 (1).ppt
Arduino-2 (1).pptHebaEng
 
Arduino cic3
Arduino cic3Arduino cic3
Arduino cic3Jeni Shah
 
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 + ProcessingDemetrio 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.pdfJayanthi Kannan MK
 
Arduino for Beginners
Arduino for BeginnersArduino for Beginners
Arduino for BeginnersSarwan 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 2016Svet 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.pdfSIGMATAX1
 
Arduino - Module 1.pdf
Arduino - Module 1.pdfArduino - Module 1.pdf
Arduino - Module 1.pdfrazonclarence4
 
Syed IoT - module 5
Syed  IoT - module 5Syed  IoT - module 5
Syed IoT - module 5Syed 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 iiJonah Marrs
 

Ähnlich wie 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
 

Mehr von The IOT Academy

Embedded Systems Programming
Embedded Systems ProgrammingEmbedded Systems Programming
Embedded Systems ProgrammingThe 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.pdfThe IOT Academy
 
Google SEO 2023: Complete SEO Guide
Google SEO 2023: Complete SEO GuideGoogle SEO 2023: Complete SEO Guide
Google SEO 2023: Complete SEO GuideThe IOT Academy
 
Embedded C The IoT Academy
Embedded C The IoT AcademyEmbedded C The IoT Academy
Embedded C The IoT AcademyThe IOT Academy
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageThe IOT Academy
 
MachineLlearning introduction
MachineLlearning introductionMachineLlearning introduction
MachineLlearning introductionThe IOT Academy
 
IoT Node-Red Presentation
IoT  Node-Red PresentationIoT  Node-Red Presentation
IoT Node-Red PresentationThe IOT Academy
 
IoT Introduction Architecture and Applications
IoT Introduction Architecture and ApplicationsIoT Introduction Architecture and Applications
IoT Introduction Architecture and ApplicationsThe IOT Academy
 
UCT IoT Deployment and Challenges
UCT IoT Deployment and ChallengesUCT IoT Deployment and Challenges
UCT IoT Deployment and ChallengesThe IOT Academy
 
UCT Electrical Vehicle Infrastructure
UCT Electrical Vehicle InfrastructureUCT Electrical Vehicle Infrastructure
UCT Electrical Vehicle InfrastructureThe IOT Academy
 
Fdp uct industry4.0_talk
Fdp uct industry4.0_talkFdp uct industry4.0_talk
Fdp uct industry4.0_talkThe IOT Academy
 
Success ladder to the Corporate world
Success ladder to the Corporate worldSuccess ladder to the Corporate world
Success ladder to the Corporate worldThe IOT Academy
 
The iot academy_lpwan_lora
The iot academy_lpwan_loraThe iot academy_lpwan_lora
The iot academy_lpwan_loraThe IOT Academy
 
The iot academy_embeddedsystems_training_circuitdesignpart3
The iot academy_embeddedsystems_training_circuitdesignpart3The iot academy_embeddedsystems_training_circuitdesignpart3
The iot academy_embeddedsystems_training_circuitdesignpart3The IOT Academy
 
The iot academy_embeddedsystems_training_basicselectronicspart2
The iot academy_embeddedsystems_training_basicselectronicspart2The iot academy_embeddedsystems_training_basicselectronicspart2
The iot academy_embeddedsystems_training_basicselectronicspart2The IOT Academy
 
The iot academy_embeddedsystems_training_basicelectronicspart1
The iot academy_embeddedsystems_training_basicelectronicspart1The iot academy_embeddedsystems_training_basicelectronicspart1
The iot academy_embeddedsystems_training_basicelectronicspart1The IOT Academy
 
The iotacademy industry4.0_talk_slideshare
The iotacademy industry4.0_talk_slideshareThe iotacademy industry4.0_talk_slideshare
The iotacademy industry4.0_talk_slideshareThe 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_labThe IOT Academy
 

Mehr von 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
 

Kürzlich hochgeladen

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 

Kürzlich hochgeladen (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

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.