UNIT 4 IOT

Building IoT with Arduino & Raspberry Pi

5.1 Building IoT with Arduino

Internet of Things (IoT)

IoT is a scenario where objects, animals, or people are provided with unique identifiers and the ability to automatically transfer data over a network without requiring human-to-human or human-to-computer interaction.

Arduino Board
  • An Arduino is a microcontroller-based kit used in communication and controlling devices.
  • The Arduino UNO is the most popular board.
  • It's suitable for starting with electronics and coding.
  • Arduino boards have common components:
    • Program memory: Stores the code (flash memory).
    • Data memory: Stores the data.
  • Arduino Uno has:
    • 14 digital input/output pins (6 can be used as PWM outputs).
    • 6 analog inputs.
    • 16 MHz crystal oscillator.
    • USB connection.
    • Power jack.
    • ICSP header.
    • Reset button.
Arduino Board Components
  1. Power USB: Powered via USB cable.
  2. Power (Barrel Jack): Powered directly from AC mains.
  3. Voltage Regulator: Controls voltage to the board and stabilizes DC voltages.
  4. Crystal Oscillator: Helps Arduino deal with time issues. The frequency is 16 MHz ( 16,000,00016,000,000 Hertz).
  5. Arduino Reset: Resets the board, starting the program from the beginning.
    • Using the reset button.
    • Connecting an external reset button to the RESET pin.
  6. Pins (3.3V, 5V, GND, Vin):
    • 3.3V: Supplies 3.3 output volts.
    • 5V: Supplies 5 output volts.
    • GND (Ground): Ground pins for the circuit.
    • Vin: Powers the board from an external power source.
  7. Analog Pins: Arduino UNO has six analog input pins (A0-A5). These pins read signals from analog sensors (e.g., humidity, temperature) and convert them into digital values.
  8. Main Microcontroller: The brain of the board, usually from ATMEL. The specific IC varies by board. Refer to the data sheet for details.
  9. ICSP Pin: AVR tiny programming header for Arduino, consisting of MOSI, MISO, SCK, RESET, VCC, and GND. Often referred to as SPI (Serial Peripheral Interface).
  10. Power LED Indicator: Lights up when the board is powered correctly. If it doesn't light up, there's a connection problem.
  11. TX and RX LEDs: TX (transmit) and RX (receive) LEDs indicate serial communication.
    • TX flashes when sending data.
    • RX flashes when receiving data.
  12. Digital I/O: 14 digital I/O pins, with 6 providing PWM (Pulse Width Modulation) output. Configurable as input (read logic values 0 or 1) or output (drive LEDs, relays, etc.).
  13. AREF: Analog Reference. Used to set an external reference voltage (0-5V) for the analog input pins.
Programming an Arduino
  • Programs can be directly loaded without a hardware programmer due to the 0.5KB bootloader.
  • Steps:
    1. Download the Arduino software.
    2. Write the code.
  • Arduino tool window:
    • Toolbar: Buttons for verify, upload, new, open, save, serial monitor.
    • Text editor: Write code.
    • Message area: Displays feedback and errors.
    • Text console: Displays output.
    • Menus: File, Edit, Tools.
  • Arduino programs are called sketches.
  • A basic sketch consists of:
    1. Declaration of Variables
    2. Initialization: Written in the setup() function.
    3. Control code: Written in the loop() function.
  • Sketches are saved with the .ino extension.
  • Choose the proper board and serial port numbers in the tools menu, then upload the code.
Basic Arduino Functions
  • digitalRead(pin): Reads the digital value at the given pin.
  • digitalWrite(pin, value): Writes the digital value to the given pin.
  • pinMode(pin, mode): Sets the pin to input or output mode.
  • analogRead(pin): Reads and returns the analog value.
  • analogWrite(pin, value): Writes the analog value to that pin.
  • serial.begin(baud rate): Sets the beginning of serial communication by setting the bit rate.
Designing Your Own Arduino

Components needed: breadboard, LED, power jack, IC socket, microcontroller, resistors, regulators, capacitors.

Steps:

  1. Mount the IC socket and power jack on the board.
  2. Add the 5V and 3.3V regulator circuits using regulators and capacitors.
  3. Add proper power connections to the microcontroller pins.
  4. Connect the reset pin of the IC socket to a 10K resistor.
  5. Connect the crystal oscillators to pins 9 and 10.
  6. Connect the LED to the appropriate pin.
  7. Mount the female headers and connect them to the respective pins.
  8. Mount the row of 6 male headers for uploading programs.
  9. Upload the program on the microcontroller and place it back on the user kit.
Advantages of Arduino Board
  1. Inexpensive.
  2. Open-source hardware allows users to develop their own kits using existing ones as a reference.
  3. The Arduino software is compatible with various operating systems (Windows, Linux, Macintosh).
  4. Open-source software enables experienced developers to merge Arduino code with existing programming language libraries, extending and modifying it.
  5. Easy to use for beginners.
  6. Can develop standalone projects or projects with direct communication with computer software.
  7. Easy provision for connecting with the computer's CPU using serial communication over USB.
Interfaces
  • UART (Universal Asynchronous Receiver/Transmitter): A serial interface with one module. RX and TX pins are connected to a USB-to-UART converter and pins 0 and 1 in the digital header.
  • SPI (Serial Peripheral Interface): Another serial interface with one SPI module.
  • TWI (Two Wire Interface) / I2C: An interface with two wires: serial data (SDA) and serial clock (SCL). Accessible from the last two pins in the digital header or pins 4 and 5 in the analog header.

5.2 Building IoT with Raspberry Pi

Internet of Things (IoT)

Same definition as above: a scenario where objects, animals, or people are provided with unique identifiers and the ability to automatically transfer data over a network without requiring human-to-human or human-to-computer interaction.

Raspberry Pi
  • A cheap, credit-card-sized computer running Linux with GPIO (general purpose input/output) pins for controlling electronic components.
  • Introduced in 2006, designed for educational use and intended for Python.
  • Plugs into a TV or monitor and uses a standard keyboard and mouse.
  • User-friendly for all age groups.
  • Can perform desktop computer tasks like word processing, browsing the internet, playing games, and playing high-definition videos.
  • Features a Broadcom system on a chip (SoC) with a graphics processing unit (GPU - Video Core IV) and an ARM-compatible CPU.
  • CPU speed ranges from 700 MHz to 1.2 GHz (Pi 3), with on-board memory ranging from 256 MB to 1 GB RAM.
  • Operating system is stored on SD cards (MicroSDHC or SDHC).
  • Most boards have 1-4 USB slots, composite video output, HDMI, and a 3.5 mm phone jack for audio. Some models have WiFi and Bluetooth.
  • Later models:
    • Processor speed ranges from 700 MHz to 1.4 GHz for the Pi 3 Model B+ or 1.5 GHz for the Pi 4
    • Up to 4 GB RAM on the Pi 4
  • Lower-level output is provided by GPIO pins, which support common protocols like I²C.
  • B-models have an 8P8C Ethernet port, and the Pi 3 and Pi Zero W have on-board Wi-Fi and Bluetooth.
Components and Peripherals
  • Voltages: Two 5V pins and two 3V3 pins, as well as ground pins (0V). Remaining pins are general-purpose 3V3 pins.
  • A GPIO pin designated as an output can be set to high (3V3) or low (0V). A GPIO pin designated as an input can be read as high (3V3) or low (0V).
  • Processor & RAM: ARM11 processor, 700MHz processor, and 512MB SDRAM. The CPU is the brain, carrying out instructions through logical and mathematical operations.
  • Ethernet: Main gateway for communicating with additional devices. Used to plug into a home router for internet access.
  • USB Ports: Has 2 USB ports, providing current up to 100mA. External powered USB hub required for devices drawing more than 100mA.
  • Ethernet Port: Standard RJ45 port. Connect Ethernet cable or USB wifi adapter for internet connectivity.
  • HDMI Output: Supports audio and video output. Connect to monitor using HDMI cable.
  • Composite Video Output: Comes with an RCA jack that supports both PAL and NTSC video output.
  • Audio Output: Has 3.5mm audio output jack. Used for providing audio output to old television along with RCA jack for video.
  • GPIO Pins: Used to connect other electronic components (e.g., temperature sensor).
  • Display Serial Interface (DSI): Connect an LCD panel.
  • Camera Serial Interface (CSI): Connect a camera module.
  • SD Card slot: Plug in an SD card loaded with Linux.
  • Power Input: Micro USB connector for power input.
  • Memory: Model A has 256MB SDRAM, and model B has 512MB. RAM memory is smaller than normal PCs.
  • Status LEDs:
    • ACT: SD card Access
    • PWR: 3.3V power is present
    • FDX: Full duplex LAN Connected
    • LNK: Link/Network Activity
    • 100: 100 Mbit LAN connected
Raspberry Pi Interfaces
  • Supports SPI, serial, and I2C interfaces for data transfer.
  • Serial: Receive (Rx) and Transmit (Tx) pins for communication with serial peripherals.
  • SPI (Serial Peripheral Interface): Synchronous serial data protocol for communicating with peripheral devices.
    • MISO (Master In Slave Out): Master line for sending data to peripherals.
    • MOSI (Master Out Slave In): Slave Line for sending data to the master.
    • SCK (Serial Clock): Clock generated by master to synchronize data transmission.
    • CE0 (Chip Enable 0): To enable or disable devices.
    • CE1 (Chip Enable 1): To enable or disable devices.
  • I2C: Synchronous data transfer with two pins: SDA (data line) and SCL (Clock Line).
Features of Raspberry Pi
  1. Suitable for system processing is huge(Weather Station, Cloud server, gaming console etc.).
  2. Raspberry Pi 3 has wireless LAN and Bluetooth for WIFI HOTSPOT.
  3. Dedicated port for connecting touch LCD display
  4. Dedicated camera port
  5. PWM outputs for application use.
  6. It supports HD steaming Applications
    • Hobby projects.
    • Low cost PC/tablet/laptop
    • IoT applications
    • Media center
    • Robotics
    • Industrial/Home automation
    • Server/cloud server
    • Print server
    • Security monitoring
    • Web camera
    • Gaming
    • Wireless access point

5.3 IoT Systems - Logical Design using Python

5.3.1 Introduction
Characteristics of Python
  • Multi-paradigm programming language: Supports object-oriented and structured programming.
  • Interpreted Language: Doesn't require explicit compilation; executes code statement by statement.
  • Interactive Language: Allows users to submit commands and interact with the interpreter directly.
  • Easy to Learn and Use: Developer-friendly and high-level.
  • Object and procedure oriented: Supports both procedure and object oriented programming.
  • Extendable: Allows integration of low-level modules written in C/C++.
  • Scalable: Provides a manageable structure for large programs.
  • Portable: Programs are executed directly from source code and copy from one machine to other without worry about portability. Python interpreter converts source code to an intermediate form called byte code and then translate this into the native language of your specific system and then runs it.
  • Broad Library support: Supports Windows, Linux, Mac. Packages are available for machine learning, image processing, network programming, cryptography, etc.
  • Databases: Interfaces to all major commercial databases.
  • GUI Programming: Supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.
Uses / Applications of Python
  • Web applications on a server.
  • Workflows alongside software.
  • Connect to database systems; read and modify files.
  • Handle big data and perform complex mathematics.
  • Rapid prototyping or production-ready software development.
5.3.2 Installing Python
  • Highly portable, works on Windows, Linux, Mac, etc.
  • Windows: Download Python 2.7 from http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi
  • Linux (Ubuntu):
    #download python wget http://python.org/ftp/python/2.7.5/python-2.7.5.tgz tar –xvf Python-2.7.5.tgz cd Python-2.7.5 #Install Python ./configure make sudo make install
5.3.3 Python data types & data structures
5.3.3.1 Numbers
  • Used to store numeric values.
  • Immutable.
  • Int: Whole number, positive or negative, without decimals, of unlimited length.
    python x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z))
    Output:
    <class 'int'> <class 'int'> <class 'int'>
  • Float: Number with one or more decimals.
    python x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z))
    Output:
    <class 'float'> <class 'float'> <class 'float'>
  • Complex: Written with a "j" as the imaginary part.
    python x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) print("Real Part is :", x.real) print("Imaginary Part is :",x.imag)
    Output:
    <class 'complex'> <class 'complex'> <class 'complex'> Real Part is : 3.0 Imaginary Part is : 5.0
5.3.3.2 Strings
  • String literals are surrounded by single or double quotation marks.
  • 'hello' is the same as "hello".
  • One or more characters.
  • A string with zero characters is an empty string.
    python a="Hello" b="World!" print(type(a)) print(b) #String concatination print(a+b) #String Length print(len(a)) #Convert to upper and lower print(a.lower()) print(a.upper()) # Substring 4th character not included print(a[1]) print(a[1:4]) print(a[1:]) #strip() method removes any whitespace or characters print(b.strip("Wor")) print(b.strip("!")) #The replace() method replaces a string with another string print(a.replace("H","J")) #Format Method age = 36 txt = "My age is {}" print(txt.format(age))
    Output:
    <class 'str'> World! HelloWorld! 5 hello HELLO e ell ello ld! World Jello My age is 36
5.3.3.3 List
  • Compound data type to group values.
  • List items need not have the same data type.
  • Ordered and changeable; allows duplicate members.
  • To add an item to the end of the list, use the append() method
  • To add an item at the specified index, use the insert() method
  • The remove() method removes the specified item
  • Separated by commas and enclosed within square brackets.
  • You can access the items of a list by referring to its index number.
    ```python
    li=['apple','orange','mango','banana']
    print(type(li))

print all item in a list

print(li)

print items in a list based on index start is 0

print(li[0])
print(li[1:])

append() add an item in end of the list

li.append("Berry")
print(li)

remove() delete an item

li.remove("apple")
print(li)

Insert an item based on index

li.insert(2,"apple")
print(li)

Crate mixed list

mi=['Hai',2,5.999]
print(mi)
print(li+mi)
```

5.3.3.4 Tuple
  • Ordered and unchangeable collection; allows duplicate members.
  • Written with round brackets.
  • You can access tuple items by referring to the index number, inside square brackets.
  • Once a tuple is created, you cannot change its values. Tuples are unchangeable.
  • To determine how many items a tuple has, use the len() method
  • You cannot add items to a tuple.
  • Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely
    ```python
    tu=('apple','orange','mango','banana')
    print(type(tu))

print all item in a list

print(tu)

print items in a tuple based on index start at 0

print(tu[0])
print(tu[1:3])
print(tu[:2])

len() length of the tuple

print(len(tu))

create Mixed tuple

mi=('Hai',2,5.999)
print(tu+mi)
Output:

('apple', 'orange', 'mango', 'banana')
apple
('orange', 'mango')
('apple', 'orange')
4
('apple', 'orange', 'mango', 'banana', 'Hai', 2, 5.999)
```

5.3.3.5 Dictionaries
  • Unordered, changeable, and indexed collection.
  • Written with curly brackets, having keys and values.
  • You can access the items of a dictionary by referring to its key name,
  • To determine how many items (key-value pairs) a dictionary has, use the len() method.
    ```python
    dict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
    }
    print(type(dict))
    print(dict)

len() to determine length of dictionary

print(len(dict))

print model value

x = dict["model"]
print(x)

print all items

print(dict.items())

get keys

print(dict.keys())

get values

print(dict.values())

add new key & value

dict["color"] = "red"
print(dict)

last item deleted

dict.popitem()
print(dict)
del dict["model"]
print(dict)
Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
3
Mustang
dictitems([('brand', 'Ford'), ('model', 'Mustang'), ('year': 1964)]) dictkeys(['brand', 'model', 'year'])
dict_values(['Ford', 'Mustang', 1964])
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'brand': 'Ford', 'year': 1964}
```

5.3.3.6 Type Conversion
  • Convert from one type to another with the int(), float(), and complex() methods:
    ```python
    x = 1 # int
    y = 2.8 # float
    z = 1j # complex

convert from int to float:

a = float(x)

convert from float to int:

b = int(y)

convert from int to complex:

c = complex(x)

print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))s="aeiou"
print(list(s))
Output:
1.0
2
(1+0j)



['a', 'e', 'i', 'o', 'u']
```

5.3.4 Control Flow
5.3.4.1 Control Statements
if
  • An "if statement" is written by using the if keyword.
  • The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison.
  • Syntax
    if expression: statement(s)
  • Example
    python a=int(input('Enter a Number')) if a>0: print("It is Positive Number")
    Output:
    Enter a Number78 It is Positive Number
elif and else
  • The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
  • An else statement can be combined with an if statement.
  • An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
  • Syntax
    if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)
  • Example
    python a=int(input('Enter a Number')) if a>0: print(a," is Positive Number") elif a<0: print(a," is Negative Number") else: print(a," is Zero")
  • Output
    Enter a Number-67 -67 is Negative Number
Nested if
  • In a nested if construct, you can have an if…elif…else construct inside another if…elif…else construct.
  • Syntax
    if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) elif expression4: statement(s) else: statement(s) else: statement(s)
  • Example
    python var = 100 if var < 200: if var == 150: print ("Which is 150") elif var == 100: print ("Which is 100") elif var == 50: print ("Which is 50") elif var < 50: print ("Value is less than 50") else: print ("Values more than 200..")
For
  • The for loop in Python is used to iterate the statements or a part of the program several times.
  • It is frequently used to traverse the data structures like list, tuple, or dictionary.
  • Syntax
    for iterating_var in sequence: statement(s)
  • Example
    ```python

print natural numbers

i=1
n=int(input("Enter the number up to print the natural numbers : "))
for i in range(0,n):
print(i,end=' ')
#print String
s="Hello World"
print("\n")
for c in s:
print(c,end=' ')

Multiplication Table

i=1;
print("\n")
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i));
```

  • Output
    ```
    Enter the number up to print the natural numbers : 2
    0 1

H e l l o W o r l d

Enter a number:4
4 X 1 = 4
4 X 2 = 8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
4 X 9 = 36
4 X 10 = 40
```

while
  • With the while loop we can execute a set of statements as long as a condition is true.
  • Syntax
    while expression: statement(s)
  • statement(s) may be a single statement or a block of statements.
  • The condition may be any expression, and true is any non-zero value.
  • The loop iterates while the condition is true.
  • Program
    ```python

print 1 to 5

i = 1
while i < 6:
print(i)
i=i+1
#print even number until 10
j=1
print("Even Numbers are")
while j<=10:
if j%2==0:
print(j)
j=j+1
```

  • Output:
    1 2 3 4 5 Even Numbers are 2 4 6 8 10
range() Function
  • To loop through a set of code a specified number of times, we can use the range() function
  • The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
  • The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):
    python for x in range(6): print(x) for x in range(2, 6): print(x) for x in range(2, 30, 3): print(x)
    Output
    0 1 2 3 4 5 2 3 4 5 2 5 8 11 14 17 20 23 26 29
Break & Continue
  • With the break statement we can stop the loop before it has looped through all the items.
  • With the continue statement we can stop the current iteration of the loop, and continue with the next.
  • Program
    python a=[1,2,3,4] for x in a: if x==2: continue print(x) for x in a: if x==3: break print(x)
Pass
  • It is null operation
  • It is used when a statement is required syntactically but not execute any code.
5.3.5 Python Functions
  • A function is a block of code which only runs when it is called.
  • You can pass data, known as parameters, into a function.
  • A function can return data as a result.
Creating a Function
  • In Python a function is defined using the def keyword.
  • Function begins with def keyword followed by function name and parenthesis.
  • Function parameters are enclosed within the parenthesis.
Calling a Function
  • To call a function, use the function name followed by parenthesis:
  • Information can be passed to functions as parameter.
  • Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
  • Program
    ```python

function1

def fun1():
print("Hello from a function")

fun1()

function2

def fun2(fname):
print("Hello "+ fname)

fun2("Cathy")
fun2("Raju")

function3

def fun3(country = "Norway"):
print("I am from " + country)

fun3("Sweden")
fun3("India")
fun3()
fun3("Brazil")

function4

def fun4(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]
fun4(fruits)

function5

def fun5(x):
return 5 * x

print(fun5(3))
print(fun5(5))
print(fun5(9))
```

5.3.6 Modules
  • Consider a module to be the same as a code library.
  • A file containing a set of functions you want to include in your application.
  • It allows organizing of the program code into different modules which improves the code readability and management.
  • A module is a python file that defines some functionality in the form of function or classes.
  • To create a module: save the code you want in a file with the file extension .py:
    • filename: module1.py
      python def f1(name): print("Hello, " + name)
  • Use a Module:
    python import module1 module1.f1("World!")
    Output:
    Hello, World!
  • Example:
    1. module3.py
      ```python
      def add(x,y):
      print("Addition is :",x+y)

def sub(x,y):
return(x-y)
2. module4.py python
import module3
module3.add(10,5)
print("Subtraction is :",module3.sub(100,50))
```

5.3.7 Packages
  • Python package is hierarchical file structure that consists of modules and sub packages.
  • Packages are organized into root directory with sub directories
  • Each directory contains a special file named __init__.py which tells python to treat directory as packages.
  • Packages are a way of structuring many packages and modules which helps in a well- organized hierarchy of data set, making the directories and modules easy to access.
  • To tell Python that a particular directory is a package,