In this article we will look at Programming Raspberry Pi with Python programming language.
LED blink program
The schematic or connection diagram for blinking a LED using Raspberry Pi is as shown below.
Code for blinking and LED using Raspberry Pi given below:
import RPi.GPIO as GPIO
import time
led_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)
while True:
GPIO.output(led_pin, GPIO.HIGH)
time.sleep(1)
GPIO.output(led_pin, GPIO.LOW)
time.sleep(1)
GPIO.cleanup( )
DHT11 Sensor
We need to install two libraries/software for making DHT11 sensor work with Raspberry Pi 4. Open a terminal and type the following commands.
pip3 install adafruit-circuitpython-dht
sudo apt-get install libgpiod2
The first command installs Adafruit’s DHT library that works with CircuitPython. The second command is a library for accessing the GPIO pins of Raspberry Pi.
The schematic or connections diagram for connecting DHT 11 sensor with Raspberry Pi is given below.
The code for sensing temperature and humidity using DHT 11 sensor using Raspberry Pi 4 is given below.
import time
import board
import adafruit_dht
dhtDevice = adafruit_dht.DHT11(board.D17)
while True:
try:
# Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print(“Temp: {:.1f} F / {:.1f} C Humidity: {}% “.format(temperature_f, temperature_c, humidity))
except RuntimeError as error:
# Errors happen fairly often, DHT’s are hard to read, just keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
dhtDevice.exit()
raise error
time.sleep(2.0)
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Nice and useful post author. Thank you. keep it up.