[go: up one dir, main page]

0% found this document useful (0 votes)
45 views20 pages

Week-8 Ece

Uploaded by

jayanthijilukara
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)
45 views20 pages

Week-8 Ece

Uploaded by

jayanthijilukara
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/ 20

Week-8:

8. Accessing GPIO pins using Python

a) Installing GPIO Zero library.


First, update your repositories list:
sudo apt update
Then install the package for Python 3:
sudo apt install python3-gpiozero

Installing GPIO Zero

GPIO Zero is installed by default in the Raspberry Pi OS desktop


image, Raspberry Pi OS Lite image, and the Raspberry Pi Desktop image for
PC/Mac, all available from raspberrypi.org. Follow these guides to installing on
other operating systems, including for PCs using the remote GPIO feature.

1.1. Raspberry Pi

GPIO Zero is packaged in the apt repositories of Raspberry Pi


OS, Debian and Ubuntu. It is also available on PyPI.

1.1.1. apt

First, update your repositories list:

pi@raspberrypi:~$ sudo apt update


Then install the package for Python 3:

pi@raspberrypi:~$ sudo apt install python3-gpiozero


or Python 2:

pi@raspberrypi:~$ sudo apt install python-gpiozero


1.1.2. pip
If you’re using another operating system on your Raspberry Pi, you may need to
use pip to install GPIO Zero instead. Install pip using get-pip and then type:

pi@raspberrypi:~$ sudo pip3 install gpiozero


or for Python 2:

pi@raspberrypi:~$ sudo pip install gpiozero


To install GPIO Zero in a virtual environment, see the Development page.

1.2. PC/Mac

In order to use GPIO Zero’s remote GPIO feature from a PC or Mac, you’ll need to
install GPIO Zero on that computer using pip. See the Configuring Remote
GPIO page for more information.

1.3. Documentation

This documentation is also available for offline installation like so:

pi@raspberrypi:~$ sudo apt install python-gpiozero-doc


This will install the HTML version of the documentation under
the /usr/share/doc/python-gpiozero-doc/html path. To view the offline
documentation you have several options:

You can open the documentation directly by visiting file:///usr/share/doc/python-


gpiozero-doc/html/index.html in your browser. However, be aware that
using file:// URLs sometimes breaks certain elements. To avoid this, you can view
the docs from an http:// style URL by starting a trivial HTTP server with Python,
like so:

$ python3 -m http.server -d /usr/share/doc/python-gpiozero-doc/html


Then visit http://localhost:8000/ in your browser.
Alternatively, the package also integrates into Debian’s doc-base system, so you
can install one of the doc-base clients (dochelp, dwww, dhelp, doc-central, etc.)
and use its interface to locate this document.

b) Blinking an LED connected to one of the GPIO pin

The article guide you through blinking a LED using the GPIO pins of Raspberry Pi.

Hope that you should have gone through the initial raspberry pi setup as given in our
previous tutorials : - ) Raspberry Pi 3 B+ have a total of 40 GPIO
pins
Above image properly mentions pin configuration of the Raspberry Pi 3 B+,
now explaining it briefly -

1. Voltage Pins - Two 5V ( pin 2 and 4 ) pins and two 3V3 ( pin 1 and 17 ) pins
are present on the board, as well as a number of ground pins i.e 0V ( pin
6,9,14,20,25,30,34 and 39 ) which are unconfigurable. The remaining pins are
all general purpose 3V3 pins, meaning outputs are set to 3V3 and inputs are
3V3-tolerant.
2. Outputs - A GPIO pin designated as an output pin can be set to high (3V3) or
low (0V).
3. Inputs - A GPIO pin designated as an input pin can be read as high (3V3) or
low (0V). This is made easier with the use of internal pull-up or pull-down
resistors. Pins GPIO2 and GPIO3 have fixed pull-up resistors, but for other
pins this can be configured in software.
4. More - As well as simple input and output devices, the GPIO pins can be used
with a variety of alternative functions, some are available on all pins, others
on specific pins.
I. PWM (pulse-width modulation)
o Software PWM available on all pins
o Hardware PWM available on GPIO12, GPIO13, GPIO18,
GPIO19
II. SPI
o SPI0: MOSI (GPIO10); MISO (GPIO9); SCLK (GPIO11); CE0
(GPIO8), CE1 (GPIO7)
o SPI1: MOSI (GPIO20); MISO (GPIO19); SCLK (GPIO21);
CE0 (GPIO18); CE1 (GPIO17); CE2 (GPIO16)
III. I2C
o Data: (GPIO2); Clock (GPIO3)
o EEPROM Data: (GPIO0); EEPROM Clock (GPIO1)
IV. Serial (UART)
o TX (GPIO14); RX (GPIO15)

You can also visit : https://pinout.xyz/ for more detailed Information


Blinking LED using GPIO pin -

Step 1 - Connections

Here we will be using GPIO 21 or pin no. 40 to make the LED blink. Ground ( 0V)
at pin 39 will be used to provide ground with a resistance ( 270,330,1k ohm ) in
series to LED. Make connection by referring the Diagram below

Step 2 - Writing Python code on Python 3(IDLE)

 Open Python 3 (IDLE) in your Raspberry Pi


 Now Create a new file. And add the code import RPi.GPIO as GPIO #
Importing GPIO library

import time
LedPin = 40 # Defining pin40 as LedPin

def setup():
 GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
 GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output
 GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to turn on led
def blink():
 while True:
  GPIO.output(LedPin, GPIO.HIGH) # led on
  time.sleep(1) # keeping it in previous state for 1 sec
  GPIO.output(LedPin, GPIO.LOW) # led off
  time.sleep(1) # keeping it in previous state for 1 sec

def destroy():
 GPIO.output(LedPin, GPIO.LOW) # led off
 GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
 setup()
  try:
   blink()
   except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child
program destroy() will be executed.
&nbsp; &nbsp;destroy()<code></code>

d) Adjust the brightness of an LED (0 to 100, where 100 means maximum


brightness) using the in-built PWM wavelength.

Raspberry Pi LED Brightness Controller:

 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.
 Breadboard.
 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.

Circuit
Diagram to turn On/Off LED using Raspberry Pi.
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)

Week-9:

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.

DHT11 Sensor
 DHT11 sensor measures and provides humidity and temperature values
serially over a single wire.
 It can measure relative humidity in percentage (20 to 90% RH) and
temperature in degree Celsius in the range of 0 to 50°C.
 It has 4 pins; one of which is used for data communication in serial form.
 Pulses of different TON and TOFF are decoded as logic 1 or logic 0 or start
pulse or end of a frame.

For more information about the DHT11 sensor and how to use it, refer the
topic DHT11 sensor in the sensors and modules topic.

Connection Diagram of DHT11 with Raspberry Pi


DHT11 Interfacing with Raspberry Pi 3
Read Temperature and Humidity using DHT11 and Raspberry Pi

 Here, we are going to interface the DHT11 sensor with Raspberry Pi 3 and
display Humidity and Temperature on the terminal.
 We will be using the DHT Sensor Python library by Adafruit from GitHub.
The Adafruit Python DHT Sensor library is created to read the Humidity and
Temperature on Raspberry Pi or Beaglebone Black. It is developed for DHT
series sensors like DHT11, DHT22, or AM2302.

Download Adafruit DHT Sensor library from here.


 Extract the library and install it in the same root directory of the downloaded
library by executing the following command,

sudo python setup.py install

 Once the library and its dependencies have been installed, open the example
sketch named simpletest from the library kept in the examples folder.
 In this code, raspberry Pi reads Humidity and Temperature from the DHT11
sensor and prints them on the terminal. But, it read and displays the value
only once. So, here we made a change in the program to print value
continuously.

Note:

 Assign proper sensor type to the sensor variable in this library. Here,
we are using DHT11 sensor.

sensor = Adafruit_DHT.DHT11

 If anyone is using sensor DHT22 then we need to


assign Adafruit_DHT.DHT22 to the sensor variable shown above.
 Also, comment out the Beaglebone pin definition and uncomment pin
declaration for Raspberry Pi.
 Then assign pin no. to which the DHT sensor’s data pin is connected.
Here, data out of the DHT11 sensor is connected to GPIO4. As shown
in the above interfacing diagram.

DHT11 Python Program for Raspberry Pi


#!/usr/bin/python

# Copyright (c) 2014 Adafruit Industries


# Author: Tony DiCola

# Permission is hereby granted, free of charge, to any person obtaining a copy


# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY


KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE
# SOFTWARE.
import Adafruit_DHT

# Sensor should be set to Adafruit_DHT.DHT11,


# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.DHT11

# Example using a Beaglebone Black with DHT sensor


# connected to pin P8_11.
#pin = 'P8_11'

# Example using a Raspberry Pi with DHT sensor


# connected to GPIO4.
pin = 4

# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))

'''

# Note that sometimes you won't get a reading and

# the results will be null (because Linux can't

# guarantee the timing of calls to read the sensor).

# If this happens try again!

if humidity is not None and temperature is not None:

print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))

else:

print('Failed to get reading. Try again!')


'''
DHT11 Output

You might also like