Raspberry PI
Raspberry Pi is a small single-board computer (SBC). It is a credit card-sized computer
that can be plugged into a monitor. It acts as a minicomputer by connecting the
keyboard, mouse, and display. Raspberry Pi has an ARM processor and 512MB of
RAM.
The following diagram shows the architecture of Raspberry Pi:
The following diagram shows some main blocks of Raspberry Pi:
Raspberry Pi mainly consists of the following blocks:
• Processor: Raspberry Pi uses Broadcom BCM2835 system on chip which is an
ARM processor and Video core Graphics Processing Unit (GPU). It is the heart of
the Raspberry Pi which controls the operations of all the connected devices and
handles all the required computations.
• HDMI: High Definition Multimedia Interface is used for transmitting video or
digital audio data to a computer monitor or to digital TV. This HDMI port helps
Raspberry Pi to connect its signals to any digital device such as a monitor digital
TV or display through an HDMI cable.
• GPIO ports: General Purpose Input Output ports are available on Raspberry Pi
which allows the user to interface various I/P devices.
• Audio output: An audio connector is available for connecting audio output
devices such as headphones and speakers.
• USB ports: This is a common port available for various peripherals such as a
mouse, keyboard, or any other I/P device. With the help of a USB port, the
system can be expanded by connecting more peripherals.
• SD card: The SD card slot is available on Raspberry Pi. An SD card with an
operating system installed is required for booting the device.
• Ethernet: The ethernet connector allows access to the wired network, it is
available only on the model B of Raspberry Pi.
• Power supply: A micro USB power connector is available onto which a 5V
power supply can be connected.
• Camera module: Camera Serial Interface (CSI) connects the Broadcom
processor to the Pi camera.
• Display: Display Serial Interface (DSI) is used for connecting LCD to Raspberry
Pi using 15 15-pin ribbon cables. DSI provides a high-resolution display interface
that is specifically used for sending video data.
Making a LED blink using the Raspberry Pi and Python
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
• Red LED
Circuit:
Code:
import [Link] as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
[Link](False) # Ignore warning for now
[Link]([Link]) # Use physical pin numbering
[Link](8, [Link], initial=[Link]) # Set pin 8 to be an output pin and set
initial value to low (off)
while True: # Run forever
[Link](8, [Link]) # Turn on
sleep(1) # Sleep for 1 second
[Link](8, [Link]) # Turn off
sleep(1) # Sleep for 1 second
for buzzer same setup as above just replace led with buzzer.
it will work like this:
How to Use Push Button:
Circuit:
Code:
import [Link] as GPIO
import time
[Link]([Link])
[Link](23, [Link], pull_up_down=GPIO.PUD_UP)#Button to GPIO23
[Link](24, [Link]) #LED to GPIO24
try:
while True:
button_state = [Link](23)
if button_state == False:
[Link](24, True)
print('Button Pressed...')
[Link](0.2)
else:
[Link](24, False)
except:
[Link]()
DHT11
Install the dht11 library
This for reference:
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))
'''
# sometimes 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!')'''
This is just the code without too much comments:
import Adafruit_DHT
import time
# Set sensor type
sensor = Adafruit_DHT.DHT11
# Set GPIO pin (BCM numbering)
pin = 4
# Continuous loop to read and display sensor data
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
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!')
[Link](2) # optional delay between reads
LDR:
Code:
import [Link] as GPIO
import time
LDR_PIN = 4
def rc_time(pin):
count = 0
# Discharge the capacitor
[Link](pin, [Link])
[Link](pin, False)
[Link](0.1)
# Switch to input and count until pin goes high
[Link](pin, [Link])
while [Link](pin) == [Link]:
count += 1
return count
[Link]([Link])
try:
while True:
light_level = rc_time(LDR_PIN)
print("Light level:", light_level)
[Link](0.5)
except KeyboardInterrupt:
pass
finally:
[Link]()
shorter code (but u need gpiozero which can be done using sudo apt install python3-
gpiozero):
From gpiozero import LightSensor
ldr = LightSensor(4)
While True:
Print([Link])
IR sensor:
Code:
import [Link] as GPIO
import time
# declare the sensor and led pin
sensor_pin = 23
led_pin = 26
# GPIO setup
[Link](False)
[Link]([Link])
[Link](sensor_pin, [Link])
[Link](led_pin, [Link])
try:
while True:
if [Link](sensor_pin):
# If no object is near
[Link](led_pin, False)
while [Link](sensor_pin):
[Link](0.2)
else:
# If an object is detected
[Link](led_pin, True)
except KeyboardInterrupt:
[Link]()
shorter code:
from gpiozero import LED, DigitalInputDevice
from time import sleep
sensor = DigitalInputDevice(23)
led = LED(26)
try:
while True:
[Link]() if not [Link] else [Link]()
sleep(0.2)
except KeyboardInterrupt:
pass
Interface motor using relay:
Code:
import time
import [Link] as GPIO
relay_ch = 26
[Link](False)
[Link]([Link])
[Link](relay_ch, [Link])
try:
while True:
[Link](relay_ch, [Link])
print("Relay ON")
[Link](1)
[Link](relay_ch, [Link])
print("Relay OFF")
[Link](1)
except KeyboardInterrupt:
print("Program stopped by User")
[Link]()
This code:
• Repeats relay on/off every second.
• Lets you stop the loop gracefully with Ctrl+C
Relay diagram:
How a Single Channel Relay Works
• Input Side:
The relay module has an input pin (usually labeled IN or S) and power pins (VCC
and GND). The input pin is connected to your microcontroller’s digital output pin.
• Output Side:
The relay has three screw terminals:
o NO (Normally Open): Device is OFF when relay is not energized; turns O
N when relay is energized.
o COM (Common): Common contact.
o NC (Normally Closed): Device is ON when relay is not energized; turns
OFF when relay is energized.
• How it switches:
When the microcontroller sends a HIGH or LOW signal (depending on relay type)
to the input pin, it energizes the relay coil, causing the internal switch to change
state (from NO to COM, or NC to COM).
Typical Uses of a Single Channel Relay
• Home Automation:
Remotely switch lights, fans, or other appliances.
• Industrial Automation:
Control machinery, pumps, or other electrical devices.
• IoT Projects:
Switch devices over WiFi/Bluetooth using ESP8266, ESP32, etc.
• Safety Systems:
Activate alarms or emergency systems.
• Remote Control:
Control devices via remote, app, or web interface.
• Timer Circuits:
Turn appliances ON/OFF after a set time.
• Energy Management:
Disconnect high-power devices to save energy.
Display the temperature and humidity measured by DHT11 sensor in raspberry pi
to smartphone :
Components Needed
• Raspberry Pi (3 or higher recommended since they have built-in Bluetooth)
• DHT11 temperature and humidity sensor
• Jumper wires(normal wires also ok)
• 10K ohm resistor (pull-up resistor for the DHT11 data line)(optional)
• Breadboard (optional)
• Power supply for Raspberry Pi
Connect the DHT11 Sensor to Raspberry Pi (refer diagram of dht 11 for this)
Wire the DHT11 sensor to the Raspberry Pi:
1. Connect VCC pin of DHT11 to 3.3V (or 5V) on Raspberry Pi
2. Connect GND pin of DHT11 to GND on Raspberry Pi
3. Connect DATA pin of DHT11 to GPIO4 (Pin 7) on Raspberry Pi
4. Connect a 10K ohm resistor between the DATA pin and VCC (as a pull-
up)(optional)
5.
Install libraries:
# Update your Pi
sudo apt-get update
sudo apt-get upgrade
# Install Python libraries for DHT11 and Bluetooth
sudo apt-get install python3-pip python3-dev python3-bluetooth bluetooth bluez
sudo pip3 install Adafruit_DHT [Link]
Create the Python Script
import Adafruit_DHT
import bluetooth
import time
# ----- SETUP -----
# Sensor
dht = Adafruit_DHT.DHT11
pin = 4 # GPIO4
# Bluetooth
bt = [Link]([Link])
[Link](("", bluetooth.PORT_ANY))
[Link](1)
# Advertise service
port = [Link]()[1]
bluetooth.advertise_service(
bt,
"TempMonitor",
service_id="00001101-0000-1000-8000-00805F9B34FB",
service_classes=["00001101-0000-1000-8000-00805F9B34FB"],
profiles=[bluetooth.SERIAL_PORT_PROFILE]
print(f"Ready! Waiting on channel {port}")
# ----- MAIN LOOP -----
try:
# Wait for phone to connect
print("Waiting for phone connection...")
phone, addr = [Link]()
print(f"Phone connected: {addr}")
# Send sensor data continuously
while True:
# Read sensor
h, t = Adafruit_DHT.read_retry(dht, pin)
# Create message
if h is not None and t is not None:
msg = f"T:{t:.1f}°C H:{h:.1f}%\n"
else:
msg = "Sensor Error\n"
# Send data
[Link](msg)
print(f"Sent: {[Link]()}")
[Link](2)
except KeyboardInterrupt:
print("Stopped by user")
finally:
# Clean up
try:
[Link]()
except:
pass
[Link]()
print("Done!")
Make the Script Executable and Run It
# Make the script executable
chmod +x dht11_bluetooth.py
# Run the script
sudo python3 dht11_bluetooth.py
Connect with a Smartphone App
you can use a third-party app to view the data:
1. For Android:
o Install "Serial Bluetooth Terminal" from Google Play Store
o Pair your phone with the Raspberry Pi in your phone's Bluetooth settings
o Open Serial Bluetooth Terminal
o Tap the menu (three dots) and select "Devices"
o Select your Raspberry Pi from the list
o The app will connect and start displaying the sensor data
If u want the easier Arduino ver:
you will need the following components:
• DHT11 temperature and humidity sensor
• HC-06 Bluetooth module
• Arduino board
• Jumper wires
• Smartphone with Bluetooth capabilities
• A software or an application on your smartphone that can receive the data
sent by the Arduino.
Code:
#include <SoftwareSerial.h>
#include <dht11.h>
#define DHT11PIN 4 // broche DATA -> broche 4
dht11 DHT11;
SoftwareSerial hc06(2,3);
void setup(){
[Link](9600);
}
void loop(){
[Link](DHT11PIN);
delay(1000);
// Send temperature and humidity separated by comma or any delimiter
[Link]((float)[Link]);
[Link](",");
[Link]((float)[Link]);
[Link](); // Send newline for easier parsing
Download Serial Bluetooth Terminal on your Phone Then:
1. Turn ON Bluetooth on your phone.
2. Go to Bluetooth Settings on your phone.
3. Scan for new devices.
4. Find “HC-06” (or similar name).
5. Tap to pair.
6. If prompted, enter the pairing code: usually 1234 or 0000
Connect via Serial Bluetooth Terminal
1. Open Serial Bluetooth Terminal app.
2. Tap the menu (≡) icon at the top.
3. Tap “Devices”.
4. Find and tap “HC-06” in the list.
5. Wait for the status to show “Connected”.
6. Once connected, you’ll see data (like 25.00,60.00 or T:25.00
H:60.00) appear in the main terminal window every second.