0% found this document useful (0 votes)
60 views

Electronics-1 Practicals

The document describes programming a Raspberry Pi to control LEDs, get feedback from a switch, detect temperature using a sensor, detect light intensity using a photocell sensor, and detect motion using a PIR sensor. Code examples in Python are provided for each application.

Uploaded by

crunchyrull2
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)
60 views

Electronics-1 Practicals

The document describes programming a Raspberry Pi to control LEDs, get feedback from a switch, detect temperature using a sensor, detect light intensity using a photocell sensor, and detect motion using a PIR sensor. Code examples in Python are provided for each application.

Uploaded by

crunchyrull2
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/ 13

1. Programming of Raspberry Pi to control LEDs attached to the GPIO pins.

Aim:
The aim of this experiment is to program a Raspberry Pi to control LEDs attached to its GPIO (General
Purpose Input Output) pins.

Apparatus:
1. Raspberry Pi (any model with GPIO pins)
2. LEDs (as many as required for the experiment)
3. Resistors (to limit the current to the LEDs)
4. Breadboard
5. Jumper wires
6. Computer with a terminal to write and execute the Python code
7. Micro SD card with Raspbian OS installed

Observation:
1. Establish the circuit by connecting the LEDs to the GPIO pins of the Raspberry Pi via the
breadboard. Ensure proper polarity and use resistors to limit the current to prevent
burning the LEDs.
2. Write Python code to control the GPIO pins. Use a library like RPi.GPIO to interact with
the GPIO pins.
3. Test the code by running it on the Raspberry Pi.
4. Observe the behavior of the LEDs based on the code execution.
5. Check if the LEDs turn on and off as per the programmed instructions.

Conclusion:
Programming the Raspberry Pi to control LEDs via GPIO pins is a straightforward
process. By properly configuring the GPIO pins and using Python code, we can control
the state of the LEDs. The GPIO pins can be set as output pins to provide voltage to the
LEDs, turning them on, or set as input pins to cut off the voltage, turning them off.

Result:
The Raspberry Pi successfully controlled the LEDs attached to its GPIO pins. By
executing the Python code, we were able to turn the LEDs on and off, demonstrating
the ability to control external hardware using the Raspberry Pi. This experiment
highlights the versatility and utility of Raspberry Pi in various embedded systems and
IoT applications.

Program:
import RPi.GPIO as GPIO
import time
# Set the GPIO mode
GPIO.setmode(GPIO.BCM)

# Define the GPIO pin for the LED


led_pin = 17

# Set up the GPIO pin as output


GPIO.setup(led_pin, GPIO.OUT)

try:
# Turn the LED on
GPIO.output(led_pin, GPIO.HIGH)
print("LED turned on")
time.sleep(2) # Wait for 2 seconds

# Turn the LED off


GPIO.output(led_pin, GPIO.LOW)
print("LED turned off")
time.sleep(2) # Wait for 2 seconds

except KeyboardInterrupt:
print("Exiting program")

finally:
# Clean up GPIO settings
GPIO.cleanup()
2. Programming of Raspberry Pi to get feedback from a switch connected to the
GPIO

Aim:
To program a Raspberry Pi to receive feedback from a switch connected to its GPIO pin.

Apparatus:
1. Raspberry Pi (any model with GPIO pins)
2. Jumper wires
3. Breadboard
4. Momentary switch (push button)
5. Resistors (optional, depending on switch type)
Observation:
We will observe whether the Raspberry Pi successfully detects the state changes of the switch
connected to its GPIO pin.

Conclusion:
Based on the behavior of the Raspberry Pi when the switch is pressed or released, we will conclude
whether the programming and hardware setup are correct.
Result:
If the Raspberry Pi registers the state changes of the switch (pressed or released) as expected, the
experiment is successful. Otherwise, we need to troubleshoot and make necessary adjustments to the
code or hardware setup.
Analysis:

1. If the terminal outputs "Switch pressed" when the switch is pressed and "Switch released" when
released, the program is working correctly.
2. If there's no response or unexpected behavior, double-check the hardware connections and the code
for errors.
3. Troubleshoot any issues encountered and make necessary adjustments until the desired feedback is
achieved.
Program:

import RPi.GPIO as GPIO


import time

# Set GPIO mode


GPIO.setmode(GPIO.BCM)
# Define GPIO pin connected to the switch
switch_pin = 17

# Setup switch_pin as input with pull-up resistor


GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Main loop
try:
while True:
# Check state of the switch
if GPIO.input(switch_pin) == GPIO.LOW:
print("Switch pressed")
else:
print("Switch released")
time.sleep(0.1) # Debouncing delay
except KeyboardInterrupt:
GPIO.cleanup() # Cleanup GPIO on Ctrl+C exit
3. Programming of Raspberry Pi to detect temperature using temperature
sensor.

Aim:
The aim of this project is to utilize a Raspberry Pi to detect temperature using a temperature sensor.
This involves programming the Raspberry Pi to interface with the sensor, read temperature
data, and display or log the results.

Apparatus:
1. Raspberry Pi (any model with GPIO pins)
2. DS18B20 temperature sensor (or any compatible temperature sensor)
3. Breadboard and jumper wires for circuit connections
4. MicroSD card with Raspbian OS installed
5. Computer with SSH client (optional for remote access)
6. HDMI display, keyboard, and mouse (optional for local setup)

Observation:
1. Setup the Raspberry Pi environment by connecting the necessary peripherals (HDMI display, keyboard,
mouse) or accessing it remotely via SSH.
2. Connect the DS18B20 temperature sensor to the Raspberry Pi's GPIO pins using the breadboard and
jumper wires. Refer to the sensor datasheet or online resources for pin connections.
3. Write a Python script to interact with the temperature sensor. Utilize libraries like RPi.GPIO or GPIO
Zero for GPIO control and the sensor's datasheet for communication protocol specifics.
4. Program the Raspberry Pi to read temperature data from the sensor at regular intervals.
5. Display the temperature data on the screen or log it to a file for further analysis.

Conclusion:
The Raspberry Pi successfully interfaces with the DS18B20 temperature sensor and accurately detects
temperature changes. The Python script effectively reads temperature data from the sensor and
displays it on the screen or logs it for future reference. This project demonstrates the capability of
Raspberry Pi for environmental monitoring applications.

Result:
The result of this project is a functioning system where the Raspberry Pi detects temperature using the
DS18B20 sensor. The temperature readings can be observed in real-time or logged for analysis over
time. This project provides a foundation for building more complex environmental monitoring systems
using Raspberry Pi and other sensors.
Program:
import os
import glob
import time

# Load kernel modules


os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

# Define path to the temperature sensor


base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

# Function to read raw temperature data


def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines

# Function to parse temperature from raw data


def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c, temp_f

# Main program loop


while True:
temp_c, temp_f = read_temp()
print('Temperature in Celsius: {:.2f} °C'.format(temp_c))
print('Temperature in Fahrenheit: {:.2f} °F'.format(temp_f))
time.sleep(1) # Adjust the delay as needed
4. Programming of Raspberry Pi to detect light intensity using photocell sensor.

Aim:
The aim of this project is to utilize a Raspberry Pi to detect light intensity using a photocell sensor.

Apparatus:
1. Raspberry Pi (any model with GPIO pins)
2. Photocell sensor (also known as a light-dependent resistor or LDR)
3. Resistor (10kΩ)
4. Breadboard and jumper wires

Observation:
By measuring the resistance of the photocell sensor, we can infer the light intensity falling on it. The resistance
decreases with increasing light intensity and vice versa.

Conclusion:
By interfacing a photocell sensor with a Raspberry Pi and monitoring the resistance changes, we can
effectively detect changes in light intensity.

Result:
The Raspberry Pi will be programmed to read the analog signal from the photocell sensor and convert it to a
digital value, which can then be used to determine the light intensity.

Program:
import RPi.GPIO as GPIO
import time

# Set GPIO mode to BCM


GPIO.setmode(GPIO.BCM)

# Define GPIO pin connected to photocell sensor


photocell_pin = 18

def read_light_intensity():
# Setup photocell_pin as input
GPIO.setup(photocell_pin, GPIO.IN)
# Allow some time for the photocell to stabilize
time.sleep(0.1)
# Read analog value from photocell sensor
analog_value = GPIO.input(photocell_pin)
return analog_value

try:
while True:
# Read light intensity
light_intensity = read_light_intensity()
print("Light Intensity:", light_intensity)
time.sleep(1) # Read every 1 second

except KeyboardInterrupt:
GPIO.cleanup()
5. Programming of Raspberry Pi for Motion detection

Aim:
To create a motion detection system using a Raspberry Pi and a PIR sensor.
Apparatus:
1. Raspberry Pi (any model with GPIO pins)
2. PIR sensor module
3. Breadboard and jumper wires
4. MicroSD card with Raspbian OS
5. Monitor, keyboard, and mouse for initial setup (optional)

Observation:
The PIR sensor detects motion by sensing changes in infrared radiation within its field of view. When motion is
detected, the sensor sends a signal to the Raspberry Pi, which can trigger actions such as taking a picture or
sending an alert.

Conclusion:
By setting up a Raspberry Pi with a PIR sensor, we can create a simple motion detection system suitable for
various applications, such as home security, automation, or monitoring.

Result:
Upon detecting motion, the Raspberry Pi can perform various actions, such as:
1. Sending an email or SMS alert
2. Capturing images or videos
3. Turning on lights or activating other devices
Program:
import RPi.GPIO as GPIO
import time

# Set up GPIO
PIR_PIN = 14
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_PIN, GPIO.IN)

def motion_detected(channel):
print("Motion detected!")
# Add your desired actions here (e.g., send email, capture image)

try:
print("Motion detection system started...")
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=motion_detected)
while True:
time.sleep(1)

except KeyboardInterrupt:
print("Motion detection stopped by user")
GPIO.cleanup()
6. Programming of Raspberry Pi for image detection.

Aim:
The aim of this project is to develop a system capable of detecting objects in images using a Raspberry
Pi and a camera module.
Apparatus:
1. Raspberry Pi (any model with GPIO pins)
2. Raspberry Pi Camera Module or USB webcam
3. Internet connection (optional, depending on requirements)
4. Computer with SSH client (optional, for remote access)
5. Power supply for Raspberry Pi
6. HDMI monitor/keyboard/mouse (optional, for setup)
Observation:
1. The system should be able to capture images using the camera module.
2. The captured images should be processed to detect objects using a suitable image detection algorithm.
3. Detected objects should be highlighted or marked in some way on the captured image.
4. The system should provide feedback or output indicating the detected objects.
Conclusion:
1. The project aims to demonstrate the capability of a Raspberry Pi to perform image detection tasks.
2. The effectiveness of the system will depend on the accuracy of the image detection algorithm used and
the processing power of the Raspberry Pi.
Result:
1. The result of the project will be a working prototype of an image detection system using a Raspberry
Pi.
2. The system should be able to detect objects in real-time or near real-time, depending on the
processing speed of the Raspberry Pi.
Program:
import cv2

# Load pre-trained model for object detection (e.g., YOLO, SSD, etc.)
# Make sure to install necessary libraries and download pre-trained model weights

def detect_objects(image):
# Perform object detection on the input image
# You'll need to implement this part using OpenCV or other libraries

# Example:
# detected_objects = model.detect(image)
# return detected_objects

pass

def mark_detected_objects(image, detected_objects):


# Mark detected objects on the input image
# You'll need to implement this part using OpenCV or other libraries

# Example:
# for obj in detected_objects:
# cv2.rectangle(image, obj.bounding_box, (0, 255, 0), 2)

pass

def main():
# Initialize the camera
cap = cv2.VideoCapture(0)

while True:
# Capture frame-by-frame
ret, frame = cap.read()

# Perform object detection


detected_objects = detect_objects(frame)

# Mark detected objects on the frame


marked_frame = mark_detected_objects(frame, detected_objects)

# Display the resulting frame


cv2.imshow('Image Detection', marked_frame)

# Check for 'q' key to exit


if cv2.waitKey(1) & 0xFF == ord('q'):
break

# Release the capture


cap.release()
cv2.destroyAllWindows()

if __name__ == "__main__":
main()

You might also like