[go: up one dir, main page]

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

Unit III Iot

The document provides an overview of Arduino and Raspberry Pi as tools for creating electronic projects, detailing their features, components, and programming interfaces. It explains the Arduino platform, including its microcontroller, various boards, and the Arduino IDE for coding and uploading sketches. Additionally, it outlines the steps for downloading and installing the Arduino software, as well as the basics of building IoT applications with Arduino.

Uploaded by

lellala4710
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 views52 pages

Unit III Iot

The document provides an overview of Arduino and Raspberry Pi as tools for creating electronic projects, detailing their features, components, and programming interfaces. It explains the Arduino platform, including its microcontroller, various boards, and the Arduino IDE for coding and uploading sketches. Additionally, it outlines the steps for downloading and installing the Arduino software, as well as the basics of building IoT applications with Arduino.

Uploaded by

lellala4710
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/ 52

lOMoARcPSD|57264712

3 UNIT IOT - jgmjmbc

Computer Science Engineering (Ram Krishna Dharmarth Foundation University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Yara Varshini (varshiniyara785@gmail.com)
lOMoARcPSD|57264712

UNIT III
IOT PHYSICAL DEVICES AND ENDPOINTS
Introduction to Arduino and Raspberry Pi- Installation, Interfaces (serial, SPI, I2C), Programming –
Python program with Raspberry PI with focus on interfacing external gadgets, controlling output, and
reading input from pins.
INTRODUCTION TO ARDUINO AND RASPBERRY PI

Arduino and Raspberry Pi are used as a tool for creating electronic projects.

ARDUINO

Arduino is a software as well as hardware platform that helps in making electronic projects. It is
an open source platform and has a variety of controllers and microprocessors. There are various types of
Arduino boards used for various purposes.

The Arduino is a single circuit board, which consists of different interfaces or parts. The board consists of
the set of digital and analog pins that are used to connect various devices and components, which we want
to use for the functioning of the electronic devices.

Most of the Arduino consists of 14 digital I/O pins.

The analog pins in Arduino are mostly useful for fine-grained control. The pins in the Arduino board are
arranged in a specific pattern. The other devices on the Arduino board are USB port, small components
(voltage regulator or oscillator), microcontroller, power connector, etc.

The features of Arduino are listed below:

❖ Arduino programming is a simplified version of C++, which makes the learning process easy.

❖ The Arduino IDE is used to control the functions of boards. It further sends the set of
specifications to the microcontroller.
❖ Arduino does not need an extra board or piece to load new code.

❖ Arduino can read analog and digital input signals.

❖ The hardware and software platform is easy to use and implement.

MICROCONTROLLER

The most essential part of the Arduino is the Microcontroller, which is shown below:

Microcontroller is small and low power computer. Most of the microcontrollers have a RAM (Random
Access Memory), CPU (Central Processing Unit), and memory storage like other computer systems.

It has very small memory of 2KB (two Kilobytes). Due to less memory, some microcontrollers are
capable of running only one program at a time.

It is a single chip that includes memory, Input/Output (I/O) peripherals, and a processor.

The GPIO (General Purpose Input Output) pins present on the chip help us to control other electronics or
circuitry from the program.
Downloaded by Yara Varshini (varshiniyara785@gmail.com)
lOMoARcPSD|57264712

ARDUINO KITS
We can easily start with our electronics projects using the complete kit. It also helps us to create hand-on
and engaging projects.

Some of the popular Arduino kits are listed below:

❖ Arduino Starter kit


❖ Robot Linking UNO kit for learning
❖ Arduino UNO 3 Ultimate starter kit
❖ UNO Super starter kit
❖ Mega 2560 Starter Kit
Arduino IDE

The IDE makes the traditional projects even easier and simpler. The USB cable is used to load the
program or sketch on the specific Arduino board.

The IDE application is suitable for Windows, Mac OS X, and Linux


❖ It supports the programming language C and C++
❖ We need to connect the Genuine and Arduino board with the IDE to upload the sketch written
in the Arduino IDE software.
ARDUINO BOARDS
There are variety of Arduino board used for different purposes. The board varies in I/O pins, size, etc.
The various components present on the Arduino boards are Microcontroller, Digital Input/Output pins,
USB Interface and Connector, Analog Pins, Reset Button, Power button, LED's, Crystal Oscillator, and
Voltage Regulator. Some components may differ depending on the type of board.
Let's discuss some of the popular Arduino boards.
❖ Arduino UNO
❖ Arduino Nano
❖ Arduino Mega
❖ Arduino Due
❖ Arduino Bluetooth

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

ARDUINO DOWNLOAD
The Arduino software (IDE) is open-source software. We are required to write the code and upload the
code to the board to perform some task.
The Arduino IDE software can be used with any type of Arduino boards. The software is available for
various operating system such as, Windows, Linux, and Mac OS X.
The steps to download the Arduino software are listed below:
1. Go to the official website of Arduino (https://www.arduino.cc/) > Click on SOFTWARE < click on
DOWNLOADS, as shown below:

2. A page will appear, as shown below:

3. Scroll the screen a little, as shown below:

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

4. Click on the 'Windows Installer' as we are operating with the Windows. We can select the
Linux or Mac OS X, accordingly.

5. A contribution window will appear. We can contribute according to our choice and click on
the 'CONTRIBUTE &DOWNLOAD' option. Otherwise, click on the 'JUST DOWNLOAD'
option, as shown below:

6. The downloading process will start. The downloading file will look like the below image:

7. Wait for few seconds for the downloading process to complete.


8. Open the downloaded file.

9. Grant permission to the Arduino Software on your computer.

10. Accept the license by clicking on 'I Agree' button, as shown below:

11. Click on the 'Next' button. It is shown below:

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

12. The window specifying the location of the installed folder will appear. Click on the 'Install'
button. It is shown below:

If you want to change the location, click on the 'Browse' button.

13. The installing process of Arduino will start, as shown below:

Wait for the installation process to complete.

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

14. Now, we have to accept the security for the installation. We are required to accept the
security Installation three times.

Click on the 'Install' button. The image is shown below:


15. Again, click on the 'Install' button. It is shown below:

16. Again, click on the 'Install' button. It is shown below:

17. The installation process is now completed. The window will now appear as:

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

18. Click on the 'Close' button at the bottom.

The Arduino IDE software will appear on your desktop, as shown below:

19. Now, open the Arduino software.

20. The Arduino IDE environment is written in the programming language named as Java. So,
we need to allow access to the Java Platform.

As soon we open the Arduino software, a license window will appear, as shown below:

Accept the license by clicking on the 'Allow access' button.

21. The Arduino window will appear as:

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

Visibility of the connected Hardware port


We can view the port of the attached hardware Arduino IDE to our computer. The steps are listed below:
Go to the File Manager and right-click on the This PC option, as shown below:

Click on the Manage


First, we need to connect the Arduino board to our computer. A window will appear, as shown below:

Click on the Device Manager


Under the PORT option, we can see the ports of the connected hardware. Arduino IDE
The Arduino IDE is an open-source software, which is used to write and upload code to the Arduino
boards. The IDE application is suitable for different operating systems such as Windows, Mac OS X, and
Linux. It supports the programming languages C and C++. Here, IDE stands for Integrated Development
Environment.
The program or code written in the Arduino IDE is often called as sketching. We need to connect the
Genuino and Arduino board with the IDE to upload the sketch written in the Arduino IDE software. The
sketch is saved with the extension '.ino.'

The Arduino IDE will appear as:

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

Let's discuss each section of the Arduino IDE display in detail. Toolbar Button
The icons displayed on the toolbar are New, Open, Save, Upload, and Verify.

It is shown below:

Upload
The Upload button compiles and runs our code written on the screen. It further uploads the code to the
connected board. Before uploading the sketch, we need to make sure that the correct board and ports are
selected.

We also need a USB connection to connect the board and the computer. Once all the above measures are
done, click on the Upload button present on the toolbar.

The latest Arduino boards can be reset automatically before beginning with Upload. In the older boards,
we need to press the Reset button present on it. As soon as the uploading is done successfully, we can
notice the blink of the Tx and Rx LED.
Downloaded by Yara Varshini (varshiniyara785@gmail.com)
lOMoARcPSD|57264712

If the uploading is failed, it will display the message in the error window.

We do not require any additional hardware to upload our sketch using the Arduino Bootloader. A
Bootloader is defined as a small program, which is loaded in the microcontroller present on the board.
The LED will blink on PIN 13.

Open
The Open button is used to open the already created file. The selected file will be opened in the current
window.
Save
The save button is used to save the current sketch or code.

New
It is used to create a new sketch or opens a new window.

Verify
The Verify button is used to check the compilation error of the sketch or the written code.

Serial Monitor
The serial monitor button is present on the right corner of the toolbar. It opens the serial monitor.

It deis shown below:


When we connect the serial monitor, the board will reset on the operating system Windows, Linux, and
Mac OS X. If we want to process the control characters in our sketch, we need to use an external terminal
program. The terminal program should be connected to the COM port, which will be assigned when we
connect the board to the computer.

Menu Bar File


When we click on the File button on the Menu bar, a drop-down list will appear. It is
shown below:

Close

The Close button closes the window from which the button is clicked.

Save

The save button is used to save the current sketch. It also saves the changes made to the current sketch. If
we have not specified the name of the file, it will open the 'Save As...' window.
Downloaded by Yara Varshini (varshiniyara785@gmail.com)
lOMoARcPSD|57264712

Save As...

We can save the sketch with a different name using the 'Save As...' button. We can also change the name
accordingly.
Page Setup

It allows setting the page margins, orientation, and size for printing. The 'Page Setup' window will appear
as:

5.1 Building IOT with Arduino

Internet of Things

The Internet of Things (IoT) is a scenario in which objects, animals or people are provided
with single identifiers and the capability to automatically transfer and the capability to
automatically transfer data more to a network without requiring human-to-human or human-
to-computer communication.

Arduino Board:
 An Arduino is actually a microcontroller based kit.
 It is basically used in communications and in controlling or operating many devices.
 Arduino UNO board is the most popular board in the Arduino board family.
 In addition, it is the best board to get started with electronics and coding.
 Some boards look a bit different from the one given below, but most Arduino’s
have majority of these components in common.
 It consists of two memories- Program memory and the data memory.
 The code is stored in the flash program memory, whereas the data is stored in the data
memory.
 Arduino Uno consists of 14 digital input/output pins (of which 6 can be used as PWM
outputs), 6 analog inputs, a 16 MHz crystal oscillator, a USB connection, a power
jack, an ICSP header, and a reset button
16.ARE
17.Arduino 15.Digital I/O
F
Reset
14.TX and RX
LEDs

1.Power
USB 4.Crystal Oscillator

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

3.Powe
r LED
1 indicator

12.ICSP pin
3.Voltage
Regulator
11.Main
microcontroll
2.Power er
(Barrel Jack)
5.Arduino
Reset
6,7,8,9.Pins 10.Analog pins
(3.3,
5, GND, Vin)

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

1. Power USB
Arduino board can be powered by using the USB cable from your computer. All you
need to do is connect the USB cable to the USB connection (1).
2. Power (Barrel Jack)
Arduino boards can be powered directly from the AC mains power supply by connecting
it to the Barrel Jack (2).
3. Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino board
and stabilize the DC voltages used by the processor and other elements.
4. Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino
calculate time? The answer is, by using the crystal oscillator. The number printed on top of the
Arduino crystal is 16.000H9H. It tells us that the frequency is 16,000,000 Hertz or 16 MHz.
5,17.Arduino Reset
You can reset your Arduino board, i.e., start your program from the beginning. You can
reset the UNO board in two ways. First, by using the reset button (17) on the board. Second, you
can connect an external reset button to the Arduino pin labelled RESET (5).
6,7,8,9.Pins (3.3, 5, GND, Vin)
• 3.3V (6) − Supply 3.3 output volt
• 5V (7) − Supply 5 output volt
• Most of the components used with Arduino board works fine with 3.3 volt and 5 volt.
• GND (8)(Ground) − There are several GND pins on the Arduino, any of which can be
used to ground your circuit.
• Vin (9) − This pin also can be used to power the Arduino board from an external power
source, like AC mains power supply.

13

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

10. Analog pins

The Arduino UNO board has six analog input pins A0 through A5. These pins can read
the signal from an analog sensor like the humidity sensor or temperature sensor and
convert it into a digital value that can be read by the microprocessor.

11. Main microcontroller

Each Arduino board has its own microcontroller (11). You can assume it as the brain of
your board. The main IC (integrated circuit) on the Arduino is slightly different from board to
board. The microcontrollers are usually of the ATMEL Company. You must know what IC your
board has before loading up a new program from the Arduino IDE. This information is available
on the top of the IC. For more details about the IC construction and functions, you can refer to
the data sheet.

12. ICSP pin

Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of
MOSI, MISO, SCK, RESET, VCC, and GND. It is often referred to as an SPI (Serial
Peripheral Interface), which could be considered as an "expansion" of the output.
Actually, you are slaving the output device to the master of the SPI bus.

13. Power LED indicator

This LED should light up when you plug your Arduino into a power source to indicate
that your board is powered up correctly. If this light does not turn on, then there is
something wrong with the connection.

14. TX and RX LEDs

On your board, you will find two labels: TX (transmit) and RX (receive). They appear in
two places on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate the
pins responsible for serial communication. Second, the TX and RX led (13). The TX led
flashes with different speed while sending the serial data. The speed of flashing depends
on the baud rate used by the board. RX flashes during the receiving process.

15. Digital I/O

• The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse
Width Modulation) output. These pins can be configured to work as input digital pins to
read logic values (0 or 1) or as digital output pins to drive different modules like LEDs,
relays, etc. The pins labeled “~” can be used to generate PWM.

16. AREF

14

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

• AREF stands for Analog Reference. It is sometimes, used to set an external reference
voltage (between 0 and 5 Volts) as the upper limit for the analog input pins.

Program an Arduino
 The most important advantage with Arduino is the programs can be directly loaded to the
device without requiring any hardware programmer to burn the program.
 This is done because of the presence of the 0.5KB of Bootloader which allows the
program to be burned into the circuit.
 All we have to do is to download the Arduino software and writing the code.
 The Arduino tool window consists of the toolbar with the buttons like verify, upload,
new, open, save, serial monitor.
 It also consists of a text editor to write the code, a message area which displays the
feedback like showing the errors, the text console which displays the output and a series
of menus like the File, Edit, Tools menu.

Steps to program an Arduino


 Programs written in Arduino are known as sketches. A basic sketch consists of 3 parts

1. Declaration of Variables
2. Initialization: It is written in the setup () function.
3. Control code: It is written in the loop () function.

 The sketch is saved with .ino extension. Any operations like verifying, opening a sketch,
saving a sketch can be done using the buttons on the toolbar or using the tool menu.

 The sketch should be stored in the sketchbook directory.

 Chose the proper board from the tools menu and the serial port numbers.

 Click on the upload button or chose upload from the tools menu. Thus the code is
uploaded by the bootloader onto the microcontroller.

Basic Adruino functions are:

 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 value.

 analogWrite(pin, value): Writes the value to that pin.

15

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 serial.begin(baud rate): Sets the beginning of serial communication by setting the bit
rate.

Design your own Arduino


 The following components are needed to design Arduino Board- A breadboard, a led, a
power jack, a IC socket, a microcontroller, few resistors, 2 regulators, 2 capacitors.

 The IC socket and the power jack are mounted on the board.

 Add the 5v and 3.3v regulator circuits using the combinations of regulators
and capacitors.

 Add proper power connections to the microcontroller pins.

 Connect the reset pin of the IC socket to a 10K resistor.

 Connect the crystal oscillators to pins 9 and 10

 Connect the led to the appropriate pin.

 Mount the female headers onto the board and connect them to the respective
pins on the chip.

 Mount the row of 6 male headers, which can be used as an alternative to


upload programs.

 Upload the program on the Microcontroller of the readymade Adruino and


then pry it off and place back on the user kit.

Advantages of Arduino Board

1. It is inexpensive

2. It comes with an open source hardware feature which enables users to develop their own
kit using already available one as a reference source.

3. The Arduino software is compatible with all types of operating systems like Windows,
Linux, and Macintosh etc.

4. It also comes with open source software feature which enables experienced software
developers to use the Arduino code to merge with the existing programming language
libraries and can be extended and modified.

5. It is easy to use for beginners.

16

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

6. We can develop an Arduino based project which can be completely stand alone or
projects which involve direct communication with the software loaded in the computer.

7. It comes with an easy provision of connecting with the CPU of the computer using serial
communication over USB as it contains built in power and reset circuitry.

Interfaces

UART Peripheral:
 A UART (Universal Asynchronous Receiver/Transmitter) is a serial interface.
 It has only one UART module.
 The pins (RX, TX) of the UART are connected to a USB-to-UART converter circuit and
also connected to pin0 and pin1 in the digital header.

SPI Peripheral:
 The SPI (Serial Peripheral Interface) is another serial interface. It has only one SPI
module.
TWI:
 The I2C or Two Wire Interface is an interface consisting of only two wires, serial data,
and a serial clock: SDA, SCL.
 You can reach these pins from the last two pins in the digital header or pin4 and pin5 in
the analog header.

5.2 Building IOT with RASPERRY


PI Internet of Things

The Internet of Things (IoT) is a scenario in which objects, animals or people are provided with
single identifiers and the capability to automatically transfer and the capability to automatically
transfer data more to a network without requiring human-to-human or human-to-computer
communication.

Raspberry Pi

 The Raspberry Pi is a very cheap computer that runs Linux, but it also provides a set of
GPIO (general purpose input/output) pins that allow you to control electronic
components for physical computing and explore the Internet of Things (IoT).
 Raspberry Pi was basically introduced in 2006.
 It is particularly designed for educational use and intended for Python.
 A Raspberry Pi is of small size i.e., of a credit card sized single board computer, which is
developed in the United Kingdom(U.K) by a foundation called Raspberry Pi.

17

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 There have been three generations of Raspberry Pis: Pi 1, Pi 2, and Pi 3


 The first generation of Raspberry (Pi 1) was released in the year 2012, that has two types
of models namely model A and model B.
 Raspberry Pi can be plugged into a TV, computer monitor, and it uses a standard
keyboard and mouse.
 It is user friendly as can be handled by all the age groups.
 It does everything you would expect a desktop computer to do like word-processing,
browsing the internet spreadsheets, playing games to playing high definition videos.
 All models feature on a broadcom system on a chip (SOC), which includes chip graphics
processing unit GPU(a Video Core IV), an ARM compatible and CPU.
 The CPU speed ranges from 700 MHz to 1.2 GHz for the Pi 3 and on board memory
range from 256 MB to 1 GB RAM.
 An operating system is stored in the secured digital SD cards and program memory in
either the MicroSDHC or SDHC sizes.
 Most boards have one to four USB slots, composite video output, HDMI and a 3.5 mm
phone jack for audio. Some models have WiFi and Bluetooth.
 Several generations of Raspberry Pis have been released.
 All models feature a Broadcom system on a chip (SoC) with an integrated ARM-
compatible central processing unit (CPU) and on-chip graphics processing unit (GPU).
 Processor speed ranges from 700 MHz to 1.4 GHz for the Pi 3 Model B+ or 1.5 GHz for
the Pi 4; on-board memory ranges from 256 MB to 1 GB with up to 4 GB available on
the Pi 4 random-access memory (RAM).
 Secure Digital (SD) cards in MicroSDHC form factor (SDHC on early models) are used
to store the operating system and program memory.
 The boards have one to five USB ports. For video output, HDMI and composite video are
supported, with a standard 3.5 mm tip-ring-sleeve jack for audio output.
 Lower-level output is provided by a number of GPIO pins, which support common
protocols like I²C. The B-models have an 8P8C Ethernet port and the Pi 3 and Pi Zero W
have on-board Wi-Fi and Bluetooth.

18

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

Components and Peripherals

 Voltages: Two 5V pins and two 3V3 pins are present on the board, as well as a number
of ground pins (0V). The remaining pins are all general purpose 3V3 pins
 A GPIO pin designated as an output pin can be set to high (3V3) or low (0V). A GPIO
pin designated as an input pin can be read as high (3V3) or low (0V).
 Processor & RAM: Raspberry based on ARM11 processor. Latest version supports
700MHz processor and 512MB SDRAM. The Central processing unit is the brain of the
raspberry pi board and that is responsible for carrying out the instructions of the computer
through logical and mathematical operations.
 Ethernet: The Ethernet port of the raspberry pi is the main gateway for communicating
with additional devices. The raspberry pi Ethernet port is used to plug your home router
to access the internet.

19

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 USB Ports: It has 2 USB ports. USB port provide current upto 100mA. For connecting
devices that draw current more than 100mA, an external USB powered hub is required.
 Ethernet Port: It has standard RJ45 Ethernet port. Connect Ethernet cable or USB wifi
adapter to provide internet connectivity.
 HDMI Output: It supports both audio and video output. Connect raspberry Pi to monitor
using HDMI cable.
 Composite video Output: Raspberry comes with a composite video output with an RCA
jack that supports both PAL and NTSC video output.
 Audio Output: It has 3.5mm audio output jack. This audio jack is used for providing
audio output to old television along with RCA jack for video.
 GPIO Pins: It has a number of general purpose input/output pins. These pins are used to
connect other electronic components. For example, you can connect it to the temperature
sensor to transmit digital data.
 Display Serial Interface (DSI): DSI interface are used to connect an LCD panel to
Raspberry PI.
 Cameral Serial Interface(CSI): CSI interface are used to connect a camera module to
Raspberry PI.
 SD Card slot: Raspberry does not have built in OS and storage. Plug in an SD card
loaded with Linux to SD card slot.
 Power Input: Raspberry has a micro USP connector for power input.
 Memory: The raspberry pi model A board is designed with 256MB of SDRAM and
model B is designed with 51MB.Raspberry pi is a small size PC compare with other PCs.
The normal PCs RAM memory is available in gigabytes. But in raspberry pi board, the
RAM memory is available more than 256MB or 512MB
 Status LEDs: Raspberry has 5 status LEDs.

Status LED Function


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:

 It supports SPI, serial and I2C interfaces for data transfer.


 Serial : Serial Interface on Raspberry has receive(Rx) and Transmit(Tx) pins for
communication with serial peripherals.
 SPI: Serial Peripheral Interface (SPI) is a synchronous serial data protocol used for
communicating with one or more peripheral devices. In an SPI connection, there is one
master device and one or more peripheral devices. There are 5 pins Raspberry for SPI
interface.
o MISO(Master In Slave Out): Master line for sending data to the peripherals.
o MOSI(Master Out Slave In): Slave Line for sending data to the master.
o SCK(Serial Clock): Clock generated by master to synchronize data transmission.
o CE0(Chip Enable 0): To enable or disable devices.

20

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

o CE1(Chip Enable 1): To enable or disable devices.


 I2C: I2C Interface pins are used to connect hardware modules. I2C interface allows
synchronous data transfer with two pins: SDA(data line) and SCL (Clock Line)

Features of Raspberry PPI

1. Where the system processing is huge. They can process high end programs for applications
like Weather Station, Cloud server, gaming console etc. With 1.2GHz clock speed and 1 GB
RAM RASPBERRY PI can perform all those advanced functions.

2. RASPBERRY PI 3 has wireless LAN and Bluetooth facility by which you can setup WIFI
HOTSPOT for internet connectivity.

3. RASPBERRY PI had dedicated port for connecting touch LCD display which is a feature that
completely omits the need of monitor.

4. RASPBERRY PI also has dedicated camera port so one can connect camera without any
hassle to the PI board.

5. RASPBERRY PI also has 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: Python supports more than one programming
paradigms including object oriented programming and structured programming.

21

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 Interpreted Language: It is an interpreted language and does not require an explicit


compilation step. Python interpreter executes the program source code directly and
statement by statement interpreted.
 Interactive Language: user can submit commands at the python prompt and interact
with the interpreter directly.
 Easy to Learn and Use: Python is easy to learn and use. It is developer-friendly and
high level programming language.
 Object and procedure oriented: python supports both procedure and object oriented
programming. It allows programs to be written around procedures or functions that allow
reuse of code.
 Extendable: It is an extendable language and allows integration of low level modules
written in languages such as C/C++.
 Scalable: It provides a manageable structure for large programs.
 Portable: Python 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: It supports and works on different platforms such as windows,
Linux, Mac etc. Large number of packages are available for various applications such as
machine learning, image processing, network programming, cryptography etc.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python 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


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.
5.3.2 Installing Python
It is highly portable language that works on different platforms such as windows, Linux, Mac
etc.
Windows
Python 2.7 can be downloaded from http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi
Linux
Install python in Ubuntu Linux like:
#download python
wget http://python.org/ftp/python/2.7.5/python-2.7.5.tgz

22

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

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
Number data type are used to store numeric values.
Numbers are immutable data types that is changing the value of a number data type
Int
 Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
 Example
x= 1
y= 35656222554887711
z= -3255522
print(type(x))
print(type(y))
print(type(z))
 Output
<class 'int'>
<class 'int'>
<class 'int'>
Float
 Float, or "floating point number" is a number, positive or negative, containing one or
more decimals.
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
 Complex numbers are written with a "j" as the imaginary part:

23

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

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 in python are surrounded by either single quotation marks, or double
quotation marks.
 'hello' is the same as "hello".
 One or more character is called string
 A string with zero character is called empty string.
 Example:
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

24

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

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
 It is a Compound data type used to group together other values.
 List items need not have the same data type.
 List is a collection which is ordered and changeable. It 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
 List items are separated by commas and enclosed with in square brackets.
 To access the list items by referring to the index number.
 To change the value of a specific item, refer to the index number
 Program
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")

25

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

print(li)
#Crate mixed list
mi=['Hai',2,5.999]
print(mi)
print(li+mi)
5.3.3.4 Tuple
 Tuple is a collection which is ordered and unchangeable. It allows duplicate members.
 In Python tuples are 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
 Example:
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
<class 'tuple'>
('apple', 'orange', 'mango', 'banana')
apple
('orange', 'mango')
('apple', 'orange')
4
('apple', 'orange', 'mango', 'banana', 'Hai', 2, 5.999)
5.3.3.5 Dictionaries
 A dictionary is a collection which is unordered, changeable and indexed.
 In Python dictionaries are written with curly brackets, and they have 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.
 Example
dict = {
"brand": "Ford",

26

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

"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
<class 'dict'>
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
3
Mustang
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
dict_keys(['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:
 Example
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:

27

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

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)
<class 'float'>
<class 'int'>
<class 'complex'>
['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
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.

28

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 Example
 syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

 Example:
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
var = 100
if var < 200:

29

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

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
#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
01

30

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

HelloWorld
Enter a number:4
4X1=4
4X2=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
#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

31

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

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):
 Program
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
012345
2345
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
a=[1,2,3,4]
for x in a:
if x==2:
continue
print(x)

for x in a:
if x==3:
break

32

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

print(x)
 Output
13412
Pass

 It is null operation
 It is used when a statement is required syntactically but not execute any code.
 Program
for x in a:
if x==1:
pass
else:
print(x)
 Output
234
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
#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")
33

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

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))
 Output
Hello from a function
Hello Cathy
Hello Raju
I am from Sweden
I am from India
I am from Norway
I am from Brazil
apple
banana
cherry
15
25
45
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.
 Create a Module : To create a module just save the code you want in a file with the file
extension .py:
 filename: module1.py
def f1(name):

34

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

print("Hello, " + name)


 Use a Module: Now we can use the module we just created, by using
the import statement:
import module1
module1.f1("World!")
 Output : Hello, World!
 Example :
1. module3.py
def add(x,y):
print("Addition is :",x+y)
def sub(x,y):
return(x-y)

2. module4.py
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, we create a file named init .py
inside it and then it is considered as a package.
 We may create other modules and sub-packages within it.
 This init .py file can be left blank or can be coded with the initialization code for the
package.
 To create a package in Python, we need to follow these three simple steps:
 First, we create a directory and give it a package name, preferably related to its operation.
 Then we put the classes and the required functions in it.
 Finally we create an init .py file inside the directory, to let Python know that the
directory is a package.

35

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 We can import modules from packages using the dot (.) operator.
 Example: import Game.Level.start

5.3.8 File Handling


 Python using reading and writing files to files using file object.
 open(filename,mode) is used to get a file object.
 Mode can be read(r), write(w),append(a),read and write(r+ or w+), read-binary(rb),
writebinary(wb),create(x).
 close() used to close the file.
 read() method for reading the content of the file
 You can return one line by using the readline() method:
 Example1:
#read whole file
f = open("ruff.txt", "r")
print(f.read())
f.close()
#read line by line
f = open("ruff.txt", "r")
print(f.readline())
print(f.readline())
f.close()
#use loop to print
f = open("ruff.txt", "r")
for x in f:
print(x)
 Output:

36

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

Java Programming
C Programming
C++ Programming
Python Programming
PHP Programming
HTML Programming
Java Programming
C Programming
Java Programming
C Programming
C++ Programming
Python Programming
PHP Programming
HTML Programming
 Example2:
#create new file
f = open("myfile.txt", "x")
#write data into file
f = open("myfile.txt", "a")
f.write("Now the file has more content!")
f.close()
#read data from file
f = open("myfile.txt", "r")
print(f.read())
f.close()
 Output:
Now the file has more content!

5.3.9 Date and Time Operations


 Calendar module in Python has the calendar class that allows the calculations for various
task based on date, month, and year.
 The TextCalendar and HTMLCalendar class in Python allows you to edit the calendar
and use as per your requirement.
 import a module named datetime to work with dates as date objects.
 Return the year and name of weekday:
 The method is called strftime(), and takes one parameter, format, to specify the format of
the returned string.
Directive Description Example

%a Weekday, short version Wed

37

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

%A Weekday, full version Wednesday

%w Weekday as a number 0-6, 0 3


is Sunday

%d Day of month 01-31 31

%b Month name, short version Dec

%B Month name, full version December

%m Month as a number 01-12 12

%y Year, short version, without 18


century

%Y Year, full version 2018

5.3.10 Classes
 Python is an object oriented programming language.
 Almost everything in Python is an object, with its properties and methods.
 A Class is like an object constructor, or a "blueprint" for creating objects.
 To create a class, use the keyword class:
 Python supports classes, class variables, class methods, inheritance, function overloading,
operator overloading.
 Class: A class is simply a representation of a type of object and user defined prototype
for an object that is composed of three things like name, attribute and
operations/methods.
 Object: Object is an instance of the data structure defined by a class.
 Inheritance: It is the process of forming a new class from an existing class or base class.
 Function overloading: It is a form of polymorphism that allows a function to have
different meanings, depending on its context.
 Operator overloading: It is a form of polymorphism that allows assignment of more
than one function to a particular operator.
 Function overriding: It allows a child class to provide a specific implementation of a
function that is already provided by the base class. Child class implementation of the
overridden function has the same name, parameters and return type as the function in the
base class.
 All classes have a function called init (), which is always executed when the class is
being initiated.
 Use the init () function to assign values to object properties, or other operations that
are necessary to do when the object is being created:
 The init () function is called automatically every time the class is being used to create
a new object.

38

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 The self parameter is a reference to the current instance of the class, and is used
to access variables that belongs to the class.
 It does not have to be named self , you can call it whatever you like, but it has to be
the first parameter of any function in the class:
 You can delete properties on objects by using the del keyword.
 Example1:
class Person:
def init (self, name, age):
print("Constructor Called..")
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
print(p1.name)
print(p1.age)
p1.myfunc()
 Output1:
Constructor Called..
John
36
Hello my name is John
 Example2:
#Inhertitance Program
class Person:
def init (self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

class Student(Person):
def init (self, fname, lname, year):
super(). init (fname, lname)
self.graduationyear = year

def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)

x = Student("Mike", "Olsen", 2019)


x.welcome()
 Output2:
Welcome Mike Olsen to the class of 2019

39

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

5.3.11 Python Packages for IoT

5.3.11.1 JSON

 Javascript Object Notation(JSON) is an easy to read and write data-interchange format.


 It is an alternate to XML.
 It is built on 2 structure: collection of name-value pairs(dictionary) and ordered list of
values(list)
 JSON format is used for serializing and transmitting structured data over a network
connection.
 If you have a JSON string, you can parse it by using the json.loads() method.
 If you have a Python object, you can convert it into a JSON string by using
the json.dumps() method
 Example:
import json

# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:


print(y["age"])

# a Python object (dict)


x={
"name": "John",
"age": 30,
"city": "New York"
}

# convert into JSON:


y = json.dumps(x)

# the result is a JSON string:


print(y)
 Output:
30
{"name": "John", "age": 30, "city": "New York"}
5.3.11.2 XML

 Extensible Markup Language(XML) is a data format for structured document


interchange.

40

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 It was designed to store and transport small to medium amounts of data and is widely
used for sharing structured information.
 In order to parse an XML document using minidom, we must first import it from
the xml.dom module. This module uses the parse function to create a DOM object from
our XML file.
 getElementByTagName() to find a specific tag.
 Example:
from xml.dom import minidom

# parse an xml file by name


mydoc = minidom.parse('items.xml')

items = mydoc.getElementsByTagName('item')

# all item attributes


print('\nAll attributes:')
for elem in items:
print(elem.attributes['name'].value)

# one specific item's data


print('\nItem #2 data:')
print(items[1].firstChild.data)

# all items data print('\


nAll item data:') for
elem in items:
print(elem.firstChild.data)
 Output:
All attributes:
item1
item2

Item #2 data:
Mango

All item data:


Apple
Mango
5.11.3.3 HTTPlib and URLlib

 HTTPLib2 and URLLib2 are python libraries used in network/internet programming.


 HTTPLib2 is an HTTP client library and URLLib2 is a library for fetching URLs.
 import urllib.requests. From there, we assign the opening of the url to a variable, where
we can finally use a .read() command to read the data.

41

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 Example1:
import http.client
conn = http.client.HTTPSConnection("www.python.org")
conn.request("GET", "/")
r1 = conn.getresponse()
print(r1.status, r1.reason)
data1 = r1.read() # This will return entire content.
# The following example demonstrates reading data in chunks.
conn.request("GET", "/")
r1 = conn.getresponse()
while not r1.closed:
print(r1.read(200))
 Example2:
import urllib.request
x = urllib.request.urlopen('https://www.gmail.com/')
print(x.read())
5.11.3.4 SMTPLib

 Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending an e-mail
and routing e-mail between mail servers.
 Python provides smtplib module, which defines an SMTP client session object that can
be used to send mails to any Internet machine with an SMTP or ESMTP.
 Syntax:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
 Here is the detail of the parameters −
 host − This is the host running your SMTP server. You can specifiy IP address of the
host or a domain name like tutorialspoint.com. This is an optional argument.
 port − If you are providing host argument, then you need to specify a port, where SMTP
server is listening. Usually this port would be 25.
 local_hostname − If your SMTP server is running on your local machine, then you can
specify just localhost the option.
 An SMTP object has an instance method called sendmail, which is typically used to do
the work of mailing a message. It takes three parameters −
 The sender − A string with the address of the sender.
 The receivers − A list of strings, one for each recipient.
 The message − A message as a string formatted as specified in the various RFCs.
 Example:
 import smtplib

 sender = 'from@fromdomain.com' receivers =
 ['to@todomain.com']

 message = """From: From Person <from@fromdomain.com>

42

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

 To: To Person <to@todomain.com>


 Subject: SMTP e-mail test

 This is a test e-mail message. """

 try:
 smtpObj = smtplib.SMTP('localhost')
 smtpObj.sendmail(sender, receivers, message)
 print "Successfully sent email"
except SMTPException:

print "Error: unable to send email"

43

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

44

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

45

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

46

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

47

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

48

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

49

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

50

Downloaded by Yara Varshini (varshiniyara785@gmail.com)


lOMoARcPSD|57264712

III Unit

51

Downloaded by Yara Varshini (varshiniyara785@gmail.com)

You might also like