0% found this document useful (0 votes)
15 views39 pages

IoT Lab Manual

The document outlines a series of experiments for hands-on learning with Raspberry Pi, covering basic Linux commands, Python programming, and hardware control. It includes detailed instructions for running Python programs that perform various tasks, such as arithmetic operations, string analysis, and area calculations for different shapes. Additionally, it emphasizes the importance of practical experience with sensors and controlling devices through the Raspberry Pi.
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)
15 views39 pages

IoT Lab Manual

The document outlines a series of experiments for hands-on learning with Raspberry Pi, covering basic Linux commands, Python programming, and hardware control. It includes detailed instructions for running Python programs that perform various tasks, such as arithmetic operations, string analysis, and area calculations for different shapes. Additionally, it emphasizes the importance of practical experience with sensors and controlling devices through the Raspberry Pi.
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/ 39

LIST OF EXPERIMENTS

Sr. No Experiment Page No.

Start Raspberry Pi and try various Linix commands in command 1


1.
terminal window:
ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more, less, ps,
sudo, cron, chown, chgrp, ping etc.

Run some python programs on Pi like: 2


2.
a) Read your name and print Hello message with name
b) Read two numbers and print their sum, difference, product and
division.
c) Word and character count of a given string.
d) Area of a given shape (rectangle, triangle and circle) reading
shape and appropriate values from standard input.

Run some python programs on Pi like: 5


3.
a) Print a name 'n' times, where name and n are read from
standard input, using for and while loops.
b) Handle Divided by Zero Exception.
c) Print current time for 10 times with an interval of 10 seconds.
d) Read a file line by line and print the word count of each line.

a) Light an LED through Python program 8


4.
b) Get input from two switches and switch on corresponding LEDs
c) Flash an LED at a given on time and off time cycle, where the two
times are taken from a file.

a) Flash an LED based on cron output (acts as an alarm) 11


5.
b) Switch on a relay at a given time using cron, where the relay's
contact terminals are connected to a load.
c) Get the status of a bulb at a remote place (on the LAN) through
web.

The student should have hands on experience in using various sensors 14


6.
like temperature, humidity, smoke, light, etc. and should be able to
use control web camera, network, and relays connected to the Pi.
EXPERIMENT-1

1. Start Raspberry Pi and try various Linux commands in command


terminal window: ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip,
cat, more, less, ps, sudo, cron, chown, chgrp, ping etc.

Starting up your Raspberry Pi and trying various Linux commands in the terminal is a great
way to get hands-on experience with the Linux environment. Here’s a detailed guide with steps
to start up your Raspberry Pi and examples of the commands you mentioned:

1. Setting up the Raspberry Pi

 Power on the Raspberry Pi: Connect your Raspberry Pi to a monitor, keyboard, mouse,
and plug in the power supply.
 Booting up: When you turn on your Raspberry Pi, it should boot into Raspberry Pi OS
(formerly Raspbian). If you are using a different OS, the process may vary slightly, but
this guide assumes you are using Raspberry Pi OS.
 Login: After booting, the login screen will appear. The default login for Raspberry Pi OS
is:
o Username: pi
o Password: raspberry

Once logged in, you should see the command line terminal window.

2. Opening the Command Terminal

 If you are using the GUI on Raspberry Pi OS, open the Terminal by clicking the
Terminal icon on the desktop or by pressing Ctrl + Alt + T.
 If you are operating headless (without a monitor), you will need to SSH into your
Raspberry Pi. (More on SSH below.)

3. Basic Linux Commands in Terminal

Here’s a breakdown of each command you mentioned with examples.

1. ls – List Files and Directories

The ls command lists files and directories in the current working directory.

 To use it:

bash
CopyEdit

Department of Engineering & Technology 1


ls

 Options:
o ls -l (long listing with permissions, owner, and timestamp)
o ls -a (includes hidden files)
o ls -lh (human-readable sizes)

2. cd – Change Directory

The cd command allows you to navigate between directories.

 To go to a specific directory:

bash
CopyEdit
cd /home/pi/Documents

 To go back to your home directory:

bash
CopyEdit
cd ~

 To move up one directory:

bash
CopyEdit
cd ..

3. touch – Create an Empty File

The touch command creates an empty file or updates the timestamp of an existing file.

 Example:

bash
CopyEdit
touch myfile.txt

4. mv – Move or Rename Files

The mv command is used to move files or rename them.

 To rename a file:

bash
CopyEdit
mv oldname.txt newname.txt

Department of Engineering & Technology 2


 To move a file:

bash
CopyEdit
mv myfile.txt /home/pi/Documents/

5. rm – Remove Files or Directories

The rm command is used to remove files or directories.

 To remove a file:

bash
CopyEdit
rm myfile.txt

 To remove a directory (and all its contents):

bash
CopyEdit
rm -r mydir/

 To remove a file without confirmation:

bash
CopyEdit
rm -f myfile.txt

6. man – Manual Pages for Commands

The man command provides the manual or help page for a command.

 To get help about a command (e.g., ls):

bash
CopyEdit
man ls

 To exit the manual page: Press q.

7. mkdir – Make Directory

The mkdir command creates a new directory.

 Example:

bash
CopyEdit
mkdir newfolder

Department of Engineering & Technology 3


8. rmdir – Remove Directory

The rmdir command removes an empty directory.

 Example:

bash
CopyEdit
rmdir myfolder

9. tar – Create and Extract Tar Archive Files

The tar command is used to compress or extract tarball files.

 To create a tarball:

bash
CopyEdit
tar -cvf archive.tar /path/to/folder

 To extract a tarball:

bash
CopyEdit
tar -xvf archive.tar

10. gzip – Compress Files

The gzip command is used to compress files.

 To compress a file:

bash
CopyEdit
gzip filename.txt

 This will compress the file and replace it with a .gz version (e.g., filename.txt.gz).

11. cat – Concatenate and Display File Contents

The cat command displays the content of a file.

 Example:

bash
CopyEdit
cat myfile.txt

12. more – View File Content with Pagination


Department of Engineering & Technology 4
The more command lets you view file contents one page at a time.

 Example:

bash
CopyEdit
more myfile.txt

 Press Space to scroll down, and q to quit.

13. less – View File Content with Enhanced Navigation

Similar to more, but with better navigation.

 Example:

bash
CopyEdit
less myfile.txt

 Use the arrow keys or PgUp/PgDn to navigate, and q to quit.

14. ps – Display Running Processes

The ps command shows information about running processes.

 To view the current user’s processes:

bash
CopyEdit
ps

 To view all processes:

bash
CopyEdit
ps aux

15. sudo – Execute Commands as Superuser

The sudo command allows you to execute commands with superuser (root) privileges.

 Example:

bash
CopyEdit
sudo apt update

16. cron – Task Scheduler


Department of Engineering & Technology 5
The cron command is used to schedule tasks.

 To edit cron jobs:

bash
CopyEdit
crontab -e

 A simple cron job to run a script every day at 2 AM:

bash
CopyEdit
0 2 * * * /path/to/script.sh

17. chown – Change Ownership of a File

The chown command changes the owner of a file.

 Example:

bash
CopyEdit
sudo chown user:group myfile.txt

18. chgrp – Change Group Ownership of a File

The chgrp command changes the group ownership of a file.

 Example:

bash
CopyEdit
sudo chgrp groupname myfile.txt

19. ping – Test Network Connectivity

The ping command checks the network connection to a server or device.

 Example:

bash
CopyEdit
ping google.com

 To stop the ping command, press Ctrl + C.

4. Additional Tips
Department of Engineering & Technology 6
 SSH into Raspberry Pi: If you’re running the Pi headless (without a monitor), you can
access the terminal remotely over the network using SSH. First, enable SSH from the
Raspberry Pi’s settings or use sudo raspi-config. Then, from another machine:

bash
CopyEdit
ssh pi@<your-pi-ip-address>

 Accessing Help: Always use man <command> or <command> --help to get detailed
information about any command.
 Basic File Permissions: Learn about chmod (change file permissions) and chown for
managing file access and ownership.

Department of Engineering & Technology 7


EXPERIMENT-2
2. Run some python programs on Pi like:
a) Read your name and print Hello message with name
b) Read two numbers and print their sum, difference, product and
division.
c) Word and character count of a given string.
d) Area of a given shape (rectangle, triangle and circle) reading shape
and appropriate values from standard input.

Prerequisites:

1. Raspberry Pi Setup: Ensure your Raspberry Pi is up and running with Raspberry Pi OS


installed.
2. Python: Python is usually pre-installed on Raspberry Pi OS. You can check the version
by typing:

bash
CopyEdit
python3 --version

Step-by-Step Guide to Running Python Programs on Raspberry Pi

a) Read your name and print a "Hello" message with your name

Program:

1. Open a terminal on your Raspberry Pi or connect to it via SSH.


2. Create a new Python file. You can use nano or vim text editor:

bash
CopyEdit
nano hello.py

3. Write the following Python code:

python
CopyEdit
# Program to print hello message with name

# Read name from user


name = input("Enter your name: ")

Department of Engineering & Technology 8


# Print greeting message
print(f"Hello, {name}!")

4. Save the file (in nano, press Ctrl + X, then Y to confirm saving).
5. Run the program:

bash
CopyEdit
python3 hello.py

Expected Output:

yaml
CopyEdit
Enter your name: John
Hello, John!

b) Read two numbers and print their sum, difference, product, and division

Program:

1. Open a terminal and create a new Python file:

bash
CopyEdit
nano calculator.py

2. Write the following Python code:

python
CopyEdit
# Program to perform arithmetic operations on two numbers

# Read two numbers from user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Perform arithmetic operations


sum_result = num1 + num2
diff_result = num1 - num2
prod_result = num1 * num2
div_result = num1 / num2 if num2 != 0 else "Undefined (division by
zero)"

# Print results
print(f"Sum: {sum_result}")
print(f"Difference: {diff_result}")
print(f"Product: {prod_result}")
print(f"Division: {div_result}")

Department of Engineering & Technology 9


3. Save the file (in nano, press Ctrl + X, then Y to confirm saving).
4. Run the program:

bash
CopyEdit
python3 calculator.py

Example Output:

yaml
CopyEdit
Enter the first number: 10
Enter the second number: 5
Sum: 15.0
Difference: 5.0
Product: 50.0
Division: 2.0

c) Word and character count of a given string

Program:

1. Open a terminal and create a new Python file:

bash
CopyEdit
nano word_char_count.py

2. Write the following Python code:

python
CopyEdit
# Program to count words and characters in a string

# Read string from user


input_string = input("Enter a string: ")

# Count words and characters


word_count = len(input_string.split())
char_count = len(input_string.replace(" ", "")) # Exclude spaces

# Print results
print(f"Word Count: {word_count}")
print(f"Character Count (excluding spaces): {char_count}")

3. Save the file (in nano, press Ctrl + X, then Y to confirm saving).
4. Run the program:

bash
CopyEdit
python3 word_char_count.py

Department of Engineering & Technology 10


Example Output:

mathematica
CopyEdit
Enter a string: Hello, how are you doing today?
Word Count: 6
Character Count (excluding spaces): 26

d) Area of a given shape (rectangle, triangle, and circle) reading shape and
appropriate values from standard input

Program:

1. Open a terminal and create a new Python file:

bash
CopyEdit
nano area_calculator.py

2. Write the following Python code:

python
CopyEdit
# Program to calculate area of rectangle, triangle, or circle

# Read shape type from user


shape = input("Enter the shape (rectangle, triangle, circle): ").lower()

if shape == 'rectangle':
# Read length and breadth
length = float(input("Enter the length of the rectangle: "))
breadth = float(input("Enter the breadth of the rectangle: "))
area = length * breadth
print(f"The area of the rectangle is {area} square units.")

elif shape == 'triangle':


# Read base and height
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print(f"The area of the triangle is {area} square units.")

elif shape == 'circle':


# Read radius
radius = float(input("Enter the radius of the circle: "))
area = 3.14159 * radius * radius
print(f"The area of the circle is {area} square units.")

else:
print("Invalid shape entered.")

3. Save the file (in nano, press Ctrl + X, then Y to confirm saving).

Department of Engineering & Technology 11


4. Run the program:

bash
CopyEdit
python3 area_calculator.py

Example Output:

mathematica
CopyEdit
Enter the shape (rectangle, triangle, circle): rectangle
Enter the length of the rectangle: 5
Enter the breadth of the rectangle: 3
The area of the rectangle is 15.0 square units.

Another example for a triangle:

mathematica
CopyEdit
Enter the shape (rectangle, triangle, circle): triangle
Enter the base of the triangle: 4
Enter the height of the triangle: 6
The area of the triangle is 12.0 square units.

Explanation of Concepts in Python Used Here:

1. input(): This function takes input from the user. It returns the value as a string, which
can be converted into other data types like integers or floats as needed.
2. float(): Converts a string to a floating-point number, which is useful when performing
arithmetic.
3. String Manipulation: Methods like split() (for splitting words) and replace() (for
removing spaces) are used to analyze the string data.
4. Conditional Statements (if-elif-else): Used to execute different code based on the
user's choice of shape in the area program.
5. Basic Arithmetic Operations: Used to perform calculations such as sum, difference, and
product.
6. Mathematical Formulae: The area of different shapes is calculated using standard
formulas (e.g., area of rectangle = length * breadth, area of triangle = 0.5 * base *
height).

Department of Engineering & Technology 12


EXPERIMENT-3

3. Run some python programs on Pi like:


a) Print a name 'n' times, where name and n are read from standard
input, using for and while loops.
b) Handle Divided by Zero Exception.
c) Print current time for 10 times with an interval of 10 seconds.
d) Read a file line by line and print the word count of each line.

a) Print a name 'n' times, where the name and n are read from standard input,
using for and while loops

Steps:

1. Create a new Python file: Open a terminal on your Raspberry Pi and create a new
Python file using the nano text editor:

bash
CopyEdit
nano print_name.py

2. Write the Python code: Copy and paste the following Python code to print the name n
times using both for and while loops:

python
CopyEdit
# Program to print a name 'n' times using for and while loops

# Read name and number of times to print from user


name = input("Enter your name: ")
n = int(input("Enter how many times to print your name: "))

# Using for loop


print("\nUsing for loop:")
for i in range(n):
print(name)

# Using while loop


print("\nUsing while loop:")
count = 0
while count < n:
print(name)
count += 1

Department of Engineering & Technology 13


3. Save the file: In nano, press Ctrl + X, then press Y to confirm saving, and hit Enter to
save the file.
4. Run the program: Run the Python program using the following command:

bash
CopyEdit
python3 print_name.py

Expected Output (Example with name "John" and n=3):

vbnet
CopyEdit
Enter your name: John
Enter how many times to print your name: 3

Using for loop:


John
John
John

Using while loop:


John
John
John

b) Handle Division by Zero Exception

Steps:

1. Create a new Python file: Open a terminal and create a new Python file:

bash
CopyEdit
nano divide_numbers.py

2. Write the Python code: Copy and paste the following Python code to handle division by
zero exception:

python
CopyEdit
# Program to handle division by zero exception

try:
# Read numbers from user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Try dividing the numbers


result = num1 / num2
print(f"The result of {num1} divided by {num2} is {result}")

Department of Engineering & Technology 14


except ZeroDivisionError:
print("Error: Cannot divide by zero!")

except ValueError:
print("Error: Please enter valid numbers.")

3. Save the file: In nano, press Ctrl + X, then press Y to confirm saving, and hit Enter to
save the file.
4. Run the program: Run the Python program using the following command:

bash
CopyEdit
python3 divide_numbers.py

Expected Output:

o If dividing by zero:

yaml
CopyEdit
Enter the first number: 10
Enter the second number: 0
Error: Cannot divide by zero!

o If valid division:

sql
CopyEdit
Enter the first number: 10
Enter the second number: 2
The result of 10.0 divided by 2.0 is 5.0

c) Print current time for 10 times with an interval of 10 seconds

Steps:

1. Create a new Python file: Open a terminal and create a new Python file:

bash
CopyEdit
nano print_time.py

2. Write the Python code: Copy and paste the following Python code to print the current
time 10 times with an interval of 10 seconds:

python
CopyEdit
# Program to print current time 10 times with an interval of 10 seconds

import time

Department of Engineering & Technology 15


from datetime import datetime

# Loop to print current time 10 times


for i in range(10):
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f"Current time ({i+1}): {current_time}")
time.sleep(10) # Wait for 10 seconds before printing again

3. Save the file: In nano, press Ctrl + X, then press Y to confirm saving, and hit Enter to
save the file.
4. Run the program: Run the Python program using the following command:

bash
CopyEdit
python3 print_time.py

Expected Output:

sql
CopyEdit
Current time (1): 2025-02-10 14:20:25
Current time (2): 2025-02-10 14:20:35
Current time (3): 2025-02-10 14:20:45
...

Each time, it prints the current time with a 10-second interval.

d) Read a file line by line and print the word count of each line

Steps:

1. Create a new Python file: Open a terminal and create a new Python file:

bash
CopyEdit
nano word_count_in_file.py

2. Create a sample text file (if you don't have a file yet): In the terminal, create a text file
to test the program. For example:

bash
CopyEdit
nano sample.txt

Add some lines of text and save it.

Sample content for sample.txt:

Department of Engineering & Technology 16


kotlin
CopyEdit
Hello, how are you?
I am learning Python.
Raspberry Pi is fun!

3. Write the Python code: Copy and paste the following Python code to read the file line
by line and count words in each line:

python
CopyEdit
# Program to read file line by line and print word count of each line

# Open the file


filename = "sample.txt"
try:
with open(filename, 'r') as file:
line_number = 1
for line in file:
word_count = len(line.split())
print(f"Line {line_number}: {word_count} words")
line_number += 1

except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")

4. Save the file: In nano, press Ctrl + X, then press Y to confirm saving, and hit Enter to
save the file.
5. Run the program: Run the Python program using the following command:

bash
CopyEdit
python3 word_count_in_file.py

Expected Output (if sample.txt contains the example text):

yaml
CopyEdit
Line 1: 4 words
Line 2: 3 words
Line 3: 4 words

Explanation of Key Concepts in the Programs

 input(): Reads input from the user. In some cases, we convert it to an integer or float
using int() or float() for calculations.
 Loops:
o for loop is used to iterate a specific number of times (e.g., printing the name
multiple times).

Department of Engineering & Technology 17


o while loop can be used for a condition-based iteration (e.g., printing the name
until a counter reaches n).
 Exception Handling:
o try-except block is used to handle errors like division by zero
(ZeroDivisionError) or invalid input (ValueError).
 time.sleep(): Pauses the program for a specified number of seconds. Used in the time-
printing example.
 datetime.now(): Fetches the current date and time.
 File Handling:
o open() is used to read a file.
o with automatically closes the file after the block of code is executed.
o split() splits a line of text into words based on spaces.

Department of Engineering & Technology 18


EXPERIMENT-4

4. a) Light an LED through Python program


b) Get input from two switches and switch on corresponding LEDs
c) Flash an LED at a given on time and off time cycle, where the two times
are taken from a file.

Prerequisites:

1. Hardware Setup:
o Raspberry Pi (any model with GPIO pins will work)
o LEDs (preferably 5mm or 3mm standard LEDs)
o Resistors (typically 220Ω or 330Ω for each LED)
o Push buttons (Switches) (optional for part b)
o Breadboard and jumper wires
o Raspberry Pi GPIO pins for control
2. Software Setup:
o Install GPIO library on your Raspberry Pi if it’s not already installed. The
library allows Python programs to interface with the GPIO pins.

bash
CopyEdit
sudo apt-get update
sudo apt-get install python3-rpi.gpio

a) Light an LED through a Python Program

In this part, we will write a Python program to light up an LED on the Raspberry Pi.

Steps:

1. Hardware Setup:
o Connect the anode (long leg) of the LED to one of the GPIO pins (for example,
GPIO17).
o Connect the cathode (short leg) of the LED to one end of a 220Ω resistor.
o Connect the other end of the resistor to a ground (GND) pin on the Raspberry Pi.
2. Write the Python Program:

o Open a terminal on your Raspberry Pi and create a new Python file:

bash
CopyEdit
nano led_on.py

Department of Engineering & Technology 19


o Write the following Python code to turn on an LED:

python
CopyEdit
import RPi.GPIO as GPIO
import time

# Set the GPIO mode to BCM (Broadcom pin-numbering)


GPIO.setmode(GPIO.BCM)

# Set GPIO pin 17 as an output pin


LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)

# Turn on the LED


GPIO.output(LED_PIN, GPIO.HIGH)
print("LED is ON")
time.sleep(5) # Keep the LED on for 5 seconds

# Turn off the LED


GPIO.output(LED_PIN, GPIO.LOW)
print("LED is OFF")

# Clean up GPIO settings


GPIO.cleanup()

3. Run the Program: Save and close the file (press Ctrl + X, then Y to save, and Enter to
confirm). Run the program:

bash
CopyEdit
python3 led_on.py

Expected Output:

o The LED will turn on for 5 seconds, and then turn off.

b) Get Input from Two Switches and Switch on Corresponding LEDs

In this part, we will read the state of two switches (buttons) and use them to control two LEDs.

Steps:

1. Hardware Setup:
o Connect Switch 1 between GPIO17 and ground (GND).
o Connect Switch 2 between GPIO27 and ground (GND).
o Connect LED 1 to GPIO17 (as before).
o Connect LED 2 to GPIO27.
2. Write the Python Program:

Department of Engineering & Technology 20


o Open a terminal on your Raspberry Pi and create a new Python file:

bash
CopyEdit
nano switch_led_control.py

o Write the following Python code to monitor two switches and control LEDs:

python
CopyEdit
import RPi.GPIO as GPIO
import time

# Set the GPIO mode to BCM (Broadcom pin-numbering)


GPIO.setmode(GPIO.BCM)

# Pin assignments
SWITCH_1 = 17
SWITCH_2 = 27
LED_1 = 17
LED_2 = 27

# Setup GPIO pins as input (switches) or output (LEDs)


GPIO.setup(SWITCH_1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(SWITCH_2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(LED_1, GPIO.OUT)
GPIO.setup(LED_2, GPIO.OUT)

try:
while True:
# Read the state of the switches
switch_1_state = GPIO.input(SWITCH_1)
switch_2_state = GPIO.input(SWITCH_2)

# Control the LEDs based on switch states


if switch_1_state == GPIO.LOW:
GPIO.output(LED_1, GPIO.HIGH) # Turn on LED 1
else:
GPIO.output(LED_1, GPIO.LOW) # Turn off LED 1

if switch_2_state == GPIO.LOW:
GPIO.output(LED_2, GPIO.HIGH) # Turn on LED 2
else:
GPIO.output(LED_2, GPIO.LOW) # Turn off LED 2

time.sleep(0.1) # Small delay to avoid bouncing

except KeyboardInterrupt:
# Clean up GPIO settings when the program is interrupted
GPIO.cleanup()

3. Run the Program: Save and close the file (press Ctrl + X, then Y to save, and Enter to
confirm). Run the program:

Department of Engineering & Technology 21


bash
CopyEdit
python3 switch_led_control.py

How It Works:

o When you press Switch 1, LED 1 will turn on, and it will turn off when you
release the button.
o Similarly, when you press Switch 2, LED 2 will turn on, and it will turn off when
you release the button.

c) Flash an LED at a Given On Time and Off Time Cycle, Where the Two Times
Are Taken from a File

In this part, we will read an LED flashing cycle (on time and off time) from a file, and then flash
the LED according to the specified times.

Steps:

1. Create a Configuration File:


o Create a file flash_times.txt that contains the on time and off time in seconds.
The format of the file is:

CopyEdit
2 1

Here, 2 is the on time (in seconds), and 1 is the off time (in seconds).

2. To create this file:


3. bash
4. CopyEdit
5. nano flash_times.txt
6. Enter:
7. CopyEdit
8. 2 1
9. Save the file by pressing Ctrl + X, then Y to confirm, and Enter to save.
10. Write the Python Program:

o Open a terminal and create a new Python file:

bash
CopyEdit
nano flash_led_from_file.py

o Write the following Python code to read the on/off cycle times from the file and
flash the LED:

Department of Engineering & Technology 22


python
CopyEdit
import RPi.GPIO as GPIO
import time

# Set the GPIO mode to BCM (Broadcom pin-numbering)


GPIO.setmode(GPIO.BCM)

# Pin assignments
LED_PIN = 17

# Setup the LED pin as output


GPIO.setup(LED_PIN, GPIO.OUT)

# Read on time and off time from the file


with open("flash_times.txt", "r") as file:
on_time, off_time = map(int, file.readline().split())

try:
while True:
# Turn on the LED for the on_time duration
GPIO.output(LED_PIN, GPIO.HIGH)
print(f"LED ON for {on_time} seconds")
time.sleep(on_time)

# Turn off the LED for the off_time duration


GPIO.output(LED_PIN, GPIO.LOW)
print(f"LED OFF for {off_time} seconds")
time.sleep(off_time)

except KeyboardInterrupt:
# Clean up GPIO settings when the program is interrupted
GPIO.cleanup()

11. Run the Program: Save and close the file (press Ctrl + X, then Y to save, and Enter to
confirm). Run the program:

bash
CopyEdit
python3 flash_led_from_file.py

How It Works:

o The program reads the on time and off time from the flash_times.txt file.
o The LED will turn on for the on time (e.g., 2 seconds) and then turn off for the
off time (e.g., 1 second). This cycle repeats indefinitely.

Department of Engineering & Technology 23


EXPERIMENT-5

5 a) Flash an LED based on cron output (acts as an alarm)


b) Switch on a relay at a given time using cron, where the relay's contact
terminals are connected to a load.
c) Get the status of a bulb at a remote place (on the LAN) through web.
a) Flash an LED Based on Cron Output (Acts as an Alarm)

In this task, we will create an alarm system where an LED flashes periodically based on a cron
job. The cron job will trigger the Python script at specific times to make the LED flash.

Steps:

1. Hardware Setup:
o Connect an LED to a GPIO pin on the Raspberry Pi (e.g., GPIO17).
o Connect a 220Ω resistor in series with the LED to protect it from excess current.
o Connect the cathode of the LED to ground (GND).

2. Write the Python Script:

o Open a terminal on your Raspberry Pi and create a new Python file:

bash
CopyEdit
nano led_alarm.py

o Write the following Python code to flash the LED:

python
CopyEdit
import RPi.GPIO as GPIO
import time

# Set up GPIO mode


GPIO.setmode(GPIO.BCM)
LED_PIN = 17 # GPIO pin to which the LED is connected

# Set up the LED pin as an output


GPIO.setup(LED_PIN, GPIO.OUT)

# Flash the LED (turn on and off for 1 second each)


GPIO.output(LED_PIN, GPIO.HIGH) # LED on
time.sleep(1)
GPIO.output(LED_PIN, GPIO.LOW) # LED off
time.sleep(1)

# Clean up GPIO setup

Department of Engineering & Technology 24


GPIO.cleanup()

3. Save and Close the Script:

o In nano, press Ctrl + X, then Y to save, and Enter to confirm.

4. Create a Cron Job to Run the Script: Cron jobs allow you to run scripts at scheduled
times.

o Open the cron table for editing:

bash
CopyEdit
crontab -e

o Add a cron job to execute the Python script at a specific time, for example, every
minute:

ruby
CopyEdit
* * * * * /usr/bin/python3 /home/pi/led_alarm.py

This will run the script every minute. You can customize the cron job schedule
using the cron syntax.

o Save and exit the cron editor.


5. Test the Cron Job:

o The LED should now flash every minute as the cron job triggers the Python script at the
scheduled time.

b) Switch on a Relay at a Given Time Using Cron, Where the Relay's Contact Terminals Are
Connected to a Load

In this task, we will use a relay module to switch on/off a load (e.g., a lamp) at a specific time
using cron jobs.

Steps:

1. Hardware Setup:
o Connect a Relay module to the Raspberry Pi.
 VCC to 5V on the Raspberry Pi.
 GND to Ground.
 IN1 (control pin) to a GPIO pin (e.g., GPIO17).
o Connect the Normally Open (NO) terminal of the relay to one terminal of the load (e.g.,
a lamp).

Department of Engineering & Technology 25


o Connect the other terminal of the load to ground.
o Common (COM) terminal connects to the power supply for the load (e.g., 220V AC for a
lamp, but be careful if working with high voltage).

2. Write the Python Script to Control the Relay:

o Open a terminal on your Raspberry Pi and create a new Python file:

bash
CopyEdit
nano relay_on.py

o Write the following Python code to switch on the relay:

python
CopyEdit
import RPi.GPIO as GPIO
import time

# Set up GPIO mode


GPIO.setmode(GPIO.BCM)
RELAY_PIN = 17 # GPIO pin to which the relay is connected

# Set up the relay pin as an output


GPIO.setup(RELAY_PIN, GPIO.OUT)

# Turn on the relay (activate the switch)


GPIO.output(RELAY_PIN, GPIO.HIGH) # Relay ON
print("Relay is ON")
time.sleep(10) # Keep the relay on for 10 seconds

# Turn off the relay


GPIO.output(RELAY_PIN, GPIO.LOW) # Relay OFF
print("Relay is OFF")

# Clean up GPIO settings


GPIO.cleanup()

3. Save and Close the Script:

o In nano, press Ctrl + X, then Y to save, and Enter to confirm.

4. Create a Cron Job to Run the Relay Script:

o Open the cron table for editing:

bash
CopyEdit
crontab -e

o Add a cron job to run the script at a specific time (e.g., at 6 PM every day):

Department of Engineering & Technology 26


ruby
CopyEdit
0 18 * * * /usr/bin/python3 /home/pi/relay_on.py

This cron job will run the relay script at 6:00 PM every day.

oSave and exit the cron editor.


5. Test the Cron Job:

o The relay will switch on at the specified time, activating the load for 10 seconds, and
then turn off.

c) Get the Status of a Bulb at a Remote Place (On the LAN) Through Web

In this task, we'll create a web interface to check the status of a bulb (connected to a relay) at a
remote location via a local network (LAN).

Steps:

1. Hardware Setup:
o Connect a Relay module to a GPIO pin (e.g., GPIO17) as described in part (b), with the
bulb connected to the relay.
o The relay will control the bulb (on or off), and you will be able to check its status
remotely via a web interface.

2. Install Flask Web Framework: Flask is a lightweight web framework in Python that
allows you to create web servers easily.

Install Flask on your Raspberry Pi:

bash
CopyEdit
sudo apt-get update
sudo apt-get install python3-flask

3. Write the Python Web Server Script:

o Open a terminal and create a new Python file for the web server:

bash
CopyEdit
nano web_bulb_status.py

o Write the following code to create a Flask web server that checks and toggles the
bulb status:

python

Department of Engineering & Technology 27


CopyEdit
from flask import Flask, render_template, redirect, url_for
import RPi.GPIO as GPIO

# Set up Flask app


app = Flask(__name__)

# Set up GPIO pins


GPIO.setmode(GPIO.BCM)
RELAY_PIN = 17
GPIO.setup(RELAY_PIN, GPIO.OUT)

@app.route('/')
def index():
# Check the current status of the bulb (relay)
relay_status = GPIO.input(RELAY_PIN) # HIGH means on, LOW
means off
bulb_status = "On" if relay_status == GPIO.HIGH else "Off"
return render_template('index.html', status=bulb_status)

@app.route('/toggle')
def toggle():
# Toggle the relay (bulb)
current_status = GPIO.input(RELAY_PIN)
GPIO.output(RELAY_PIN, GPIO.LOW if current_status == GPIO.HIGH
else GPIO.HIGH)
return redirect(url_for('index'))

# Run the web server


if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

4. Create the HTML Template for Web Interface:


o In the same directory as the web_bulb_status.py file, create a folder named
templates:

bash
CopyEdit
mkdir templates

o Inside the templates folder, create an index.html file:

bash
CopyEdit
nano templates/index.html

o Write the following HTML code for the web interface:

html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

Department of Engineering & Technology 28


<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Bulb Status</title>
</head>
<body>
<h1>Bulb is currently: {{ status }}</h1>
<a href="{{ url_for('toggle') }}">Toggle Bulb</a>
</body>
</html>

5. Run the Web Server: Run the web server using the following command:

bash
CopyEdit
python3 web_bulb_status.py

The web server will start, and you can access it via your Raspberry Pi's IP address at port
5000 (e.g., http://192.168.1.100:5000).

6. Access the Web Interface:

o Open a web browser and enter your Raspberry Pi's IP address followed by :5000 (e.g.,
http://192.168.1.100:5000).
o You will see a page showing the current status of the bulb (on or off) and a link to toggle
the bulb's state.

Department of Engineering & Technology 29


EXPERIMENT-6

6 The student should have hands on experience in using various sensors like
temperature, humidity, smoke, light, etc. and should be able to use control
web camera, network, and relays connected to the Pi.
1. Using Temperature and Humidity Sensor (DHT11 or DHT22)

The DHT11 or DHT22 is a popular sensor for measuring temperature and humidity. The sensor
outputs data through a digital signal, which can be easily read by a Raspberry Pi.

Hardware Setup:

1. Wiring the DHT11/DHT22 Sensor:


o VCC to 3.3V or 5V on the Raspberry Pi.
o GND to Ground (GND).
o Data to a GPIO pin (e.g., GPIO4).

2. Install Required Libraries: You need to install the Adafruit_DHT library to interface
with the sensor.

bash
CopyEdit
sudo pip3 install Adafruit_DHT

3. Python Script to Read Temperature and Humidity:

o Open a terminal and create a new Python file:

bash
CopyEdit
nano dht_read.py

o Write the following Python code:

python
CopyEdit
import Adafruit_DHT
import time

# Set sensor type (DHT11 or DHT22) and GPIO pin


sensor = Adafruit_DHT.DHT22 # Change to DHT11 if using that
sensor
pin = 4 # GPIO4

# Try to read the sensor data


humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

Department of Engineering & Technology 30


if humidity is not None and temperature is not None:
print(f'Temperature: {temperature:.1f}C Humidity:
{humidity:.1f}%')
else:
print('Failed to get data from the sensor')

time.sleep(2) # Wait 2 seconds before reading again

4. Run the Program:

bash
CopyEdit
python3 dht_read.py

o This will output the temperature and humidity values to the console.

2. Using Smoke Sensor (MQ-2)

The MQ-2 gas sensor can be used to detect smoke, gases like LPG, CO, methane, etc. It outputs
an analog signal that we will read using an ADC (Analog-to-Digital Converter) since the
Raspberry Pi doesn’t have built-in ADC pins.

Hardware Setup:

1. MQ-2 Wiring:
o VCC to 5V on the Raspberry Pi.
o GND to Ground (GND).
o A0 (Analog Output) to an ADC input (e.g., GPIO17) or directly to an analog-to-digital
converter (like the MCP3008).

2. Install MCP3008 Libraries: For using an ADC with Raspberry Pi, we use the
MCP3008 library.

bash
CopyEdit
sudo apt-get install python3-spidev
sudo pip3 install adafruit-mcp3008

3. Python Script to Read Smoke Sensor Data:

o Open a terminal and create a new Python file:

bash
CopyEdit
nano mq2_read.py

o Write the following Python code to read the data:

Department of Engineering & Technology 31


python
CopyEdit
import time
import spidev
from Adafruit_MCP3008 import MCP3008

# Set up SPI and MCP3008 ADC


spi = spidev.SpiDev()
spi.open(0, 0) # Use bus 0, device 0
adc = MCP3008(spi=spi)

# Define the channel for the smoke sensor


smoke_channel = 0 # Channel 0 for smoke sensor

while True:
# Read the value from the sensor
smoke_value = adc.read(smoke_channel)
print(f"Smoke Level: {smoke_value}")
time.sleep(1)

4. Run the Program:

bash
CopyEdit
python3 mq2_read.py

o This will output the analog value from the MQ-2 sensor, which indicates the smoke
concentration.

3. Using Light Sensor (LDR - Light Dependent Resistor)

An LDR (Light Dependent Resistor) changes its resistance based on light intensity. We can use
a voltage divider circuit to measure the light intensity through the Raspberry Pi's analog-to-
digital converter (MCP3008).

Hardware Setup:

1. LDR Wiring:
o Connect the LDR in a voltage divider configuration with a resistor (e.g., 10kΩ).
o Connect the midpoint of the divider (LDR + Resistor) to an ADC pin (e.g., GPIO18).

2. Python Script to Read Light Sensor Data:

o Open a terminal and create a new Python file:

bash
CopyEdit
nano ldr_read.py

Department of Engineering & Technology 32


o Write the following Python code:

python
CopyEdit
import time
import spidev
from Adafruit_MCP3008 import MCP3008

# Set up SPI and MCP3008 ADC


spi = spidev.SpiDev()
spi.open(0, 0)
adc = MCP3008(spi=spi)

# LDR sensor channel


ldr_channel = 1

while True:
# Read the LDR value
light_level = adc.read(ldr_channel)
print(f"Light Level: {light_level}")
time.sleep(1)

3. Run the Program:

bash
CopyEdit
python3 ldr_read.py

o This will output the light intensity value from the LDR sensor.

4. Controlling a Relay with Python

A Relay can be used to control high-power devices like lights, motors, or other appliances. We
will use a relay to switch on/off a load at a specific time or in response to some sensor input.

Hardware Setup:

1. Relay Wiring:
o VCC to 5V on the Raspberry Pi.
o GND to Ground (GND).
o IN to a GPIO pin (e.g., GPIO17).
o Connect the Common (COM) terminal to the load's power source.
o Connect the Normally Open (NO) terminal to the load.

Python Script to Control the Relay:

1. Open a terminal and create a new Python file:

bash

Department of Engineering & Technology 33


CopyEdit
nano relay_control.py

2. Write the following Python code:

python
CopyEdit
import RPi.GPIO as GPIO
import time

# Set up GPIO pin


RELAY_PIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY_PIN, GPIO.OUT)

# Turn on the relay (activate the switch)


GPIO.output(RELAY_PIN, GPIO.HIGH)
print("Relay ON")
time.sleep(5) # Keep it on for 5 seconds

# Turn off the relay


GPIO.output(RELAY_PIN, GPIO.LOW)
print("Relay OFF")

GPIO.cleanup()

3. Run the Program:

bash
CopyEdit
python3 relay_control.py

o This will turn on the relay (and thus the connected load) for 5 seconds.

5. Controlling a Web Camera (Using Python and OpenCV)

You can control a web camera through the Raspberry Pi using OpenCV. OpenCV is an open-
source computer vision library that can capture images and video from connected cameras.

Hardware Setup:

 Connect a USB webcam to the Raspberry Pi.

Install Required Libraries:

1. Install OpenCV:

bash
CopyEdit
sudo apt-get update

Department of Engineering & Technology 34


sudo apt-get install python3-opencv

Python Script to Capture Video:

1. Open a terminal and create a new Python file:

bash
CopyEdit
nano webcam_capture.py

2. Write the following Python code to access the webcam and display video:

python
CopyEdit
import cv2

# Open the webcam (0 is usually the default webcam)


cap = cv2.VideoCapture(0)

while True:
# Capture frame-by-frame
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break

# Display the resulting frame


cv2.imshow('Webcam', frame)

# Exit the video stream on pressing 'q'


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

# Release the webcam and close any open windows


cap.release()
cv2.destroyAllWindows()

3. Run the Program:

bash
CopyEdit
python3 webcam_capture.py

o This will open a window showing live video from the webcam. Press q to quit.

6. Controlling a Network (Using HTTP Requests to Control Devices)

You can create a web server on your Raspberry Pi to control devices like LEDs, relays, etc., via
HTTP requests.

Department of Engineering & Technology 35


Install Flask for Web Interface:

bash
CopyEdit
sudo apt-get install python3-flask

Python Script for Web Control:

1. Create a new Python file:

bash
CopyEdit
nano web_control.py

2. Write the following code to control devices via a web interface:

python
CopyEdit
from flask import Flask, render_template, request
import RPi.GPIO as GPIO

app = Flask(__name__)

# GPIO setup
GPIO.setmode(GPIO.BCM)
RELAY_PIN = 17
GPIO.setup(RELAY_PIN, GPIO.OUT)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/turn_on')
def turn_on():
GPIO.output(RELAY_PIN, GPIO.HIGH)
return "Relay is ON"

@app.route('/turn_off')
def turn_off():
GPIO.output(RELAY_PIN, GPIO.LOW)
return "Relay is OFF"

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

3. Create the HTML interface:

html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

Department of Engineering & Technology 36


<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Control Relay</title>
</head>
<body>
<h1>Relay Control</h1>
<a href="/turn_on">Turn ON</a>
<a href="/turn_off">Turn OFF</a>
</body>
</html>

4. Run the Web Server:

bash
CopyEdit
python3 web_control.py

o Visit the Raspberry Pi's IP address in a web browser and control the relay using the web
interface.

Department of Engineering & Technology 37

You might also like