Iot Module 2 Material

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 36

Introduction to Arduino

• Arduino is an open-source platform used for building electronics projects.


• A microcontroller board, contains on board power supply, USB for programming and
Microcontroller chip.
• The Arduino platform has become quite popular with people because it does not need a
separate piece of hardware (called a programmer) in order to load new code onto the board
• Arduino can interact with buttons, LEDs, motors, speakers, GPS units, cameras, the internet,
smart-phone and TV. This flexibility combined with the fact that the Arduino software is free,
the hardware boards are pretty cheap, and both the software and hardware are easy to learn.
Features
• It consists on board Atmega328 Microcontroller
• It has an operating voltage of 5V while the input voltage may vary from 7V to 12V.
• Arduino UNO has a maximum current rating of 40mA, so the load shouldn't exceed
this current rating or you may harm the board.
• It comes with a crystal oscillator of 16MHz, which is its operating frequency.
• Arduino Uno Pinout consists of 14 digital pins starting from D0 to D13.
• It also has 6 analog pins starting from A0 to A5.
• It also has 1 Reset Pin, which is used to reset the board programmatically. In order to
reset the board, we need to make this pin LOW.
• It also has 6 Power Pins, which provide different voltage levels.
Out of 14 digital pins, 6 pins are used for generating PWM pulses of 8-Bit resolution. PWM
pins in Arduino UNO are D3, D5, D6, D9, D10 and D11.
• Arduino UNO comes with 3 types of memories associated with it, named:
Flash Memory: 32KB
SRAM: 2KB
EEPROM: 1KB
• Arduino UNO supports 3 types of communication protocols, used for interfacing with
third-party peripherals, named:
Serial Protocol
I2C Protocol
SPI Protocol
• Apart from USB, a battery or AC to DC adopter can also be used to power the board.
Arduino UNO comes with a USB interface i.e. USB port is added on the board to develop
serial communication with the computer.
Arduino - Installation

The software used for writing, compiling & uploading code to Arduino boards is called
Arduino IDE (Integrated Development Environment), which is free to download from
Arduino Official Site.

◎ Before you start programming, double check that correct board is selected under
Tools  Board.
Now, you can start playing with Arduino.

◎ The Arduino Uno can be programmed with the Arduino software. Select "Arduino
Uno from the Tools > Board menu (according to the microcontroller on your board).
◎ All the peripheral connected with Computers are using Serial Port.
You can check port for Arduino Uno in Device Manger.
Major Functions
◎ digitalWrite()
◎ analogWrite()
◎ digitalRead()
◎ If (statements) / Boolean
◎ analogRead
Serial Communication

Arduino Bootloader
• As you go to the Tools section, you will find a bootloader at the end.
It is very helpful to burn the code directly into the controller, setting you free from buying the
external burner to burn the required code.
Interfacing an LED with Arduino UNO
• LEDs are small, powerful lights that are used in many different applications.
we should not connect LED directly to Arduino. As the GPIO pins of Arduino provide 5V on
a HIGH state, due to overvoltage, the LED might get damaged. A resistor in series with the
LED pin has to be used to avoid over-voltage damage.

void setup()
{
pinMode(13, OUTPUT); // initialize digital pin 13 as an output.
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
◎ pinMode(13, OUTPUT) : Before using one of Arduino’s pins, we need to tell
Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in “function”
called pinMode() to do this.
◎ digitalWrite(13, HIGH) : When any pin use as an OUTPUT, we can command it to
be HIGH (output 5 volts), or LOW (output 0 volts).
Interfacing Push button and LED with Arduino UNO

::: Switch and Display :::


When swith is pressed then LED will ON.*/
const int BUTTON = 2;
const int LED = 13;
int BUTTONstate = 0;
void setup()
{
pinMode(BUTTON, INPUT);
pinMode(LED, OUTPUT);
}

void loop()
{
BUTTONstate = digitalRead(BUTTON); if (BUTTONstate == HIGH)
{
digitalWrite(LED, HIGH);
}
else{
digitalWrite(LED, LOW);
}
delay(100);
}
◎ pinMode(13, OUTPUT) : Before using one of Arduino’s pins, we need to tell
Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in “function”
called pinMode() to do this.
◎ digitalWrite(13, HIGH) : When any pin use as an OUTPUT, we can command it to
be HIGH (output 5 volts), or LOW (output 0 volts).
LCD interfacing to Arduino UNO
VEE: Contrast adjustment; through a variable resistor of 10K ohm.
RS: Selects data register when high and command register when low
RW: High to read from the register, Low to write to the register
E:Sends data to data pins when a high to low pulse is given
LEDA: Backlight VCC (5V) (Anode)
LEDK: Backlight Ground (0V) (Cathode)

// include the library code:


#include <LiquidCrystal.h>
// initialize the library by associating any needed LCD interface pin// with the
arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD. lcd.print("hello, world!");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis() / 1000);
}

Temperature sensor interfacing with Arduino UNO

DHT11 Temperature and Humidity sensor


• The DHT11 is a basic, ultra low-cost digital temperature and humidity sensor.
• It's fairly simple to use but requires careful timing to grab data.
It uses a capacitive humidity sensor and a thermistor to measure the surrounding air
and spits out a digital signal on the data pin (no analog input pins needed).
• thermistor is a temperature sensing element and it can operate over a wide
temperature range and give temperature value by its resistance change.
For measuring temperature this sensor uses a Negative Temperature coefficient
thermistor, which causes a decrease in its resistance value with increase in
temperature.
The humidity sensor component consists of two electrodes containing a dehydrated
substrate sandwich. The ions are released into the substrate as water vapor absorbs it,
which in turn increases the conductivity between the electrodes.
The resistance change between the two electrodes is proportional to the relative
humidity. High relative humidity reduces the resistance between the electrodes, while
low relative humidity increases the resistance between the electrodes.
Features of DHT11 Sensor
• Cheap in Price.
• The temperature range of DHT11 is from 0 to 50 degree Celsius with a 2-degree
accuracy.
• Humidity range of this sensor is from 20 to 80% with 5% accuracy.
• The sampling rate of this sensor is 1Hz .i.e. it gives one reading for every second.
• DHT11 is small in size with operating voltage from 3 to 5 volts.
• The maximum current used while measuring is 2.5mA.
3 pins with 0.1″ spacing
include <dht.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(3, 4, 5, 6, 7, 8);
#define dhtpin A0// the output pin of DH11
dht DHT;
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
}
void loop()
{
int val= DHT.read11(7);
int cel= DHT.temperature;
int humi=DHT.humidity;
lcd.print("Temperature: ");
lcd.print(cel);// display the temperature
lcd.print((char)223);
lcd.setCursor(0, 1);
lcd.print("humidity: ");
lcd.print(humi); // display the humidity
delay(1000);
lcd.clear();
}

Applications of DHT11 sensor


 Air conditioning systems.
 Weather stations
 In homes where people are affected by humidity.
Offices, cars, museums, greenhouses and industries use this sensor for measuring
humidity values and as a safety measure.

Interfacing IR Sensor Module with Arduino UNO


• An infrared proximity sensor or IR Sensor is an electronic device that emits infrared
lights to sense some aspect of the surroundings and can be employed to detect the
motion of an object.
• It can only measure infrared radiation.
In the output pin, LOW indicates no motion is detected; HIGH means motion is detected.
The various parts of IR Motion Sensor Module
• This sensor has three pins, VCC, GND and OUT(data pin).
• It has an onboard power LED
• A signal LED which turns on when the circuit is triggered.
• This board also has a comparator Op-amp that is responsible for converting the
incoming analog signal from the photodiode to a digital signal.
It also had a sensitivity adjustment potentiometer which is used to adjust the sensitivity
(triggering distance for this module) of the device.
It had a photodiode and the IR emitting LED pair which all together make the total IR
Proximity Sensor Module.

Working of IR Sensor Module


• It consists of two main components: the first is the IR transmitter section and the
second is the IR receiver section.
• In the transmitter section- IR led is used
• In the receiver section- a photodiode is used to receive infrared signal.
When you power on the board, the Infrared Light Emitting Diode which in turn emits infrared
light.

• This light propagates through the air and hits an object, after that the light gets
reflected in the photodiode sensor.
If the object is close- The reflected light will be stronger
If the object is far away- The reflected light will be weaker.
When the sensor becomes active it sends a corresponding Low signal through the output pin
that can be sensed by an Arduino.
Source CodeSource Code
// Arduino IR Sensor Code
int IRSensor = 9; // connect ir sensor module to Arduino pin 9
int LED = 13; // conect LED to Arduino pin 13
void setup()
{
Serial.begin(115200); // Init Serila at 115200 Baud
Serial.println("Serial Working"); // Test to check if serial is working or not
pinMode(IRSensor, INPUT); // IR Sensor pin INPUT
pinMode(LED, OUTPUT); // LED Pin Output
}
void loop()
{
int sensorStatus = digitalRead(IRSensor); // Set the GPIO as Input
if (sensorStatus == 1) // Check if the pin high or not
{
// if the pin is high turn off the onboard Led
digitalWrite(LED, LOW); // LED LOW
Serial.println("Motion Ended!"); // print Motion Detected! on the serial monitor
window
}
else
{
//else turn on the onboard LED
digitalWrite(LED, HIGH); // LED High
Serial.println("Motion Detected!"); // print Motion Ended! on the serial monitor window
}
}

Applications of IR sensor
1)Night Vision Device
2) Radiation Thermometers
3) IR Imaging Devices

Servo motor Interfacing with Arduino UNO


• It is an electric device that is used to control angular rotation.
• It is a rotary actuator or linear actuator.
• The user can control the rotation speed and position (angle) precisely.
• A servo motor has 3 pins.
VCC ( 5 Volts )
GND
Signal ( Control input signal )
You can control the servo motor by sending a series of pulses to it. A typical servo motor
expects a pulse every 20 milliseconds
• A short pulse of 1 ms or less will rotate the servo to 0 degrees (one extreme).
• A pulse duration of 1.5 ms will rotate the servo to 90 degrees (middle position).
 pulse duration of 2 ms or so will rotate the servo to 180 degrees (other extreme).

Pulses ranging from 1ms to 2ms will rotate the servo to a position proportional to the pulse
width.
INTRODUCTION TO PYTHON
• Python is a very popular general-purpose interpreted, interactive, object-oriented, and
high-level programming language.
• Programming Language
An ordered set of instructions to be executed by a computer to carry out a specific
task is called a program
The language used to specify this set of instructions to the computer is called a
programming language
• What is High-level language and Why ?
The languages which can understand by the humans, later it can convert in the
form of machine understandable language ( machine language…0s and 1s)
Language Translators: Compiler and Interpreter
• A program written in a high-level language is called source code.
A compiler translates the entire source code, as a whole, into the object code. After scanning
the whole program, it generates error messages, if any

Python uses an interpreter which processes the program statements one by one, first
translating and then executing. This process is continued until an error is encountered or the
whole program is executed successfully.

Compiled Language Interpreted Language


• The Reasons why python is popular
 Easy to Learn and Use
 Mature and Supportive Python Community
 Support from Renowned Corporate Sponsors
 Hundreds of Python Libraries and Frameworks
 Versatility, Efficiency, Reliability, and Speed
 Big data, Machine Learning and Cloud Computing
 First-choice Language
 The Flexibility of Python Language
 Use of python in academics
Keywords
• Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter.
• we can use a keyword in our program only for the purpose for which it has been
defined.
As Python is case sensitive, keywords must be written exactly as given below.

Identifiers
• In programming languages, identifiers are names used to identify a variable, function,
or other entities in a program.
• There are some rules for writing Identifiers. But first you must know Python is case
sensitive. That means Name and name are two different identifiers in Python. Here
are some rules for writing Identifiers in python.
• The name should begin with an uppercase or a lowercase alphabet or an
underscore sign (_).
• This may be followed by any combination of characters a–z, A–Z, 0–9 or
underscore (_). Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and
meaningful).
• It should not be a keyword or reserved word
We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
Variables
• A variable in a program is uniquely identified by a name (identifier). Variable in
Python refers to an object — an item or element that is stored in the memory.
• Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric (e.g., 345) or
any combination of alphanumeric characters (CD67).
• In Python we can use an assignment statement (=) to create new variables and assign
specific values to them.
Ex:
gender = 'M‘
message = "Keep Smiling"
price=987.9
Comments
• Comments are used to add a remark or a note in the source code. Comments are not
executed by interpreter.
• In Python, a comment starts with # (hash sign).
Everything following the # till the end of that line is treated as a comment and the interpreter
simply ignores it while executing the statement
Identity of an Object.
• Python treats every value or data item whether numeric, string, or any other type as an
object.
• Every object in Python is assigned a unique identity (ID) which remains the same for
the lifetime of that object. This ID is the memory address of the object.
• The function id() returns the identity of an object.
Ex:
n = 300
m=n
id(n)
60127840
id(m)
60127840
Debugging
• A programmer can make mistakes while writing a program, and hence, the program
may not execute or may generate wrong output.
• The process of identifying and removing such mistakes (bugs or errors) from a
program is called debugging.
• Errors occurring in programs can be categorized as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
Runtime Errors
• A runtime error causes abnormal termination of program while it is executing.
• Runtime error is when the statement is correct syntactically, but the interpreter cannot
execute it.
• Runtime errors do not appear until after the program starts running or executing.
#Runtime Errors Example
num1 = int(input(“num1=“))
num2 = int(input("num2 = "))
#if user inputs a string or a zero, it leads to runtime error
print(num1/num2)
Case 1: Give num2 as ‘string’
Case 2: Give num2 as 0
DATA TYPES
• Every value belongs to a specific data type in Python.
• Data type identifies the type of data values a variable can hold and the operations that
can be performed on that data.
The different data types available in Python are shown below.

There are four collection data types in the Python programming language:
◎ List is a collection which is ordered and changeable. Allows duplicate members.
◎ Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
◎ Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
Dictionary is a collection which is ordered** and changeable. No duplicate members.
Numbers
◎ Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.
Ex:
x=1 # int
y = 2.8 # float
z = 2+1j # complex
Boolean Values
◎ We can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the
Boolean answer:
◎ Ex:

◎ \
◎ Let us now try to execute few statements in interactive mode to determine the data
type of the variable using built-in function type().


Sequences
◎ Python sequence is an ordered collection of items, where each item is indexed by an
integer.
◎ The three types of sequence data types available in Python are Strings, Lists and
Tuples.
List
• Lists are used to store multiple items in a single variable.
• List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
Lists will allow duplicate values.

String
◎ String is a group of characters.
◎ These characters may be alphabets, digits or special characters including spaces.
◎ String values are enclosed either in single quotation marks (e.g.,‘Hello’) or in double
quotation marks (e.g., “Hello”).
◎ The quotes are not a part of the string, they are used to mark the beginning and end of
the string for the interpreter.
◎ However, Python does not have a character data type, a single character is simply a
string with a length of 1.
◎ Square brackets can be used to access elements of the string.
EX:
>>> str1 = 'Hello Friend‘
>>> str2 = "452"

Slicing the Strings


Modifying the Strings

String Concatenation
Tuple
◎ Tuple is a sequence of items separated by commas and items are enclosed in
parenthesis ( ).
◎ This is unlike list, where values are enclosed in brackets [ ].
◎ Once created, we cannot change the tuple.
Ex:
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
Set
◎ Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }.
◎ A set is similar to list, except that it cannot have duplicate entries.
◎ Once created, elements of a set cannot be changed.
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2) {1, 2, 3}

Dictionary
◎ Dictionary in Python holds data items in key-value pairs. Items in a dictionary are
enclosed in curly brackets { }.
◎ Dictionaries permit faster access to data.
◎ Every key is separated from its value using a colon (:) sign.
◎ The key : value pairs of a dictionary can be accessed using the key.
◎ The keys are usually strings and their values can be any data type.
In order to access any value in the dictionary, we have to specify its key in square brackets [].
Example
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
>>> print(dict1['Price(kg)'])
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
120
Operators
◎ An operator is used to perform specific mathematical or logical operation on values.
◎ The values that the operators work on are called operands.
For example, in the expression
10 + num
the value 10, and the variable num are operands and the + (plus) sign is an operator.
Arithmetic
Operators
Python supports arithmetic operators that are used to perform the four basic arithmetic
operations as well as modular division, floor division and exponentiation.
Relational
Operators
◎ Relational operator compares the values of the operands on its either side and
determines the relationship among them.
Assume the Python variables
num1 = 10
num2 = 0,
num3 = 10
str1 = "Good“
str2 = "Afternoon“
for the following examples:
Assignment operators
Assignment operator assigns or changes the value of the variable on its left.
Logical Operators
◎ There are three logical operators supported by Python.
◎ These operators (and, or, not) are to be written in lower case only.
◎ The logical operator evaluates to either True or False based on the logical operands on
either side.
◎ Every value is logically either True or False.
◎ By default, all values are True except None, False, 0 (zero), empty collections "", (),
[], {}, and few other special values.
So if we say num1 = 10, num2 = -20, then both num1 and num2 are logically True
Identity operators
◎ Identity operators are used to determine whether the value of a variable is of a certain
type or not.
Identity operators can also be used to determine whether two variables are referring to the
same object or not. There are two identity operators.
Membership operators
Membership operators are used to check if a value is a member of the given sequence or not.

You might also like