0% found this document useful (0 votes)
12 views60 pages

CIVILECEPythonlab manual - R22

The document is a lab manual for the Python programming course (CS406PC) at the Princeton Institute of Engineering & Technology for Women, detailing the course objectives, outcomes, and a series of experiments for students. It outlines prerequisites, program educational objectives, specific outcomes, and program outcomes related to Computer Science Engineering. Additionally, it includes instructions for installing Python and various libraries, along with practical exercises in Python programming and data handling.

Uploaded by

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

CIVILECEPythonlab manual - R22

The document is a lab manual for the Python programming course (CS406PC) at the Princeton Institute of Engineering & Technology for Women, detailing the course objectives, outcomes, and a series of experiments for students. It outlines prerequisites, program educational objectives, specific outcomes, and program outcomes related to Computer Science Engineering. Additionally, it includes instructions for installing Python and various libraries, along with practical exercises in Python programming and data handling.

Uploaded by

manjulacsepetw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

PRINCETON INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN

(Approved by AICTE, New Delhi & Affiliated to JNTU Hyderabad)


Chowdaryguda (V), Ghatkesar (M), Medchal-Malkajgiri(D).TS-500088
Phone: 9394544566 / 6305324412
e-mail: [email protected]
JNTUH Code(6M) CIVIL–EEE–ECE-CSE-CSE(AI&ML)-CSE(DS)-CSE(CS) EAMCET Code– PETW

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

Python programming
LAB MANUAL

Subject Code : CS406PC


Regulation : R22/JNTUH
Academic Year : 2024-2025

I B. TECH II SEMESTER

COMPUTER SCIENCE AND ENGINEERING

1 1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PRINCETON INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Approved by AICTE, New Delhi & Affiliated to JNTU Hyderabad)
Chowdaryguda (V), Ghatkesar (M), Medchal-Malkajgiri(D).TS-500088
Phone: 9394544566 / 6305324412
e-mail: [email protected]
JNTUH Code(6M) CIVIL–EEE–ECE-CSE-CSE(AI&ML)-CSE(DS)-CSE(CS) EAMCET Code– PETW

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Academic Year 2022-2023
COLLEGE VISION, MISSION, CORE VALUES AND QUALITY POLICY:

VISION

The educational environment in order to develop graduates with the strong academic technical backgrounds
needed to achieve distinction in the discipline and to bring up the Institution as an Institution of Academic
excellence of International standard.

MISSION

We transform persons into personalities by the state-of-the-art infrastructure, time consciousness, quick
response and the best academic practices through assessment and advice.

CORE VALUES

Attaining global eminence, by achieving excellence in all that we do in life education and service

VISION AND MISSION OF CSE DEPARTMENT


VISION

The educational environment in order to develop graduates with the strong academic technical
backgrounds needed to achieve distinction in the discipline and to bring up the Institution as an
Institution of Academic excellence of International standard.

MISSION

 We transform persons into personalities by the state-of-the-art infrastructure, time consciousness, quick

2
DEPARTMENT OF COMPUTER SCIENCE
AND ENGINEERING

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


PEOs DESCRIPTION
Work in Multinational companies and become successful IT professionals.
PEO1
Pursue higher studies and have their career in educational institutions research
PEO2 organizations, or be entrepreneurs.
Possess social responsibility, team work skills, leadership capabilities and urge
PEO3
for learning in their professional fields.
PROGRAM SPECIFIC OUTCOMES (PSOs)
PSOs DESCRIPTION
Applying the mathematical and computing knowledge to identify and provide
PSO1
solutions for solving computing enthusiastically problems.
Involving students in software development, software testing, storage, computing
PSO2
and business intelligence sectors.
Making them to use their technical expertise in latest technologies and update
PSO3 knowledge continuously in Computer Science and Engineering to excel in career.

3
P[
PROGRAM OUTCOMES:

PROGRAM OUTCOMES (POs)


POs DESCRIPTION
Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
PO1 an engineering specialization to the solution of complex engineering problems.

Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
PO2 problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
PO3 public health and safety, and the cultural, societal, and environmental considerations.

Conduct investigations of complex problems: Use research-based knowledge and research methods
PO4 including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
PO5 and IT tools including prediction and modeling to complex engineering activities with an understanding
of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
PO7 societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
PO8 engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in diverse
PO9
teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the engineering
PO10 community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the engineering and
PO11 management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12 independent and life-long learning in the broadest context of technological change.

4
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PREREQUISITES:
A course on “Programming for Problem Solving”, A course on “Computer Organization and Architecture”.

COURSE OBJECTIVES:

The objective of this lab is to get an overview to To provide an understanding of the design aspects of
operating system concepts through simulation and Introduce basic Unix commands, system call interface for
process management, interprocess communication and I/O in Unix

COURSE OUTCOMES:
1. Simulate and implement operating system concepts such as scheduling, deadlock management, file
management and memory management.
2. Able to implement C programs using Unix system calls.

5
P[
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Course Name: Course Code: CS406PC
Year/Semester: I/II Regulation: R22

S. No List of Page No.


Experiments
1 Downloading and Installing Python and Modules
a)Python 3 on Linux .
b)Python 3 on Windows
c)pip3 on Windows and Linux
d)Installing numpy and scipy
e)Installing jupyter lab
2 Introduction to Python3
a)Printing your biodata on the screen
b)Printing all the primes less than a given number
c)Finding all the factors of a number and show whether it is a perfect
number
3 Defining and Using Functions
a )Write a function to read data from a file and display it on the screen
b )Define a boolean function is palindrome(<input>)
c )Write a function collatz(x) which does the following: if x is odd, x =
3x + 1; if x is even, then x = x/2. Return the number of steps it takes for
x=1
d )Write a function N(m, s) = exp(-(x-m)2/(2s2))/sqrt(2π)s that
computes the Normal distribution
4 The package numpy
a )Creating a matrix of given order m x n containing random numbers
in the range 1 to 99999
b )Write a program that adds, subtracts and multiplies two matrices.
Provide an interface such that, based on the prompt, the function
(addition, subtraction, multiplication) should be performed
c )Write a program to solve a system of n linear equations in n
variables using matrix inverse
5 The package scipy and pyplot
6
a )Finding if two sets of data have the same mean value
b )Plotting data read from a file
c )Fitting a function through a set a data points using polyfit function
d )Plotting a histogram of a given data set
The strings package
6 a )Read text from a file and print the number of lines, words and
characters
b )Read text from a file and return a list of all n letter words beginning
with a vowel
c )Finding a secret message hidden in a paragraph of text
d )Plot a histogram of words according to their length from text read
from a file
7 Installing OS on Raspberry Pi
a )Installation using PiImager
b )Installation using image file
· Downloading an Image
· Writing the image to an SD card
· using Linux
· using Windows
· Booting up
8 Accessing GPIO pins using Python
a )First, update your repositories list:
Installing GPIO Zero library.
First, update your repositories list:
sudo apt update
Then install the package for Python 3:
sudo apt install python3-gpiozero
b )Blinking an LED connected to one of the GPIO pin
c )Adjusting the brightness of an LED
9 Collecting Sensor Data
a )DHT Sensor interface
◦ Connect the terminals of DHT GPIO pins of Raspberry Pi.
◦ Import the DHT library using import Adafruit_DHT
◦ Read sensor data and display it on screen.

FACULTY HOD, CSE

7
P[
Cycle – 1
1. Downloading and Installing Python and Modules
a) Python 3 on Linux
To install Python 3.6 or 3.8 on Ubuntu Linux machines:
To see which version of Python 3 you have installed, open a command prompt and run

If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the
following commands:

If you’re using another version of Ubuntu (e.g. the latest LTS release) or you want to use a
more current Python, we recommend using the deadsnakes PPA to install Python 3.8:

Working with Python 3

This will always launch the Python 3 interpreter.


b) Python 3 on Windows
Installing Python 3 on Windows 10 and 11
Step 1: Search for Python in Google

8
Step 2: Click on Welcome to Python.org

You will see the following screen.

Step 3: Place the mouse pointer on Downloads


Step 4: Click on Python3.11.3

10
Python 3.11.3 will be downloaded.

Step 5: Double click on the downloaded file and install Python.


You will see the following screen.

Step 6: Click on Customize Installation

You will see the following screen.

12
Step 7 : click on Next.

Step8 : click on Install.

c) pip3 on Windows and Linux


Check if pip3 is already installed by entering the following command in a terminal or command
line:

Output should be similar to:

14
You can also check to see which version of pip3 is installed by entering

Output should be similar to:

Confirm which version of Python (if any) is installed on your computer by entering:
Output should be similar to:

Pip3 Installation

Pip3 Upgrade

In operating system environments that already have Python 3 and pip3 installations, you
can upgrade pip3, by entering:

Ubuntu 20.4 has only Python 3, but still requires a separate python-pip 3 installation.

Procedure for installing pip3 on Ubuntu and Debian Linux:

Enter the following command to update Linux:

Enter the following command to install pip3:

The above command will also install all pip3 dependencies.


To find the location where pip3 installs packages in Ubuntu Linux, enter:

Output should be similar to:

16
Install pip3 Windows
To install or upgrade pip3 in a Windows environment that already has Python 3 installed:
Download the latest version of get-pip.py from

You can also use the curl command to download get-pip.py:

CD into the directory where get-pip.py was downloaded to, and enter the following command
to install pip3 and its dependencies:

You can verify that pip3 is installed by navigating to the default pip3 installation directory,
For Example: C:\python38\scripts\, and enter:

d) Installing numpy and scipy


You can install any python3 package using the command pip3 install <packagename>
Pip3 Usage

To install a Python package, enter:

e) Installing jupyterlab
Install from pip using the command pip install jupyterlab

2. Introduction to Python3

18
a) Printing your biodata on the screen

#python program to print biodata


print ("Biodata")
a=input("Enter your Name:")
b=input("Enter your Father's Name:")
c=input("Enter Date of Birth")
print("Name:",a)
print("\nFather's name:",b)
print("\nDate of Birth:",c)

OUTPUT

b) Printing all the primes less than a given number


#program to print prime numbers upto the given number
n=int(input("Enter any number"))
print ("The Prime Numbers are: ")
for number in range (1, n + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)

OUTPUT

c) Finding all the factors of a number and show whether it is a perfect number, i.e., the

20
sum of all its factors (excluding the number itself) is equal to the number itself

#program to check the given number is perfect or not and to print all the factors of the given
number
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
print("\n",i)
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")

OUTPUT

3. Defining and Using Functions


a) Write a function to read data from a file and display it on the screen
#function to read data from a file and display it on the screen
a=str(input("Enter the name of the file with .txt extension:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
print(line)
line=file2.readline()
file2.close()

OUTPUT

b) Define a boolean function is palindrome(<input>)

22
#program define a boolean function is palindrome(<input>)
def isPalindrome(s):
return s == s[::-1]
s=input("Enter any String")
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")

OUTPUT

c) Write a function collatz(x) which does the following: if x is odd, x = 3x + 1; if x is


even, then x = x/2. Return the number of steps it takes for x = 1
# program print collats sequence
def collatz_sequence(x):
num_seq = [x]
if x < 1:
return []
while x > 1:
if x % 2 == 0:
x=x/2
else:
x=3*x+1
# Added line
num_seq.append(x)
return num_seq
print(collatz_sequence(12))
print(collatz_sequence(19))

d) Write a function N(m, s) = exp(-(x-m)2/(2s2))/sqrt(2π)s that computes the Normal


distribution

24
#Program for Normal Distribution
from matplotlib import pyplot as mp
import numpy as np
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
mp.plot(x_values, gaussian(x_values, mu, sig))
mp.show()
Sample output:

4. The package numpy


a) Creating a matrix of given order m x n containing random numbers in the range 1 to
99999
import numpy as np
a=int(input("enter number of rows"))
b=int(input("enter number of columns"))
array = np.random.randint(100000, size=(a, b))
print(array)

SAMPLE OUTPUT

26
b) Write a program that adds, subtracts and multiplies two matrices. Provide an
interface such that, based on the prompt, the function (addition, subtraction,
multiplication) should be performed

# importing numpy as np
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])
# creating second matrix
B = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
# adding two matrix
print("Addition of two matrix")
print(np.add(A, B))
# subtracting two matrix
print("Subtraction of two matrix")
print(np.subtract(A, B))
# multiplication of two matrix
print("multiplication of two matrices")
result = np.dot(A,B)
r=result
for r in result:
print(r)

SAMPLE OUTPUT
28
c) Write a program to solve a system of n linear equations in n variables using matrix
inverse

Let’s now solve asystem of three linear equations, as shown below:


4x+3y+2z=25
-2x+2y+3z=-10
3x-5y+2z=-4

# program to solve a system of n linear equations in n variables using matrix inverse


A = np.array([[4, 3, 2], [-2, 2, 3], [3, -5, 2]])
B = np.array([25, -10, -4])
X = np.linalg.inv(A).dot(B)

print(X)

OUTPUT
5. The package scipy and pyplot
a) Finding if two sets of data have the same mean value

30
b) Plotting data read from a file

Create Sample file as shown below and save as Sample.txt

#Program to Plot data read from a file


import matplotlib.pyplot as plt
names = []
marks = []
f = open('sample.txt','r')
for row in f:
row = row.split(' ')
names.append(row[0])
marks.append(int(row[1]))
plt.bar(names, marks, color = 'g', label = 'File Data')
plt.xlabel('Student Names', fontsize = 12)
plt.ylabel('Marks', fontsize = 12)
plt.title('Students Marks', fontsize = 20)
plt.legend()
plt.show()

Sample output:
32
c) Fitting a function through a set a data points using polyfit function

#Fitting a function through a set a data points using polyfit function


import numpy as np
import matplotlib.pyplot as mp
np.random.seed(12)
x = np.linspace( 0, 1, 25 )
y = np.cos(x) + 0.3*np.random.rand(25)
p = np.poly1d( np.polyfit(x, y, 4) )
t = np.linspace(0, 1, 250)
mp.plot(x, y, 'o', t, p(t), '-')
mp.show()
Sample output:

34
d) Plotting a histogram of a given data set

#Program for histogram of a given dataset


from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])
# Creating histogram
fig, ax = plt.subplots(figsize =(10, 7))
ax.hist(a, bins = [0, 25, 50, 75, 100])
# Show plot
plt.show()

Sample output
6. The strings package
a) Read text from a file and print the number of lines, words and characters
Create a text file and save as data.txt

#program to count number of words, lines and characters in a text file


number_of_words = 0
number_of_lines = 0
number_of_characters = 0
with open("data.txt", 'r') as file:
for l in file:
number_of_words += len(l.split())
number_of_lines += 1
number_of_characters += len(l)
print("No of words: ", number_of_words)
print("No of lines: ", number_of_lines)
print("No of characters: ", number_of_characters)
Sample output:

36
b) Read text from a file and return a list of all n letter words beginning with a vowel
# Python Program that Extract words starting
# with Vowel From A list initializing list
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
# Printing original list
print("The original list is : " + str(test_list))
res = []
vow = "aeiou"
for i in test_list:
if i[0] in vow:
res.append(i)
# Printing result
print("The extracted words : " + str(res))
Sample Output:
c) Finding a secret message hidden in a paragraph of text

#Finding a secret message hidden in a paragraph of text

38
# Taking input from user
data = 'Svool sld ziv blf'
# conversion Chart
conversion_code = {
# Uppercase Alphabets
'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V', 'F': 'U',
'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q', 'K': 'P', 'L': 'O',
'M': 'N', 'N': 'M', 'O': 'L', 'P': 'K', 'Q': 'J', 'R': 'I',
'S': 'H', 'T': 'G', 'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C',
'Y': 'B', 'Z': 'A',

# Lowercase Alphabets
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u',
'g': 't', 'h': 's', 'i': 'r', 'j': 'q', 'k': 'p', 'l': 'o',
'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k', 'q': 'j', 'r': 'i',
's': 'h', 't': 'g', 'u': 'F', 'v': 'e', 'w': 'd', 'x': 'c',
'y': 'b', 'z': 'a'
}
# Creating converted output
converted_data = ""
for i in range(0, len(data)):

if data[i] in conversion_code.keys():
converted_data += conversion_code[data[i]]
else:
converted_data += data[i]
# Printing converted output
print(converted_data)

Sample Output:
d) Plot a histogram of words according to their length from text read from a file

#Program to Plot a histogram of words according to their length from


#text read from a file
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]


plt.rcParams["figure.autolayout"] = True

bar_names = []
bar_heights = []

for line in open("hist.txt", "r"):


bar_name, bar_height = line.split()
bar_names.append(bar_name)
bar_heights.append(bar_height)
plt.bar(bar_names, bar_heights)
plt.show()

#Program to Plot a histogram of words according to their length from


#text read from a file
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]


plt.rcParams["figure.autolayout"] = True

bar_names = []
bar_heights = []

for line in open("hist.txt", "r"):


bar_name, bar_height = line.split()
bar_names.append(bar_name)
bar_heights.append(bar_height)
plt.bar(bar_names, bar_heights)
plt.show()

Sample Data to be stored in hist.txt is

Seyfert1 112
Seyfert2 42
Quasars 131
QuasarsSeyfert1 46
Radiogalaxy 5

40
BLlacHP 39
Seyfert3 5
HeIIRegions 55

Sample Output:
Cycle – 2

Blinking an LED connected to one of the GPIO pin


A great way to get started with electronics and the Raspberry Pi is hooking up a red LED and
making it blink using a Python script. This tutorial will guide you through setting up the circuit,
connecting it to the Raspberry Pi and how to write the Python script that makes the LED blink.
What you’ll need for this guide
We will need the following tools to complete the project:
 Raspberry Pi 3 setup with monitor and USB Mouse & Keyboard
o Checkout this guide if you need help
 Solderless breadboard
 Jumper wires for easy hookup
 Resistor pack
 Red LED
 Multimeter (optional)
Setting up the circuit
The first step in this project is to design a simple LED circuit. Then we will make the LED
circuit controllable from the Raspberry Pi by connecting the circuit to the general purpose
input/output (GPIO) pins on the Raspberry Pi.

A simple LED circuit consists of a LED and resistor. The resistor is used to limit the current
that is being drawn and is called a current limiting resistor. Without the resistor the LED would
run at too high of a voltage, resulting in too much current being drawn which in turn would
instantly burn the LED, and likely also the GPIO port on the Raspberry Pi.

To calculate the resistor value we need to examine the specifications of the LED. Specifically
we need to find the forward voltage (VF) and the forward current (IF). A regular red LED has
a forward voltage (VF) of 1.7V and forward current of 20mA (IF). Additionally we need to
know the output voltage of the Raspberry Pi which is 3.3V.

We can then calculate the resistor size needed to limit the current to the LED’s maximum
forward current (IF) using ohm’s law like this:

RΩ=VI=3.3–VFIF=3.3–1.720mA=80Ω

Unfortunately 80 ohm is not a standard size of a resistor. To solve this we can either combine
multiple resistors, or round up to a standard size. In this case we would round up to 100 ohm.

42
Important information: Since ohm’s law tells us that I (current) = V (voltage) / R (ohm)
rounding up the resistor value will lower the actual current being drawn a little. This is good
because we don’t want to run our system at the maximum current rating. Rounding down
instead of up would be dangerous, since it will actually increase the current being drawn.
Increased current would result in running our system over the maximum rating and potentially
destroying or damaging our components.

With the value calculated for the current limiting resistor we can now hook the LED and resistor
up to GPIO pin 8 on the Raspberry Pi. The resistor and LED needs to be in series like the
diagram below. To find the right resistor use the resistor color code – for a 100 ohm resistor it
needs to be brown-black-brown. You can use your multimeter to double check the resistor
value.
When hooking up the circuit note the polarity of the LED. You will notice that the LED has a
long and short lead. The long lead is the positive side also called the anode, the short lead is
the negative side called the cathode. The long should be connected to the resistor and the short
lead should be connected to ground via the blue jumper wire and pin 6 on the Raspberry Pi as
shown on the diagram.
To find the pin number refer to this diagram showing the physical pin numbers on the

44
Writing the Python Software to blink the LED

With the circuit created we need to write the Python script to blink the LED. Before we start
writing the software we first need to install the Raspberry Pi GPIO Python module. This is a
library that allows us to access the GPIO port directly from Python.

To install the Python library open a terminal and execute the following

With the library installed now open your favorite Python IDE (I recommend Thonny Python
IDE more information about using it here)

Our script needs to do the following:


 Initialize the GPIO ports
 Turn the LED on and off in 1 second intervals

To initialize the GPIO ports on the Raspberry Pi we need to first import the Python library, the
initialize the library and setup pin 8 as an output pin.

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)

Next we need to turn the LED on and off in 1 second intervals by setting the output pin to either
high (on) or low (off). We do this inside a infinite loop so our program keep executing until we
manually stop it.

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(1) # Sleep for 1 second

Combining the initialization and the blink code should give you the following full Python
program:

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(1) # Sleep for 1 second

With our program finished, save it as blinking_led.py and run it either inside your IDE or in
the console with:

With the program running you should see something like this:

46
ADJUSTING THE BRIGHTNESS OF AN LED

48
Controlling Brightness of LED using Raspberry Pi 4
Controlling the brightness of an LED or blinking it continually by passing various delays
with PWM(Pulse Width Modulation) it might be your first Raspberry Pi 4 learning experience.
In this article, we perform three activities which are
 Turning On & Off LED.
 Blinking it using PWM at different frequencies.
 Controlling the brightness of the LED.
Required Components:
 Raspberry Pi 4 controller.
 Monitor/Laptop.
 And other connecting wires such as (Ethernet Cable, HDMI Cable, & Powering cable for
both Raspberry Pi and Monitor, etc.)
 LED of any color.
 Jumper Wire.
 Bread-board.
 Resistor 100 Ohm.
Now we will proceed further with our first activity i.e. Turning On & Off LED.
Circuit Connection for controlling the brightness of LED using Raspberry pi:
The circuit diagram remains the same for all 3 activities there is no change in the circuit
diagram only we have to change the code for all activities to blink it and to control its brightness
from 0 to 100 by applying PWM signal via Board pin 11(in raspberry pi there are two different
types of pin numbering available, you can use anyone out of these two there is a slight change
in the code by which you can switch these pin numbering configuration). The 2 pin
configurations are GPIO pin configuration and the second one is Board Pin configuration.
further, I’ll tell you what is the change required in the code to switch between available pin
configurations.
As you can see that in the above figure the positive terminal of LED is connected to the board
pin 11 and on which we will apply 5V to turn ON&OFF LED. Now we have done with the
circuit diagram, now think! how to power the LED with raspberry pi? to answer this let us
move to the coding part.

Code to turn On & Off:


import RPi.GPIO as GPIO //Importing GPIO library as object GPIO
GPIO.setmode(GPIO.Board) //If you are using board pin numbering ||or||
GPIO.setmode(GPIO.BCM) //If you are using GPIO pin numbering you can use either one
GPIO.setup(11, GPIO.OUT) //Board pin 11 set as output pin.
GPIO.output(11, True) //To turn on LED pin 11 supplied with logic 1 and by switching this
you can turn on and off LED.
Code to blink LED:
import RPi.GPIO as GPIO
import time //Imported time library
GPIO.setmode(GPIO.Board)
GPIO.setup(11, GPIO.OUT)
while:
GPIO.output(11, True)
time.sleep(1)
GPIO.output(11, False)
time.sleep(1)
Code for controlling the brightness of LED using Raspberry pi:
import RPI.GPIO as GPIO
import time
GPIO.setmode(GPIO.Board)
GPIO.setup(11, GPIO.OUT)
p = GPIO.PWM(11, 100) //11 is pin number and 100 is max range of PWM.
p.start(0) //Starting point of PWM signal you can select any value between 0 to 100.
while True:
for x in range (0, 100, 1): //Increasing brightness of LED from 0 to 100
p.ChangeDutyCycle(x)
time.sleep(0.1)
for x in range (100, 0, -1): //fading brightness of LED from 100 to 0
p.ChangeDutyCycle(x)
time.sleep(0.1)

ADJUST THE BRIGHTNESS OF AN LED (0 TO 100, WHERE 100 MEANS


MAXIMUM BRIGHTNESS) USING THE IN BUILT PWM WAVELENGTH

Control LED brightness with PWM


Pulse width modulation, allows you to give analogue behaviours to digital devices, such as
LEDs. This means that rather than an LED being simply on or off, you can control its
brightness.
For this activity, you can use the circuit from the last step.

50
Save and run the file. You should see the LED pulse bright and dim, in a continuous cycle.
The frequency ( pwm.freq) tells Raspberry Pi Pico how often to switch the power between on
and off for the LED.
The duty cycle tells the LED for how long it should be on each time. For Raspberry Pi Pico in
MicroPython, this can range from 0 0 to 6 65025. 6502505 would be 100% of the time, so the
LED would stay bright. A value of around2 32512 would indicate that it should be on for half
the time.

Collecting Sensor Data


a) DHT Sensor interface
◦ Connect the terminals of DHT GPIO pins of Raspberry Pi.
◦ Import the DHT library using import Adafruit_DHT
◦ Read sensor data and display it on screen.
Raspberry Pi DHT11 Humidity and Temperature Sensor Interface
In this project, we will learn about DHT11 Humidity and Temperature Sensor and how the
Raspberry Pi DHT11 Humidity Sensor interface works. By Interfacing DHT11 Temperature
and Humidity Sensor with Raspberry Pi, you can implement a basic IoT Project like a simple
Weather Station.

52
Overview
DHT11 is a Digital Sensor consisting of two different sensors in a single package. The sensor
contains an NTC (Negative Temperature Coefficient) Temperature Sensor, a Resistive-type
Humidity Sensor and an 8-bit Microcontroller to convert the analog signals from these
sensors and produce a Digital Output.
I have already worked with the DHT11 Sensor in my DHT11 Humidity Sensor on
Arduino Project. In that project, I have mentioned the Pin Configuration of the DHT11
Sensor, how to interface it with a Microcontroller and how the digital Output from the
DHT11 Sensor can be decoded.

So, I suggest you to refer to that project once for more information on DHT11 Humidity and
Temperature Sensor. I’ll explain a few thing which I have missed in the Arduino Project.
We know that the output from the DHT11 Sensor is Digital. But how exactly we can read this
digital data?

Reading Digital Output from DHT11


DHT11 uses a Single bus data format for communication. Only a single data line between an
MCU like Arduino or Raspberry Pi and the DHT11 Sensor is sufficient for exchange of
information.

In this setup, the Microcontroller acts as a Master and the DHT11 Sensor acts as a Slave. The
Data OUT of the DHT11 Sensor is in open-drain configuration and hence it must always be
pulled HIGH with the help of a 5.1KΩ Resistor.
This pull-up will ensure that the status of the Data is HIGH when the Master doesn’t request

54
the data (DHT11 will not send the data unless requested by the Master).
Now, we will the how the data is transmitted and the data format of the DHT11 Sensor.
Whenever the Microcontroller wants to acquire information from DHT11 Sensor, the pin of
the

Microcontroller is configured as OUTPUT and it will make the Data Line low for a minimum
time of 18ms and releases the line. After this, the Microcontroller pin is made as INPUT.
The data pin of the DHT11 Sensor, which is an INPUT pin, reads the LOW made by the
Microcontroller and acts as an OUTPUT pin and sends a response of LOW signal on the data
line for about 80µs and then pulls-up the line for another 80µs.
After this, the DHT11 Sensor sends a 40 bit data with Logic ‘0’ being a combination of 50µs
of LOW and 26 to 28µs of HIGH and Logic ‘1’ being 50µs of LOW and 70 to 80µs of
HIGH.

After transmitting 40 bits of data, the DHT11 Data Pin stays LOW for another 50µs and
finally changes its state to input to accept the request from the Microcontroller.
NOTE: We have implemented this logic while programming the Arduino. But for Raspberry
Pi, we used a library that takes care of all these things.
Raspberry Pi DTH11 Humidity and Temperature Sensor Interface
By interfacing the DHT11 Sensor with Raspberry Pi, you can build your own IoT Weather
Station. All you need to implement such IoT Weather is a Raspberry Pi, a DHT11 Humidity
and Temperature Sensor and a Computer with Internet Connectivity.

Circuit Diagram
The following is the circuit diagram of the DHT11 and Raspberry Pi Interface.
Components Required
 Raspberry Pi 3 Model B
 DHT11 Temperature and Humidity Sensor
 Connecting Wires
 Power Supply
 Computer

Circuit Design
If you observe the circuit diagram, there is not a lot of stuff going on with respect to the
connections. All you need to do is to connect the VCC and GND pins of the DHT11 Sensor
to +5V and GND of Raspberry Pi and then connect the Data OUT of the Sensor to the GPIO4
i.e. Physical Pin 7 of the Raspberry Pi.

Installing DTH11 Library

56
Since we are using a library called Adafruit_DHT provided by Adafruit for this project, we
need to first install this library into Raspberry Pi.
First step is to download the library from GitHub. But before this, I have created a folder
called ‘library’ on the desktop of the Raspberry Pi to place the downloaded files. You don’t
have to do that.
Now, enter the following command to download the files related to the Adafruit_DHT
library

git clone https://github.com/adafruit/Adafruit_Python_DHT.git

All the contents will be downloaded to a folder called ‘Adafruit_Python_DHT’. Open this
directory using cd Adafruit_Python_DHT. To see the contents of this folder, use ‘ls’
command.

In that folder, there is file called ‘setup.py’. We need to install this file using the following
command.
Code
As we are using the library Adafruit_DHT for this project, there is nothing much to do in the
Python Programming part. All you need to do is to invoke the library with the Sensor and
GPIO Pin and print the values of Temperature and Humidity

import sys
import Adafruit_DHT
import time
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
print 'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity)
time.sleep(1)

Working
Make the connections as per the circuit diagram and install the library. Use the above python
program to see the results.

58
60

You might also like