Iot Module 2 Material
Iot Module 2 Material
Iot Module 2 Material
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
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)
• 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
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.
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"
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.