0% found this document useful (0 votes)
3 views65 pages

D3S1 Arduino Programming

The document provides an introduction to Arduino programming, detailing its features, types of boards, and the Arduino IDE used for coding. It covers the setup process, sketch structure, supported data types, and various functions and libraries available for programming. Additionally, it includes examples of projects such as a blinking LED and a traffic control system, along with information on sensors and actuators used in IoT applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views65 pages

D3S1 Arduino Programming

The document provides an introduction to Arduino programming, detailing its features, types of boards, and the Arduino IDE used for coding. It covers the setup process, sketch structure, supported data types, and various functions and libraries available for programming. Additionally, it includes examples of projects such as a blinking LED and a traffic control system, along with information on sensors and actuators used in IoT applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Programming for IoT

Introduction to Arduino Programming

Parichay Bhattacharjee
Manager, CRM-III
Bokaro Steel Plant
Steel Authority of India Limited
Email: [email protected]
1
Features of Arduino

▪ Open source based electronic programmable board (micro


controller)and software(IDE)
▪ Accepts analog and digital signals as input and gives desired
output
▪ No extra hardware required to load a program into the
controller board

2
Types of Arduino Board

▪ Arduino boards based on ATMEGA328 microcontroller

▪ Arduino boards based on ATMEGA32u4 microcontroller

▪ Arduino boards based on ATMEGA2560 microcontroller

▪ Arduino boards based on AT91SAM3X8E microcontroller

3
Arduino UNO

Feature Value
Operating Voltage 5V
Clock Speed 16MHz
Digital I/O 14
Analog Input 6
PWM 6
UART 1
Interface USB via ATMega16U2

4
Board Details
▪ Power Supply: USB or
power barrel jack
▪ Voltage Regulator
▪ LED Power Indicator
▪ Tx-Rx LED Indicator
▪ Output power, Ground
▪ Analog Input Pins
▪ Digital I/O Pins
Image source: https://upload.wikimedia.org/wikipedia/commons/9/9d/UnoConnections.jpg

5
Arduino IDE

▪ Arduino IDE is an open source software that is used to


program the Arduino controller board
▪ Based on variations of the C and C++ programming
language
▪ It can be downloaded from Arduino’s official website and
installed into PC

6
Set Up

▪ Power the board by connecting it to a PC via USB cable


▪ Launch the Arduino IDE
▪ Set the board type and the port for the board
▪ TOOLS -> BOARD -> select your board
▪ TOOLS -> PORT -> select your port

7
Set up (contd..)

8
Arduino IDE Overview

Program coded in Arduino IDE


is called a SKETCH

9
Arduino IDE Overview (contd..)
▪ To create a new sketch
▪ File -> New
▪ To open an existing sketch
▪ File -> open ->
▪ There are some basic ready-to-use
sketches available in the EXAMPLES
section
▪ File -> Examples -> select any program

10
Arduino IDE Overview (contd..)
▪ Verify: Checks the code for
compilation errors
▪ Upload: Uploads the final code to
the controller board
▪ New: Creates a new blank sketch
with basic structure
▪ Open: Opens an existing sketch
▪ Save: Saves the current sketch

11
Arduino IDE Overview (contd..)

▪ Serial Monitor: Opens the serial


console
▪ All the data printed to the console
are displayed here

12
Sketch Structure
▪ A sketch can be divided into two parts:
▪ Setup ()
▪ Loop()
▪ The function setup() is the point where
the code starts, just like the main()
function in C and C++
▪ I/O Variables, pin modes are initialized in
the Setup() function
▪ Loop() function, as the name suggests,
iterates the specified task in the program

13
Supported Datatype
▪ Arduino supports the following data
types-

Void Long
Int Char
Boolean Unsigned char
Byte Unsigned int
Word Unsigned long
Float Double
Array String-char array
String-object Short

14
Arduino Function Libraries
▪ Input/Output Functions:
▪ The arduino pins can be configured to act as input or output pins using the
pinMode() function

Void setup ()
{
pinMode (pin , mode);
}
Pin- pin number on the Arduino board
Mode- INPUT/OUTPUT

15
Arduino Function Libraries (contd..)
▪ digitalWrite() : Writes a HIGH or LOW value to a digital pin

▪ analogRead() : Reads from the analog input pin i.e., voltage applied across the
pin

▪ Character functions such as isdigit(), isalpha(), isalnum(), isxdigit(), islower(),


isupper(), isspace() return 1(true) or 0(false)

▪ Delay() function is one of the most common time manipulation function used
to provide a delay of specified time. It accepts integer value (time in
miliseconds)

16
Example- Blinking LED
▪ Requirement:
▪ Arduino controller board, USB connector,
Bread board, LED, 1.4Kohm resistor,
connecting wires, Arduino IDE
▪ Connect the LED to the Arduino using the
Bread board and the connecting wires
▪ Connect the Arduino board to the PC using
the USB connector
▪ Select the board type and port
▪ Write the sketch in the editor, verify and
upload.

17
Example- Blink (contd..)

Connect the positive terminal of the


LED to digital pin 12 and the negative
terminal to the ground pin (GND) of
Arduino Board

18
Example- Blink (contd..) image setup
void setup() {
pinMode(12, OUTPUT); // set the pin mode
}
void loop() {
digitalWrite(12, HIGH); // Turn on the LED
delay(1000);
digitalWrite(12, LOW); //Turn of the LED
delay(1000);
}

19
Example- Blink (contd..)
Set the pin mode as output which is
connected to the led, pin 12 in this
case.

Use digitalWrite() function to set the


output as HIGH and LOW

Delay() function is used to specify


the delay between HIGH-LOW
transition of the output

20
Example- Blink (contd..) image setup

▪ Connect he board to the PC

▪ Set the port and board type

▪ Verify the code and upload, notice the TX –


RX led in the board starts flashing as the
code is uploaded.

21
Content

▪ Operators in Arduino ▪ Random Number


▪ Control Statement ▪ Interrupts
▪ Loops ▪ Example Program
▪ Arrays
▪ String
▪ Math Library

2
Operators
▪ Arithmetic Operators: =, +, -, *, /, %
▪ Comparison Operator: ==, !=, <, >, <=, >=
▪ Boolean Operator: &&, ||, !
▪ Bitwise Operator: &, |, ^, ~, <<, >>,
▪ Compound Operator: ++, --, +=, -=, *=, /=, %=, |=, &=

3
Control Statement
▪ If…….Elseif…..Else
▪ If statement ▪ if (condition1){
▪ if(condition){ Statements if the
Statements if the condition1 is true;
condition is true ; }
} else if (condition2){
▪ If…Else statement Statements if the
▪ if(condition ){ condition1 is false
Statements if the and condition2 is true;
condition is true; }
} else{
else{ Statements if both the
Statements if the conditions are false;
condition is false; }
}

4
Control Statement (contd..)
▪ Switch Case
▪ Switch(choice)
{
case opt1: statement_1;break;
case opt2: statement_2;break;
case opt3: statement_3;break;
.
.
.
case default: statement_default; break;
}

▪ Conditional Operator.
▪ Val=(condition)?(Statement1): (Statement2)

5
Loops
▪ For loop
▪ for(initialization; condition;
increment){ Statement till the
condition is true;
}
▪ While loop
▪ while(condition){
Statement till the condition is true;
}
▪ Do… While loop
▪ do{
Statement till the condition is true;
}while(condition);

6
Loops (contd..)
▪ Nested loop: Calling a loop inside another loop

▪ Infinite loop: Condition of the loop is always true, the loop will never
terminate

7
Arrays
▪ Collection of elements having homogenous datatype that are
stored in adjacent memory location.
▪ The conventional starting index is 0.
▪ Declaration of array:
<Datatype> array_name[size];
Ex: int arre[5];

8
Arrays (contd..)
▪ Alternative Declaration:
int arre[]={0,1,2,3,4};
int arre[5]={0,1,2};
▪ Multi-dimentional array Declaration:
<Datatype> array_name[n1] [n2][n3]….;
Ex: int arre[row][col][height];

9
String
▪ Array of characters with NULL as termination is termed as a String.
▪ Declaration using Array:
▪ char str[]=“ABCD”;
▪ char str[4];
▪ str[0]=‘A’;
▪ str[0]=‘B’;
▪ str[0]=‘C’;
▪ str[0]=0;
▪ Declaration using String Object:
▪ String str=“ABC”;

10
String (contd..)
▪ Functions of String Object:
▪ str.ToUpperCase(): change all the characters of str to upper case
▪ str.replace(str1,str2): is str1 is the sub string of str then it will be
replaced by str2
▪ str.length(): returns the length of the string without considering null

11
Math Library
▪ To apply the math functions and mathematical constants, “MATH.h” header
files is needed to be included.
▪ Functions:
▪ cos(double radian);
▪ sin(double radian);
▪ tan(double radian);
▪ fabs(double val);
▪ fmod(double val1, double val2);

12
Math Library (contd..)
▪ Functions:
▪ exp(double val);
▪ log(double val);
▪ log10(double val);
▪ square(double val);
▪ pow(double base, double power);

13
Random Number
▪ randomSeed(int v): reset the pseudo-random number generator
with seed value v
▪ random(maxi)=gives a random number within the range [0,maxi]
▪ random(mini,maxi)=gives a random number within the range
[mini,maxi]

14
Interrupts
▪ An external signal for which system blocks the current running
process to process that signal
▪ Types:
▪ Hardware interrupt
▪ Software interrupt
▪ digitalPinToInterrupt(pin): Change actual digital pin to the specific
interrupt number.
▪ attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
▪ ISR: a interrupt service routine have to be defined

15
Example: Traffic Control System

Requirement:
▪ Arduino Board
▪ 3 different color LEDs
▪ 330 Ohm resistors
▪ Jumper wires

16
Example: Traffic Control System (contd..)
Connection:
▪ Connect the positive
terminals of the LEDs to
the respective digital
output pins in the board,
assigned in the code.
▪ Connect the negative
terminals of the LEDs to
the ground

17
Example: Traffic Control System (contd..)
▪ Sketch
//LED pins
int r = 2;
int g = 3;
int y = 4;
void setup()
{
Serial.begin(9600);
pinMode(r, OUTPUT); digitalWrite(r,LOW);
pinMode(g, OUTPUT); digitalWrite(g,LOW);
pinMode(y , OUTPUT); digitalWrite(y, LOW);
}

18
Example: Traffic Control System (contd..)
void traffic()
{
digitalWrite(g, HIGH);
Serial.println(“Green LED: ON, GO”);
// delay of 5 seconds
delay(5000);
digitalWrite(g, LOW);
digitalWrite(y, HIGH);
Serial.println(“Green LED: OFF ; Yellow LED: ON, WAIT”);
delay(5000);

19
Example: Traffic Control System (contd..)
digitalWrite(y, LOW);
digitalWrite(r, HIGH);
Serial.println(“Yellow LED: OFF ; Red LED: ON, STOP");
delay(5000); // for 5 seconds
digitalWrite(r, LOW);
Serial.println(“All OFF");
}

void loop()
{
traffic ();
delay (10000);
}

20
Example: Traffic Control System (contd..)
Output:
▪ Initially, all the LEDs are turned
off
▪ The LEDs are turned on one at
a time with a delay of 5
seconds
▪ The message is displayed
accordingly
▪ Figure showing all the LEDs
turned on

21
Output

22
Sensors

▪ Electronic elements
▪ Converts physical quantity/ measurements into electrical
signals
▪ Can be analog or digital

2
Types of Sensors

Some commonly used sensors:


▪ Temperature
▪ Humidity
▪ Compass
▪ Light
▪ Sound
▪ Accelerometer

3
Sensor Interface with Arduino

▪ Digital Humidity and Temperature


Sensor (DHT)
▪ PIN 1, 2, 3, 4 (from left to right)
▪ PIN 1- 3.3V-5V Power supply
▪ PIN 2- Data
▪ PIN 3- Null
▪ PIN 4- Ground

4
DHTSensor Library

▪ Arduino supports a special library for the DHT11 and DHT22


sensors
▪ Provides function to read the temperature and humidity
values from the data pin
dht.readHumidity()
dht.readTemperature()

5
Connection
▪ Connect pin 1 of the DHT
to the 3.3 V supply pin in
the board
▪ Data pin (pin 2) can be
connected to any digital
pin, here 12
▪ Connect pin 4 to the
ground (GND) pin of the
board

6
Sketch: DHT_SENSOR

Install the DHT Sensor Library

▪ Go to Sketch -> Include Library ->


Manage Library

7
Sketch: DHT_SENSOR (contd..)

▪ Search for DHT SENSOR


▪ Select the “DHT sensor
library” and install it

8
Sketch: DHT_SENSOR (contd..)
#include <DHT.h>; void loop()
DHT dht(8, DHT22); //Initialize DHT sensor {
//Read data from the sensor and store it to variables
float humidity; //Stores humidity value humidity and temperature
float temperature; //Stores temperature humidity = dht.readHumidity();
value temperature= dht.readTemperature();
void setup() //Print temperature and humidity values to serial
{ monitor
Serial.begin(9600); Serial.print("Humidity: ");
Serial.print(humidity);
dht.begin();
Serial.print("%, Temperature: ");
} Serial.print(temperature);
Serial.println(" Celsius");
delay(2000); //Delay of 2 seconds
}
9
Sketch: DHT_SENSOR (contd..)

10
Sketch: DHT_SENSOR (contd..)
▪ Connect the board to the PC

▪ Set the port and board type

▪ Verify and upload the code

11
Output

The readings are printed at a delay of


2 seconds as specified by the delay()
function

12
Actuators

▪ Mechanical/Electro-mechanical device
▪ Converts energy into motion
▪ Mainly used to provide controlled motion to other
components

3
Basic Working Principle

Uses different combination of various mechanical


structures like screws, ball bearings, gears to produce
motion.

4
Types of Motor Actuators

▪ Servo motor
▪ Stepper motor
▪ Hydraulic motor
▪ Solenoid
▪ Relay
▪ AC motor

5
Servo Motor
▪ High precision motor
▪ Provides rotary motion 0
to 180 degree
▪ 3 wires in the Servo motor
▪ Black or the darkest one is
Ground
▪ Red is for power supply
▪ Yellow for signal pin

6
Servo Library on Arduino

▪ Arduino provides different library- SERVO


to operate the servo motor
▪ Create an instance of servo to use it in the
sketch
Servo myservo;

7
Sketch: SERVO_ACTUATOR
void loop(){
#include <Servo.h> //Servo moves to 0 degrees
//Including the servo library for the program ServoDemo.write(0);
int servoPin = 12; delay(1000);

// Servo moves to 90 degrees


Servo ServoDemo; // Creating a servo object
ServoDemo.write(90);
void setup() { delay(1000);
// The servo pin must be attached to the servo
before it can be used // Servo moves to 180 degrees
ServoDemo.attach(servoPin); ServoDemo.write(180);
} delay(1000);
}

8
Sketch: SERVO_ACTUATOR ( contd..)

▪ Create an instance of Servo


▪ The instance must be attached
to the pin before being used in
the code
▪ Write() function takes the
degree value and rotates the
motor accordingly

9
Connection

▪ Connect the Ground of the


servo to the ground of the
Arduino board.
▪ Connect the power supply wire
to the 5V pin of the board.
▪ Connect the signal wire to any
digital output pin (we have used
pin 8).

10
Board Setup
▪ Connect the board to the PC

▪ Set the port and board type

▪ Verify and upload the code

11
Output

The motor turns 0, 90 and 180


degrees with a delay of 1 second
each.

12
Do more with the Servo library
Some other functions available with the Servo
library:
▪ Knob()
▪ Sweep()
▪ write()
▪ writeMicroseconds()
▪ read()
▪ attached()
▪ detach()

Source: “Servo Library”, Arduino Home (Online), Link: www.arduino.cc/en/Reference/Servo

13
14

You might also like