0% found this document useful (0 votes)
46 views87 pages

Python Programming with Raspberry Pi

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views87 pages

Python Programming with Raspberry Pi

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Introduction to Python Programming

OVERVIEW
Part-A:
IoT Physical Devices and Endpoints - Introduction
to Raspberry PI-Interfaces (serial, SPI, I2C)

Part-B:
Programming – Python program with Raspberry PI
with focus of interfacing external gadgets,
controlling output, reading input from pins.
Why Python?
 Python is a versatile language which is easy to script and easy
to read.
 It doesn’t support strict rules for syntax.
 Its installation comes with integrated development
environment for programming.
 It supports interfacing with wide ranging hardware platforms.
 With open-source nature, it forms a strong backbone to build
large applications.
Python Benefits
Python is a high level multi-purpose programming language
created by Guido Van Rossum.
Python is easy-to-use, read and maintain.
Python is an object-oriented, supports structured and
procedure oriented programming languages.
Python is an interactive language
Python is platform independent.
Python
IDE
 Python IDE is a free and open source software that is used
to write codes, integrate several modules and libraries.
 It is available for installation into PC with Windows, Linux
and Mac.
 Examples: Spyder, PyCharm, etc.
Starting with Python
 Simple printing statement at the python interpreter prompt,
>>> print “Hi, Welcome to
python!” Output: Hi, Welcome to
python!
 To indicate different blocks of code, it follows rigid
indentation. if True:
print “Correct"
else:
print “Error"
Data- types in
Python
There are 5 data types in
Python:
 Numbers
x, y, z = 10, 10.2
 String
x = "This is Python“
print x >>This is
print x[0] Python
>>T
Data- types in Python
(contd..)
 List
x = [10, 10.2,
'python']

 Tuple

 Dictionary
d = {1:‘item','k':2}
Controlling Statements
 if (cond.):  while (cond.):
statement 1 statement
1
statement 2
statement
elif (cond.): 2
statement 1  x = [1,2,3,4]
statement for i in x:
2 statement
else: 1
statement
statement
2
1
statement
2
Controlling Statements (contd..)
 Break  Continue
for s in for s in
"string": if "string": if
s == ‘n': s == ‘y':
brea continu
k print (s) e print (s)
print print “End”
“End”
Functions in Python
 Defining a function
 Without return value
def funct_name(arg1, arg2, arg3): # Defining the
statement 1 function
statement 2
 With return value
def funct_name(arg1, arg2, # Defining the
arg3): function
statement
1
statement # Returning the
2 return x value
Functions in Python
 Calling a function
def example (str):
print (str +
“!”)
example (“Hi”) # Calling the
function
Output:: Hi!
Functions in Python (contd..)
 Example showing function returning multiple
values def greater(x, y):
if x > y:
return x,
y else:
return
y, x

val = greater(10,
100) print(val)

Output:: (100,10)
Modules in Python
 Any segment of code fulfilling a particular task that can be
used commonly by everyone is termed as a module.

 Syntax:
import module_name #At the top of the
code
using #To access functions and values
module_name.var with ‘var’ in the
module
Modules in Python (contd..)
 Example:
import random

for i in range(1,10):
val =
[Link](1,10)
print (val)

Output:: varies with each execution


Modules in Python (contd..)
 We can also access only a particular function from a
module.

 Example:
from math import pi

print (pi)

Output::

3.14159
Example Code: to check number is prime or not
x = int (input("Enter a number:
")) def prime (num):
if num > 1:
for i in
range(2,num):
if (num %
i) == 0:
print (num,"is not a prime
number") print (i,“is a factor
of”,num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
prime (x)
IoT Platforms
The IoT concepts imply a creation of network of various
devices interacting with each other and with their
environment.

Interoperability and connectivity wouldn’t be possible


without hardware platforms that help developers solve
issues.
Types of IoT Platforms
• Arduino
• Raspberry Pi
• Intel Galileo
Arduino
Arduino
•created back in 2005 by the Arduino company and allows for
open source prototyping and flexible software development
and back-end deployment.

•Arduino has a built-in micro controller that operates on the


Arduino software.
Raspberry Pi
Raspberry Pi
•Raspberry Pi is a mono-board computing platform that's as
tiny as a credit card.

•Raspberry Pi uses Linux as its default operating system (OS).


It’s also fully Android compatible.
Intel Galileo
Intel Galileo
Intel Galileo is a highly integrated board that's just a little larger
than a credit card.

microprocessor on Galileo can be used for a wide variety of


functions; among them are robotic engineering and IoT
technologies.
Raspberry Pi – Part I

1
Introduction to Internet of Things
What is Raspberry
Pi?
• Single-board computer
• Low cost
• Easy to access
• Affordable credit-card sized computer
• Plugs into a computer monitor or TV
• Uses standard keyboard and mouse
• Can browse the internet and play HD video
• Can also interact with the outside world!
2
Introduction to Internet of Things
Raspberry Pi Foundation
Educational charity based in the UK
•The Foundation’s goal is to advance the education of
adults and children in the field of computers, computer
science, and related subjects.

[Link]
Specifications
Key features Raspberry pi 3 model B Raspberry pi Raspberry Pi zero
2 model B

RAM 1GB SDRAM 1GB SDRAM 512 MB SDRAM


CPU Quad cortex Quad ARM 11@ 1GHz
A53@1.2GHz cortex
A53@900
MHz
GPU 400 MHz video core IV 250 MHz video core 250 MHz video core IV
IV
Ethernet 10/100 10/100 None
Wireless 802.11/Bluetooth 4.0 None None
Video output HDMI/Composite HDMI/Composite HDMI/Composite
GPIO 40 40 40 3
Introduction to Internet of Things
Basic Architecture

RA
M

I/ CPU/ USB
O GPU HUB

ETHERNE US
T B

4
Introduction to Internet of Things
Raspberry
Pi

Introduction to Internet of Things 5


IoT Physical Devices and Endpoints
•UART = Universal
Asynchronous
Receiver /
Transmitter

•SPI = Serial
Peripheral Interface

•I2C = Inter-
Integrated Circuit
IoT Physical Devices and Endpoints
• All represent standard communications protocols that are
available through the Raspberry Pi GPIO (General Purpose
Input/Output) pins.
• Each has characteristics that may be better for a particular
project.
• Data communications is important for devices, like the
Raspberry Pi, to communicate and exchange "data" with
other devices.
• Examples of devices that the RPi may communicate include:
display devices, sensors, robotics, other computers, input
devices, industrial controls, scientific instruments, . . .
IoT Physical Devices and Endpoints
I2C, SPI and UART are all digital, serial communications
methods.
Table of RPi Serial Communications Methods via GPIO*
Name Description Function

Half duplex, serial data transmission used for


IC
2
Inter-Integrated Circuit short-distance between boards, modules and
peripherals. Uses 2 pins.
Full-duplex, serial data transmission used for
SPI Serial Peripheral Interface bus
short-distance between devices. Uses 4 pins.
Universal Asynchronous Asynchronous, serial data transmission
UART
Receiver-Transmitter between devices. Uses 2 pins.
IoT Physical Devices and Endpoints
Q: What is SPI interface Raspberry Pi?
A: The Serial Peripheral Interface (SPI) is a communication
protocol used to transfer data between micro-computers like
the Raspberry Pi and peripheral devices. These peripheral
devices may be either sensors or actuators.
• Serial Peripheral Interface (SPI) is a full-duplex serial
protocol for communicating with high-speed peripherals.
The SPI Master on Raspberry Pi™ hardware can drive
two SPI peripheral devices.
• The SPI Master has four pins: GPIO 11 (SPI0_SCLK)
outputs a serial clock signal to synchronize communications.
SPI
 SPI is a bidirectional, synchronous, serial communications interface - like
I2C. Also like I2C, it is used for relatively short distances.
 Unlike I2C, however, SPI operates at full duplex, meaning data can be
sent and received simultaneously.
 Additionally, it can operate at faster data transmission rates, with rates
upwards of 8 Mbits or more possible on the RPi.
 SPI can communicate with multiple devices through two ways.
 The first is by selecting each device with a Chip Select line.
 A separate Chip Select line is required for each device.
 This is the most common way RPi's currently use SPI.
 The second is through daisy chaining where each device is connected to
the other through its data out to the data in line of the next.
 The image at the top of this article illustrates the first method.
 There is no defined limit to the number of SPI devices that can be connected.
 However, practical limits exist due to constrains by the number of hardware
select lines available on the master in the first method, or the complexity of
passing data through devices in the second daisy chain method.
 The RPi has two Chip Select (CE0 & CE1) lines readily available. More can
be defined by configuring other GPIO pins and through software
programming.
Default RPi GPIO Pins used for SPI
Board Pin BCM Number Function
19 GPIO 10 MOSI - Master Out Slave In
21 GPIO 9 MISO - Master In Slave Out
23 GPIO 11 SCLK - Serial Clock
24 GPIO 8 CE0 - Chip Select 0
26 GPIO 7 CE1 - Chip Select 1
I2C [ I2C]
 I2C is bidirectional, synchronous, serial communications interface.
 It operates on two lines in a half-duplex mode.
 It was originally created by Philips Semiconductor which later became
NXP Semiconductors.
 A single master (the RPi) can communicate with one or more slave
devices.
 Each connected device is selected via a 7 bit address (10 or more bit
addressing is possible, but more complex).
 Originally limited to 100 kbits per second, it now supports faster
transmission rates.
 The Pi can support 100 kbits standard mode as well as 400 kbits "fast
mode", with some reports citing higher speeds depending on cable
length, board model and software processing.
 With its 7 bit addressing, I2C can support up to 127 devices (or nodes).
 The two lines are called SCL and SDA.
 SCL is the clock line for synchronizing transmission.
 SDA is the data line through which bits of data are sent or received.
 During transmission, the first byte includes the 7 bit address plus a read / write
bit. Subsequent bits represent the actual data.
 I2C connection to the RPi is made using GPIO board pins 3 for SDA and 5 for
SCL (BCM mode GPIO 2 and GPIO 3).
 The RPi GPIO operates at 3.3v so care must be taken to ensure connections
to slave devices are also 3.3v.
 A voltage level converter can be used if necessary to interface to other
devices, i.e. 5v Arduino to RPi 3.3v.
 I2C wiring distance is considered relatively short, typically from inches to a few
meters.
 Distance is affected by data speed, wire quality and external noise.
UART
 Origins of the UART go back decades making this the granddaddy of
communications hardware / protocols.
 Its simplicity and wide application has stood the test of time and is still a
popular method for data communications.
 UART is a hardware implementation that supports bidirectional,
asynchronous, serial communications.
 It requires two data lines - one for transmit and one for receive.
 The transmit line of one device is connected to the receive line of the second
device, and vice versa for transmission in both directions.
 A UART can only connect between two devices.
 It can operate between devices in:
 1) Simplex - data transmission in one direction only;
 2) Half Duplex - data transmission in either direction, but not simultaneously;
 3) Full Duplex - data transmission in both directions simultaneously.
UART
NOTE:
 RPi has two UARTs.
 A fully functional UART and a second one called a "mini" UART with less
capability. Prior to RPi 3, the full UART was available on GPIO pins 8 and 10.
However, to support Bluetooth on the RPi 3, the full UART was moved from the
GPIO to the Bluetooth chip and the mini UART was made available on GPIO pins
8 and 10.
 It is possible to redirect the full UART to the GPIO, but requires configuration
changes.
 For more detail about this topic, see Raspberry Pi's UART documentation.
 Either UART uses GPIO pin 8 (BCM GPIO 14) for transmit and pin 10 (BCM
GPIO 15) for receive.
 UART data transmission speed is referred to as BAUD Rate and is set to 115,200
by default (BAUD rate is based on symbol transmission rate, but is similar to bit
rate).
 Rates approaching 1 Mbps have been successful with the RPi.
Summary
•UART - simple;
•not high speed;
•no clock needed;
•limited to one device connected to the Pi.

•I2C - faster than UART, but not as fast as SPI;


•easier to chain many devices;
•RPi drives the clock so no sync issues.

•SPI - fastest of the three; Pi drives the clock so no sync issues;


practical limit to number of devices on the Pi.
Some Hardware Components shown above are mention below:
[Link] (High-Definition Multimedia Interface): It is used for
transmitting uncompressed video or digital audio data to the Computer
Monitor, Digital TV, etc. Generally, this HDMI port helps to connect
Raspberry Pi to the Digital television.
[Link] Camera Interface: CSI (Camera Serial Interface) interface provides
a connection in between Broadcom Processor and Pi camera. This interface
provides electrical connections between two devices.
[Link] Display Interface: DSI (Display Serial Interface) Display Interface
is used for connecting LCD to the Raspberry Pi using 15-pin ribbon cable.
DSI provides fast High-resolution display interface specifically used for
sending video data directly from GPU to the LCD display.
[Link] Video and Audio Output: The composite Video and Audio
output port carries video along with audio signal to the Audio/Video
systems.
[Link] LED: It is a RED colored LED which is used for Power indication.
This LED will turn ON when Power is connected to the Raspberry Pi. It is
connected to 5V directly and will start blinking whenever the supply
Start up raspberry pi

Introduction to Internet of Things


Raspberry Pi
GPIO
• Act as both digital output and digital
input.

• Output: turn a GPIO pin high or low.

• Input: detect a GPIO pin high or low.

Introduction to Internet of Things 7


Raspberry Pi pin configuration

Source: Raspberry Pi PCB Pin Overview, Wikimedia Commons Source: Raspberry Pi GPIO, Wikimedia Commons (Online)
(Online)

Introduction to Internet of Things 8


Basic Set up for Raspberry Pi
• HDMI cable.
• Monitor.
• Key board.
• Mouse.
• 5volt power adapter for raspberry
pi.
• LAN cable .
• Min- 2GB micro sd card

Introduction to Internet of Things9


Basic Set up for Raspberry Pi

Introduction to Internet of Things10


Operating System
Official Supported OS :
• Raspbian
• NOOBS
Some of the third party OS
: • UBUNTU mate
• Snappy Ubuntu core
• Windows 10 core
• Pinet
• Risc OS

Source: Downloads, Raspberry Pi Foundation


Introduction to Internet of Things
11
Raspberry Pi
Setup
Download Raspbian:
• Download latest Raspbian image from raspberry pi official
site: [Link]

• Unzip the file and end up with an .img file.

12
Introduction to Internet of Things
Raspberry Pi OS Setup
Write Raspbian in SD card :
• Install “Win32 Disk Imager” software in windows
machine .
• Run Win32 Disk Imager
• Plug SD card into your PC
• Select the “Device”
• Browse the “Image File”(Raspbian image)
• Write

Introduction to Internet of Things13


Raspberry Pi OS Setup

Introduction to Internet of Things14


Basic Initial Configuration

Enable SSH
Step1 : Open command prompt and type sudo raspi-config and press
enter.

Step2: Navigate to SSH in the Advance option.

Step3: Enable SSH

Introduction to Internet of Things15


Basic Initial Configuration

Introduction to Internet of Things16


Basic Initial Configuration contd.

Expand file
system :
Step 1: Open command prompt and type sudo raspi-config and press
enter.

Step 2: Navigate to Expand Filesystem

Step 3: Press enter to expand it.

Introduction to Internet of Things17


Basic Initial Configuration contd.

Introduction to Internet of Things18


Raspberry Pi Getting Started
1. When booting up for the first time you will get the blue “raspi-­config”
‐ screen.
Here you can configure your Pi with language and keyboard settings for your
desired region of the world. Use tab and arrow keys to browse.

2. Once configured to your liking go to <Finish> and hit enter. This will take you to
the command prompt where you will need to type in “startx” to start up the
GUI (Graphical User Interface)
Basic Pi Commands
rasp-­‐config ssh
Change your pi configuration settings. Connect your pi to other computers.

startx sudo
Start the GUI (Graphical User Interface) Run commands as super user.

ifconfig shutdown
This will shutdown your pi.
Get the details of your Ethernet or wireless network
adapter. nano
This is your text editor for changing or adding files.
rpi-­‐update Save, edit, create.
Updates your Raspberry Pi firmware.
cat
lsusb Read out files at the command line.
Shows a list of usb devices.
passwd
apt-­‐get update & apt-­‐get upgrade Change your user password.
Update or upgrade your pi soft ware
Programming

Default installed :
• Python
• C
• C++
• Java
• Scratch
• Ruby
Note : Any language that will compile for ARMv6 can be used with raspberry
pi.
Source: Programming languages for Raspberry Pi, eProseed, Lonneke Dikmans, August 07, 2015

19
Introduction to Internet of Things
Popular Applications
• Media streamer
• Home automation
• Controlling BOT
• VPN
• Light weight web server for IoT
• Tablet computer
• Teaching programming concepts
• Designing DIY projects

20
Introduction to Internet of Things
Introduction to Raspberry Pi – Part
II
Blinking
LED
 Requirement:
 Raspberry pi
 LED
 100 ohm
resistor
 Bread board
 Jumper cables
Blinking LED (contd..)
Installing GPIO library:
 Open terminal
 Enter the command “sudo apt-get install python-dev” to install
python development
 Enter the command “sudo apt-get install [Link]” to install
GPIO library.
Blinking LED (contd..)

Connection:
 Connect the negative terminal
of the LED to the ground pin of
Pi
 Connect the positive terminal
of the LED to the output pin of
Pi
Blinking LED (contd..)
Basic python coding:

 Open terminal enter the command


sudo nano [Link]
 This will open the nano editor where you can write your
code
 Ctrl+O : Writes the code to the file
 Ctrl+X : Exits the editor
Blinking LED (contd..)
Code:
import [Link] as GPIO #GPIO
import time library
[Link]([Link] # Set the type of board for pin
RD) [Link](11, numbering # Set GPIO pin 11as output
[Link]) pin
for i in range (0,5): # Turn on GPIO pin
[Link](11,True) 11
[Link](1)
[Link](11,False)
[Link](2)
[Link](11,True)
[Link]()
Blinking LED (contd..)
Blinking LED (contd..)
The LED blinks in a loop with
delay of 1 and 2 seconds.
Implementation of IoT with Raspberry Pi: Part 1
IO
T
Internet Of
Things
Creating an interactive environment
 Network of devices connected
together
Senso
r
 Electronic element
 Converts physical quantity into electrical
signals
 Can be analog or digital
Actuator
 Mechanical/Electro-mechanical device
 Converts energy into motion
 Mainly used to provide controlled motion to
other components
System Overview
 Sensor and actuator interfaced with Raspberry Pi
 Read data from the sensor
 Control the actuator according to the reading from
the sensor
 Connect the actuator to a device
System Overview (contd..)
Requirements
 DHT Sensor
 4.7K ohm
resistor
 Relay
 Jumper wires
 Raspberry Pi
 Mini fan
DHT
Sensor
 Digital Humidity and
Temperature Sensor
(DHT)
 PIN 1, 2, 3, 4 (from left
to right)
 PIN 1- 3.3V-5V
Power supply
 PIN 2- Data
 PIN 3- Null
 PIN 4- Ground
Rela
y
 Mechanical/electromechanical
switch
 3 output terminals (left to
right)
 NO (normal open):
 Common
 NC (normal close)
Temperature Dependent Auto Cooling System
Sensor interface with Raspberry Pi

 Connect pin 1 of DHT sensor to


the 3.3V pin of Raspberry Pi
 Connect pin 2 of DHT sensor to
any input pins of Raspberry Pi,
here we have used pin 11
 Connect pin 4 of DHT sensor to
the ground pin of the Raspberry
Pi
Temperature Dependent Auto Cooling System
(contd..)
Relay interface with Raspberry Pi

 Connect the VCC pin of relay to the


5V supply pin of Raspberry Pi
 Connect the GND (ground) pin of
relay to the ground pin of Raspberry
Pi
 Connect the input/signal pin of Relay
to the assigned output pin of
Raspberry Pi (Here we have used pin
7)
Temperature Dependent Auto Cooling System
(contd..)
Adafruit provides a library to work with the DHT22
sensor
 Install the library in your Pi-
 Get the clone from GIT
git clone [Link]
 Go to folder Adafruit_Python_DHT
cd Adafruit_Python_DHT
 Install the library
sudo
Source: ADAFRUIT DHTXX python
SENSORS, [Link] install
Lady Ada, 2012-07-
29
Program: DHT22 with Pi
import [Link] as
GPIO from time import
sleep import #importing the Adafruit
Adafruit_DHT library
[Link]([Link])
[Link](False)
sensor = Adafruit_DHT.AM2302 # create an instance of the sensor
print (‘Getting data from the type
sensor’)
#humidity and temperature are 2 variables that store the values received from the
sensor

humidity, temperature = Adafruit_DHT.read_retry(sensor,17)


print ('Temp={0:0.1f}*C humidity={1:0.1f}%'.format(temperature, humidity))
Program: DHT22 interfaced with Raspberry
Pi
Code
Output
Connection: Relay
 Connect the relay pins with the Raspberry Pi as mentioned in previous
slides

 Set the GPIO pin connected with the relay’s input pin as output in the
sketch
[Link](13,[Link])

 Set the relay pin high when the temperature is greater than 30
if temperature > 30:
[Link](13,0) # Relay is active
low print(‘Relay is on')
sleep(5)
[Link](13,1) # Relay is turned
off after delay of 5 seconds
Connection: Relay (contd..)
Connection: Fan
 Connect the Li-po battery in series with the fan
 NO terminal of the relay -> positive terminal of
the Fan.
 Common terminal of the relay -> Positive terminal
of the battery
 Negative terminal of the battery -> Negative terminal
of the fan.
 Run the existing code. The fan should operate when the
surrounding temperature is greater than the threshold
value in the sketch
Connection: Fan (contd..)
Resul
t The fan is switched on
whenever the temperature is
above the threshold value set
in the code.

Notice the relay indicator


turned on.

You might also like