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

The IoT Academy IoT Training Arduino Part 3 programming

  • 1.
  • 2.
    Arduino Code Basics Arduinoprograms 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 sectionis 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 3LED’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 Task1 to have an advanced green (blinking green LED) for 3 seconds before illuminating the green LED for 5 seconds 7
  • 8.
    Variables A variable islike “bucket” It holds numbers or other values temporarily 8 value
  • 9.
    DECLARING A VARIABLE 9 intval = 5; Type variable name assignment “becomes” value
  • 10.
    Task Replace all delaytimes 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 decisionsin 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
  • 15.
  • 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 withinteger 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 acommand, 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:
  • 20.
  • 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 toindicate 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: Usedfunctions: 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 theConsole 26 void setup() { Serial.begin(9600); Serial.println(“Hello World!”); } void loop() {}
  • 27.
    IF - ELSECondition if( “answer is true”) { “perform some action” } else { “perform some other action” }
  • 28.
    IF - ELSEExample 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 - ELSEIF Condition if( “answer is true”) { “perform some action” } else if( “answer is true”) { “perform some other action” }
  • 30.
    IF - ELSEExample 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 programthat 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 alsouse 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 andoutput 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 aprogram 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
  • 38.
  • 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 programthat 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 programthat 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 thevalue 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 voidloop() //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 andbuttons 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 inputsand 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 bargraph 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 bargraph 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 intinPin = 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 fromArduino void setup() { Serial.begin(9600); } void serialtest() { int i; for(i=0; i<10; i++) Serial.println(i); }
  • 51.
    Using Interrupts  Ona 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.hlibrary)  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.hlibrary) 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.hlibrary) 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" Timert; 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(); } voiddoSomething() { 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) Setspin 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
  • 60.
  • 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 isnecessary  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.