0% found this document useful (0 votes)
7 views26 pages

SEC134 Lab Manual

The document outlines a series of hands-on Python labs using Raspberry Pi, covering topics such as calculating factorials and prime numbers, interfacing with LEDs and push buttons, and setting up a web server to display sensor data. It includes detailed algorithms, Python code examples, and setup procedures for various hardware components. The labs aim to provide practical experience in programming and hardware interfacing with Raspberry Pi.

Uploaded by

thotanarasanna
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)
7 views26 pages

SEC134 Lab Manual

The document outlines a series of hands-on Python labs using Raspberry Pi, covering topics such as calculating factorials and prime numbers, interfacing with LEDs and push buttons, and setting up a web server to display sensor data. It includes detailed algorithms, Python code examples, and setup procedures for various hardware components. The labs aim to provide practical experience in programming and hardware interfacing with Raspberry Pi.

Uploaded by

thotanarasanna
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/ 26

SEC134 Hands-On Python with Raspberry Pi - Lab

Ex. No 1 Introduction to Python & Raspberry Pi Setup

31.03.22

Problem: Write the python programs for finding the factorial and the prime numbers within the
given range. And do the headless raspberrypi setup with ethernet connection.

Aim: Write the Python program for the following

1. Find the factorial of a number with recursion.


2. Find the prime numbers in the given range.
(and)

Do the headless Raspberry pi board setup with Ethernet connection and VNC viewer

Hardware/Software Tools required: Python 3.x ( Anaconda Distribution)

Raspberry Pi 4 with power adapter

Algorithm for Programs:

Factorial:

Main Function()

1. Input the number


2. Call the factorial function with the given number as argument and store the return value.
3. Print the return value

Factorial_Function( n)

1. If n is equal to 1 or n is equal to 0, return 1


2. Else call Factorial Function with n-1 as argument.

Finding the prime numbers within he given range:

// Student need to write the algorithm

Program to find the factorial:

# Python 3 program to find

# factorial of given number

def factorial(n):

# single line to find factorial

return 1 if (n==1 or n==0) else n * factorial(n - 1);

# Driver Code
SEC134 Hands-On Python with Raspberry Pi - Lab

num = 5;

print("Factorial of",num,"is",

factorial(num))

Input/Output

Input: None

Output: 120

Program to find the prime numbers within given range:

def prime(x, y):

prime_list = []

for i in range(x, y):

if i == 0 or i == 1:

continue

else:

for j in range(2, int(i/2)+1):

if i % j == 0:

break

else:

prime_list.append(i)

return prime_list

# Driver program

starting_range = 2

ending_range = 7

lst = prime(starting_range, ending_range)

if len(lst) == 0:

print("There are no prime numbers in this range")

else:

print("The prime numbers in this range are: ", lst)

Input/Output
SEC134 Hands-On Python with Raspberry Pi - Lab

Input: None

Output: [2 3 5]

Setting up Headless Raspberry Pi Setup using Ethernet Connection

Procedure:

Raspberry pi 4 OS setup:

Here we are setting up a headless raspberry pi with Ethernet and VNC viewer.

1. Download the imager from the link


https://downloads.raspberrypi.org/imager/imager_latest.exe
2. Insert the SD card reader with the SD Card where the raspberry pi os has to be installed.
3. Open the imager app.

4. Choose Raspberry pi os (32-bit) as shown above.


5. Choose the SD card drive for the storage
6. Then click on write.
7. Open the SD Card and put the file “ssh” into the sd card.
8. And put one more file “wpa_supplicant.conf” for wireless internet connectivity
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
ssid="NETWORK_NAME"
psk="NETWORK_KEY"
}
9. Login to raspberry pi using ssh. Use putty and use the host name raspberrypi.local (default
port:22)
SEC134 Hands-On Python with Raspberry Pi - Lab

10. Login with the username “pi” and the password “raspberry”
11. Install the VNC server in raspberry pi with the following commands
sudo apt update
sudo apt install realvnc-vnc-server realvnc-vnc-viewer

12. Enable vnc server by giving the following commands


sudo raspi-config
Select the Interface options → VNC Enable/disable → Enable
13. Type ifconfig in the ssh window in putty. Get the Ethernet IP. Usually, if you connect the PC
directly, you will get the IP like 169.254.x.x
14. Use the Ethernet IP to connect to vncviewer

Conclusion: Thus the python programs for finding the factorial of a given number and prime
numbers within the given range has been written and the headless raspberry pi setup has been done
with ethernet connectivity.
SEC134 Hands-On Python with Raspberry Pi - Lab

Ex No 2: Interfacing the LED with Raspberry Pi

Problem: Write the Python program to blink the LED connected to the GPIO pin of a Raspberry Pi
Board

Aim: Write the Python program to blink the LED connected to the GPIO 14 of Raspberry-Pi board.
The LED will be ON for 1 Second and OFF for 2 Seconds.

Hardware/Software Tools required: Hardware: Raspberry Pi 4 with power adapter

Breadboard, LED, 100 Ohm Resistor

Software: Python 3 with time & GPIO package

Schematic:

Raspberry Pi 4 R = 100

GPIO14 (8th Pin)

Algorithm:

1. Import the RPi.GPIO library


2. Disable the warnings
3. Set the GPIO.BOARD mode to access the GPIO with board’s physical pin number.
4. Setup the 8th pin of GPIO connector of Raspberrypi as output and make it low.
5. Give HIGH logical signal to the 8th pin of GPIO connector of Raspberry Pi
6. Call Sleep function with 1 Second sleep time
7. Give LOW logical signal to the 8th pin of GPIO connector of Raspberry Pi
8. Call Sleep function with 2 Second sleep time
9. Goto step 5

Program:

Using RPi.GPIO Library


SEC134 Hands-On Python with Raspberry Pi - Lab

import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library

from time import sleep # Import the sleep function from the time module

GPIO.setwarnings(False) # Ignore warning for now

GPIO.setmode(GPIO.BOARD) # Use physical pin numbering

GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to
low (off)

while True: # Run forever

GPIO.output(8, GPIO.HIGH) # Turn on

sleep(1) # Sleep for 1 second

GPIO.output(8, GPIO.LOW) # Turn off

sleep(2) # Sleep for 1 second

Conclusion: Thus, the python program for blinking the LED connected to the 8th pin of GPIO
connector of Raspberry PI has been executed and witnessed the LED blinking.
SEC134 Hands-On Python with Raspberry Pi - Lab

Ex No 3: Write a program to get the input from the push button and actuate the LED accordingly
with Raspberry Pi

Problem: Write the python program to write a program to turn ON LED when push button is pressed

Aim: Write the Python program to turn ON the LED connected to the GPIO 14 (8th pin) of Raspberry-
Pi board when the push button connected to GPIO 21( 40th pin) is pressed.

Hardware/Software Tools required: Hardware: Raspberry Pi 4 with power adapter

Breadboard, LED,push button, 100 Ohm, 1K Resistor, jumper


wires -5

Software: Python 3 with time & GPIO package

Schematic: 3.3V

GPIO 15(10th Pin)

Raspberry Pi 4 R = 100

GPIO14 (8th Pin)

Algorithm:

To Be written by the student

Program:

Using RPi.GPIO Library

import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library

GPIO.setwarnings(False) # Ignore warning for now

GPIO.setmode(GPIO.BOARD) # Use physical pin numbering


SEC134 Hands-On Python with Raspberry Pi - Lab

GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to
low (off)

GPIO.setup(40, GPIO.IN) # Set pin 40 to be an input pin

while True: # Run forever

inp = GPIO.input(40)

print(inp)

if (inp == 0):

GPIO.output(8, GPIO.HIGH) # Turn on

else:

GPIO.output(8, GPIO.LOW) # Turn off

Conclusion: Thus the python program for turning ON the LED connected to the 8th pin of GPIO
connector when the push button connected to 40th pin of GPIO connector of Raspberry PI has been
executed and witnessed the LED blinking.
SEC134 Hands-On Python with Raspberry Pi - Lab

Ex No 4: Write a program to interface DHT11 sensor with Raspberry Pi and write a program to print
temperature and humidity readings.

Aim: Write a program to interface DHT11 sensor with Raspberry Pi and write a program to print
temperature and humidity readings for every 1 second.

Hardware/Software Tools required: Hardware: Raspberry Pi 4 with power adapter

Breadboard, DHT sensor, Jumper wires -3

Software: Python 3 with time & GPIO, DHT11 package

DHT11 package: https://github.com/binaryupdates/dht11-raspberrypi

Schematic:

GPIO21(40th Pin)

3.3V(1st Pin)

GND(6th Pin)

Raspberry Pi 4

Algorithm:

To Be written by the student

Program:

import RPi.GPIO as GPIO

import dht11

import time

# initialize GPIO

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BCM)
SEC134 Hands-On Python with Raspberry Pi - Lab

#GPIO.cleanup()

GPIO.setup(21, GPIO.IN) # Set pin 8 to be an output pin and set initial value to low (off)

# read data using Pin GPIO21

instance = dht11.DHT11(pin=21)

while True:

result = instance.read()

if result.is_valid():

print("Temp: %d C" % result.temperature +' '+"Humid: %d %%" % result.humidity)

time.sleep(1)

Conclusion: Thus the python program for interfacing DHT11 has been written for getting the
temperature and humidity values and the same is printed every 1 second.
SEC134 Hands-On Python with Raspberry Pi - Lab

Ex No 5: Write python programs to make raspberry pi board as web server and give the sensor
data to client and get the command from the user to turn ON/OFF the LED from the client. interface
DHT11 sensor with Raspberry Pi and write a program to print temperature and humidity readings.

Aim: Write a program to interface DHT11 sensor with Raspberry Pi and use the Flask package to
make the raspberry pi as web sever to serve the web page with temperature and humidity data and
to get the user data to control the led ON/OFF.

Hardware/Software Tools required: Hardware: Raspberry Pi 4 with power adapter

Breadboard, DHT sensor, Jumper wires -3

Software: Python 3 with time & GPIO, DHT11 package, Flask

DHT11 package: https://github.com/binaryupdates/dht11-raspberrypi

Schematic:

GPIO21(40th Pin)

3.3V(1st Pin)

GND(6th Pin)

Raspberry Pi 4

Algorithm:

To Be written by the student

Program:

Web Page:

style.css – Cascading style sheet (Should be in static folder)

body {

background: blue;

color: yellow;

}
SEC134 Hands-On Python with Raspberry Pi - Lab

Index.html (Should be in static folder)

<html>

<head>

<title>{{ title }}</title>

<link rel="stylesheet" href="../static/style.css/">

<meta http-equiv="refresh" content="5">

</head>

<body>

<h1>Hello from a PC!</h1>

<h2>The date and time on the server is: {{ time }}</h2>

<h2> Temperature is: {{ Temp }}</h2>

<h2> Humidity is: {{ Humid }}</h2>

</body>

</html>

Ledstat.html (Should be in static folder)

<html>

<head>

<title>{{ title }}</title>

<link rel="stylesheet" href="../static/style.css/">

</head>

<body>

<h2>LED connected to GPIO 14 is turned {{ ledstatus }}</h2>

</body>

</html>

import RPi.GPIO as GPIO

import dht11

import time

from flask import Flask, render_template, request

import datetime
SEC134 Hands-On Python with Raspberry Pi - Lab

global temper

global humidi

# initialize GPIO

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BCM)

#GPIO.cleanup()

GPIO.setup(21, GPIO.IN) # Set GPIO 21 to be an INput pin

GPIO.setup(14, GPIO.OUT, initial=GPIO.LOW) # Set GPIO 14 to be an output pin and set initial value
to low (off)

# read data using Pin GPIO21

instance = dht11.DHT11(pin=21)

app = Flask(__name__)

@app.route('/')

def index():

now = datetime.datetime.now()

timeString = now.strftime("%Y-%m-%d %H:%M")

while True:

result = instance.read()

if result.is_valid():

temper = result.temperature

humidi = result.humidity

break

templateData = {

'title' : 'HELLO!',

'time': timeString,

'Temp': temper,

'Humid': humidi

return render_template('index.html', **templateData)


SEC134 Hands-On Python with Raspberry Pi - Lab

@app.route('/ledctrl', methods=['GET'])

def ledctrl():

#return 'Hello world'

cmd = request.args.get('led')

print(cmd)

if cmd == 'ON':

GPIO.output(14, GPIO.HIGH) # Turn on

LedStatusString ='ON'

else:

GPIO.output(14, GPIO.LOW) # Turn off

LedStatusString = 'OFF'

templateData = {

'title' : 'LED_STATUS',

'ledstatus': LedStatusString

return render_template('ledstat.html', **templateData)

if __name__ == '__main__':

app.run(debug=False, host='0.0.0.0')

[ To get the output, run this python app and in your PC, open the browser and type the following

Raspberrypi.local:5000 - To get the sensor data along with the time

Raspberrypi.local:5000/ledctrl?led=ON - For turning ON the LED

Raspberrypi.local:5000/ledctrl?led=OFF - For turning OFF the LED


SEC134 Hands-On Python with Raspberry Pi - Lab

Output:

Index.html with the sensor data:

LED control:

LED ON

LED OFF
SEC134 Hands-On Python with Raspberry Pi - Lab

Conclusion: Thus, the python program using Flask has been executed which acts as a web server
with two web pages; index.html and ledstat.html. The application has been tested with the browser
and the sensor data is read and the user command is taken from client and given to the application
which controls the LED accordingly.
SEC134 Hands-On Python with Raspberry Pi - Lab

Ex No 6: Write a program to create UDP server on Raspberry Pi and respond with Temperature
and Humidity data to UDP client.
Aim: Write a python program to create UDP server on Raspberry Pi and respond with
Temperature and Humidity data to UDP client.
Hardware/Software Tools required: Hardware: Raspberry Pi 4 with power adapter, Hercules TCP
Utility

Breadboard, DHT sensor, Jumper wires -3

Software: Python 3 with time & GPIO, DHT11 package

DHT11 package: https://github.com/binaryupdates/dht11-raspberrypi

Schematic:

GPIO21(40th Pin)

3.3V(1st Pin)

GND(6th Pin)

Raspberry Pi 4

Algorithm:

To Be written by the student

Program:

import RPi.GPIO as GPIO

import dht11

import time

import socket

localPort = 20001
SEC134 Hands-On Python with Raspberry Pi - Lab

bufferSize = 1024

# initialize GPIO

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BCM)

#GPIO.cleanup()

GPIO.setup(21, GPIO.IN) # Set pin 8 to be an output pin and set initial value to low (off)

# read data using Pin GPIO21

instance = dht11.DHT11(pin=21)

# Create a datagram socket

UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# Bind to address and ip

UDPServerSocket.bind(('', localPort))

print("UDP server up and listening")

# Listen for incoming datagrams

while(True):

message, address = UDPServerSocket.recvfrom(bufferSize)

clientMsg = "Message from Client:{}".format(message)

clientIP = "Client IP Address:{}".format(address)

print(clientMsg)

print(clientIP)

if message == b'read':

while True:

result = instance.read()

if result.is_valid():

temper = result.temperature

humidi = result.humidity
SEC134 Hands-On Python with Raspberry Pi - Lab

break

msgFromServer = "Temperature:" + str(temper) +" Humidity:" + str(humidi)

bytesToSend = str.encode(msgFromServer)

# Sending a reply to client

UDPServerSocket.sendto(bytesToSend, address)

[ To get the output, run this python app and in your PC, open the Hercules Utility which will act as a
UDP Client.]

Output:

UDP Client querying the sensor data and getting it:

Conclusion: Thus, a python program has been written to create UDP server on Raspberry Pi and
respond with Temperature and Humidity data to UDP client.
SEC134 Hands-On Python with Raspberry Pi - Lab

Ex No 7: Write a program to create TCP server on Raspberry Pi and respond with Temperature
and Humidity data to TCP client.
Aim: Write a python program to create TCP server on Raspberry Pi and respond with
Temperature and Humidity data to TCP client.
Hardware/Software Tools required: Hardware: Raspberry Pi 4 with power adapter, Hercules TCP
Utility

Breadboard, DHT sensor, Jumper wires -3

Software: Python 3 with time & GPIO, DHT11 package

DHT11 package: https://github.com/binaryupdates/dht11-raspberrypi

Schematic:

GPIO21(40th Pin)

3.3V(1st Pin)

GND(6th Pin)

Raspberry Pi 4

Algorithm:

To Be written by the student

Program:

import RPi.GPIO as GPIO

import dht11

import time

import socket

localPort = 20001

bufferSize = 1024
SEC134 Hands-On Python with Raspberry Pi - Lab

# initialize GPIO

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BCM)

#GPIO.cleanup()

GPIO.setup(21, GPIO.IN) # Set pin 8 to be an output pin and set initial value to low (off)

# read data using Pin GPIO21

instance = dht11.DHT11(pin=21)

# Create a datagram socket

TCPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)

# Bind to address and ip

TCPServerSocket.bind(('', localPort))

TCPServerSocket.listen()

conn, addr = TCPServerSocket.accept()

print("UDP server up and listening")

print(f"Connected by {addr}")

while True:

message = conn.recv(bufferSize)

if not message:

break

if message == b'read':

while True:

result = instance.read()

if result.is_valid():

temper = result.temperature

humidi = result.humidity

break
SEC134 Hands-On Python with Raspberry Pi - Lab

msgFromServer = "Temperature:" + str(temper) +" Humidity:" + str(humidi)

bytesToSend = str.encode(msgFromServer)

# Sending a reply to client

conn.sendall(bytesToSend)

[ To get the output, run this python app and in your PC, open the Hercules Utility which will act as a
UDP Client.]

Output:

TCP Client querying the sensor data and getting it:

Conclusion: Thus, a python program has been written to create TCP server on Raspberry Pi and
respond with Temperature and Humidity data to TCP client.
SEC134 Hands-On Python with Raspberry Pi - Lab

Ex No 8: Write a Python program to interface a camera connected toRaspberry Pi and use


OpenCV to detect the edges of an object .
Aim: To write a Python program to interface a camera connected toRaspberry Pi and use
OpenCV to detect the edges of an object .

Hardware/Software Tools required: Hardware: Raspberry Pi 4 with power adapter, 5MP Camera,

Camera ribbon cable.

Software: Python 3 with OpenCV package

Schematic:

Algorithm:

To Be written by the student

Program:

i. Camera Interface Python Program

from picamera import PiCamera, Color


from time import sleep
from gpiozero import Button

button = Button(14)
camera = PiCamera()
camera.rotation = 180
camera.start_preview()
button.wait_for_press()
print("Button pressed")
sleep(5)
camera.capture('/home/pi/Desktop/image.jpg')
camera.stop_preview()

ii. Edge Detection using OpenCV

#!/usr/bin/python
SEC134 Hands-On Python with Raspberry Pi - Lab

# -*- coding: latin-1 -*-


# import the necessary packages

import cv2

# load the image, convert it to grayscale, and blur it slightly


image = cv2.imread("pills.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# show the original and blurred images


cv2.imshow("Original", image)
cv2.imshow("Blurred", blurred)

# compute a "wide", "mid-range", and "tight" threshold for the edges


wide = cv2.Canny(blurred, 10, 200)
mid = cv2.Canny(blurred, 50, 150)
tight = cv2.Canny(blurred, 240, 250)

# show the edge maps


cv2.imshow("Wide Edge Map", wide)
cv2.imshow("Mid Edge Map", mid)
cv2.imshow("Tight Edge Map", tight)
cv2.waitKey(0)

Edge Detection Output

Conclusion: Thus, a Python program has been written to interface the camera with Raspberry Pi.
An Edge detection using OpenCV is done in Raspberry Pi for a given image.
SEC134 Hands-On Python with Raspberry Pi - Lab

Appendix A: Raspberry Pi GPIO Connector

Figure A.1: Raspberry Pi GPIO Pinouts

Source: https://www.tutorialspoint.com/raspberry_pi/raspberry_pi_gpio_connector.htm

Appendix B:

Raspberry pi 4 OS setup:

Here we are setting up headless raspberry pi with Ethernet and VNC viewer.

15. Download the imager from the link


https://downloads.raspberrypi.org/imager/imager_latest.exe
16. Insert the SD card reader with the SD Card where the raspberry pi os has to be installed.
17. Open the imager app.
SEC134 Hands-On Python with Raspberry Pi - Lab

18. Choose Raspberry pi os (32-bit) as shown above.


19. Choose the SD card drive for the storage
20. Then click on write.
21. Open the SD Card and put the file “ssh” into the sd card.
22. And put one more file “wpa_supplicant.conf” for wireless internet connectivity
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
ssid="NETWORK_NAME"
psk="NETWORK_KEY"
}
23. Login to raspberry pi using ssh. Use putty and use the host name raspberrypi.local (default
port:22)
24. Login with the username “pi” and the password “raspberry”
25. Install the VNC server in raspberry pi with the following commands
sudo apt update
sudo apt install realvnc-vnc-server realvnc-vnc-viewer

26. Enable vnc server by giving the following commands


sudo raspi-config
Select the Interface options → VNC Enable/disable → Enable
27. Type ifconfig in the ssh window in putty. Get the Ethernet IP. Usually, if you connect the PC
directly, you will get the IP like 169.254.x.x (if you connect to PC directly through Ethernet)
28. Use the Ethernet IP to connect to vncviewer

You might also like