IoT Lab Manual
IoT Lab Manual
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:
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.
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.)
The ls command lists files and directories in the current working directory.
To use it:
bash
CopyEdit
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
To go to a specific directory:
bash
CopyEdit
cd /home/pi/Documents
bash
CopyEdit
cd ~
bash
CopyEdit
cd ..
The touch command creates an empty file or updates the timestamp of an existing file.
Example:
bash
CopyEdit
touch myfile.txt
To rename a file:
bash
CopyEdit
mv oldname.txt newname.txt
bash
CopyEdit
mv myfile.txt /home/pi/Documents/
To remove a file:
bash
CopyEdit
rm myfile.txt
bash
CopyEdit
rm -r mydir/
bash
CopyEdit
rm -f myfile.txt
The man command provides the manual or help page for a command.
bash
CopyEdit
man ls
Example:
bash
CopyEdit
mkdir newfolder
Example:
bash
CopyEdit
rmdir myfolder
To create a tarball:
bash
CopyEdit
tar -cvf archive.tar /path/to/folder
To extract a tarball:
bash
CopyEdit
tar -xvf archive.tar
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).
Example:
bash
CopyEdit
cat myfile.txt
Example:
bash
CopyEdit
more myfile.txt
Example:
bash
CopyEdit
less myfile.txt
bash
CopyEdit
ps
bash
CopyEdit
ps aux
The sudo command allows you to execute commands with superuser (root) privileges.
Example:
bash
CopyEdit
sudo apt update
bash
CopyEdit
crontab -e
bash
CopyEdit
0 2 * * * /path/to/script.sh
Example:
bash
CopyEdit
sudo chown user:group myfile.txt
Example:
bash
CopyEdit
sudo chgrp groupname myfile.txt
Example:
bash
CopyEdit
ping google.com
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.
Prerequisites:
bash
CopyEdit
python3 --version
a) Read your name and print a "Hello" message with your name
Program:
bash
CopyEdit
nano hello.py
python
CopyEdit
# Program to print hello message with 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:
bash
CopyEdit
nano calculator.py
python
CopyEdit
# Program to perform arithmetic operations on two numbers
# Print results
print(f"Sum: {sum_result}")
print(f"Difference: {diff_result}")
print(f"Product: {prod_result}")
print(f"Division: {div_result}")
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
Program:
bash
CopyEdit
nano word_char_count.py
python
CopyEdit
# Program to count words and characters in a string
# 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
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:
bash
CopyEdit
nano area_calculator.py
python
CopyEdit
# Program to calculate area of rectangle, triangle, or circle
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.")
else:
print("Invalid shape entered.")
3. Save the file (in nano, press Ctrl + X, then Y to confirm saving).
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.
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.
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).
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
bash
CopyEdit
python3 print_name.py
vbnet
CopyEdit
Enter your name: John
Enter how many times to print your name: 3
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: "))
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
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
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
...
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
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
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
yaml
CopyEdit
Line 1: 4 words
Line 2: 3 words
Line 3: 4 words
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).
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
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:
bash
CopyEdit
nano led_on.py
python
CopyEdit
import RPi.GPIO as GPIO
import time
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.
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:
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
# Pin assignments
SWITCH_1 = 17
SWITCH_2 = 27
LED_1 = 17
LED_2 = 27
try:
while True:
# Read the state of the switches
switch_1_state = GPIO.input(SWITCH_1)
switch_2_state = GPIO.input(SWITCH_2)
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
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:
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:
CopyEdit
2 1
Here, 2 is the on time (in seconds), and 1 is the off time (in seconds).
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:
# Pin assignments
LED_PIN = 17
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)
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.
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).
bash
CopyEdit
nano led_alarm.py
python
CopyEdit
import RPi.GPIO as GPIO
import time
4. Create a Cron Job to Run the Script: Cron jobs allow you to run scripts at scheduled
times.
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 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).
bash
CopyEdit
nano relay_on.py
python
CopyEdit
import RPi.GPIO as GPIO
import time
bash
CopyEdit
crontab -e
o Add a cron job to run the script at a specific time (e.g., at 6 PM every day):
This cron job will run the relay script at 6:00 PM every day.
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.
bash
CopyEdit
sudo apt-get update
sudo apt-get install python3-flask
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
@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'))
bash
CopyEdit
mkdir templates
bash
CopyEdit
nano templates/index.html
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
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).
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.
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:
2. Install Required Libraries: You need to install the Adafruit_DHT library to interface
with the sensor.
bash
CopyEdit
sudo pip3 install Adafruit_DHT
bash
CopyEdit
nano dht_read.py
python
CopyEdit
import Adafruit_DHT
import time
bash
CopyEdit
python3 dht_read.py
o This will output the temperature and humidity values to the console.
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
bash
CopyEdit
nano mq2_read.py
while True:
# Read the value from the sensor
smoke_value = adc.read(smoke_channel)
print(f"Smoke Level: {smoke_value}")
time.sleep(1)
bash
CopyEdit
python3 mq2_read.py
o This will output the analog value from the MQ-2 sensor, which indicates the smoke
concentration.
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).
bash
CopyEdit
nano ldr_read.py
python
CopyEdit
import time
import spidev
from Adafruit_MCP3008 import MCP3008
while True:
# Read the LDR value
light_level = adc.read(ldr_channel)
print(f"Light Level: {light_level}")
time.sleep(1)
bash
CopyEdit
python3 ldr_read.py
o This will output the light intensity value from the LDR sensor.
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.
bash
python
CopyEdit
import RPi.GPIO as GPIO
import time
GPIO.cleanup()
bash
CopyEdit
python3 relay_control.py
o This will turn on the relay (and thus the connected load) for 5 seconds.
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:
1. Install OpenCV:
bash
CopyEdit
sudo apt-get update
bash
CopyEdit
nano webcam_capture.py
2. Write the following Python code to access the webcam and display video:
python
CopyEdit
import cv2
while True:
# Capture frame-by-frame
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
bash
CopyEdit
python3 webcam_capture.py
o This will open a window showing live video from the webcam. Press q to quit.
You can create a web server on your Raspberry Pi to control devices like LEDs, relays, etc., via
HTTP requests.
bash
CopyEdit
sudo apt-get install python3-flask
bash
CopyEdit
nano web_control.py
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)
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
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.