IoT Laboratory with Mini Project- MCA Students

 Use Raspberry Pi and Execute the following




Goto folder and find file.py and in terminal type >python3 file.py to execute
1. Run some python programs on Pi like: Read your name and print Hello message with name
Read two numbers and print their sum, difference, product and division. Word and character
count of a given string Area of a given shape (rectangle, triangle and circle) reading shape and
appropriate values from standard input Print a name „n‟ times, where name and n are read
from standard input, using for and while loops. Handle Divided by Zero Exception. Print
current time for 10 times with an interval of 10 seconds. Read a file line by line and print the
word count of each line
a) #Python program that reads your name and prints a hello message:
# Read your name
name = input("What is your name? ")

# Print hello message with name
print("Hello, " + name + "!")

b) # Program to perform arithmetic operations on two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

print(f"Sum: {num1 + num2}")
print(f"Difference: {num1 - num2}")
print(f"Product: {num1 * num2}")

# Handle division by zero
try:
    print(f"Division: {num1 / num2}")
except ZeroDivisionError:
    print("Division by zero is not allowed!")

c) # Program to count words and characters in a string
text = input("Enter a string: ")

# Word count
words = text.split()
word_count = len(words)

# Character count
char_count = len(text)

print(f"Word count: {word_count}")
print(f"Character count: {char_count}")

d) # Program to calculate the area of a shape
import math

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

if shape == "rectangle":
    length = float(input("Enter the length: "))
    width = float(input("Enter the width: "))
    area = length * width
    print(f"Area of the rectangle: {area}")

elif shape == "triangle":
    base = float(input("Enter the base: "))
    height = float(input("Enter the height: "))
    area = 0.5 * base * height
    print(f"Area of the triangle: {area}")

elif shape == "circle":
    radius = float(input("Enter the radius: "))
    area = math.pi * radius**2
    print(f"Area of the circle: {area:.2f}")

else:
    print("Invalid shape entered!")
e) # Program to print a name 'n' times
name = input("Enter a name: ")
n = int(input("Enter the number of times to print: "))

# Using for loop
print("Using for loop:")
for _ in range(n):
    print(name)

# Using while loop
print("Using while loop:")
count = 0
while count < n:
    print(name)
    count += 1
f) # Program to handle division by zero exception
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))

try:
    result = numerator / denominator
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed!")
g) # Program to print current time 10 times with a 10-second interval
import time
from datetime import datetime

for _ in range(10):
    current_time = datetime.now().strftime("%H:%M:%S")
    print(f"Current time: {current_time}")
    time.sleep(10)  # Wait for 10 seconds
h)# Program to read a file line by line and print word count of each line
file_path = input("Enter the file path: ")

try:
    with open(file_path, 'r') as file:
        for line_number, line in enumerate(file, start=1):
            words = line.split()
            word_count = len(words)
            print(f"Line {line_number}: {word_count} words")
except FileNotFoundError:
    print("File not found!")
Note: Create a text file with some content


2) Get input from two switches and switch on corresponding LEDs

import RPi.GPIO as GPIO
import time

# Pin Definitions
switch1_pin = 17  # GPIO17 for switch 1
switch2_pin = 27  # GPIO27 for switch 2
led1_pin = 22     # GPIO22 for LED 1
led2_pin = 23     # GPIO23 for LED 2

# Setup GPIO
GPIO.setmode(GPIO.BCM)  # Use BCM pin numbering
GPIO.setup(switch1_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # Set switch1 as input with pull-up
GPIO.setup(switch2_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # Set switch2 as input with pull-up
GPIO.setup(led1_pin, GPIO.OUT)  # Set LED1 as output
GPIO.setup(led2_pin, GPIO.OUT)  # Set LED2 as output

try:
    while True:
        # Read the state of the switches
        switch1_state = GPIO.input(switch1_pin)
        switch2_state = GPIO.input(switch2_pin)

        # Control LED1 based on switch1
        if switch1_state == GPIO.LOW:  # Switch is pressed (assuming active-low)
            GPIO.output(led1_pin, GPIO.HIGH)  # Turn on LED1
        else:
            GPIO.output(led1_pin, GPIO.LOW)   # Turn off LED1

        # Control LED2 based on switch2
        if switch2_state == GPIO.LOW:  # Switch is pressed (assuming active-low)
            GPIO.output(led2_pin, GPIO.HIGH)  # Turn on LED2
        else:
            GPIO.output(led2_pin, GPIO.LOW)   # Turn off LED2

        # Small delay to avoid excessive CPU usage
        time.sleep(0.1)

except KeyboardInterrupt:
    # Clean up GPIO on CTRL+C exit
    GPIO.cleanup()

except Exception as e:
    print(f"An error occurred: {e}")
    GPIO.cleanup()

3) Flash an LED at a given on time and off time cycle, where the two times are taken from a file

import RPi.GPIO as GPIO
import time

# Pin Definitions
led_pin = 18  # GPIO18 for the LED

# File to read on-time and off-time
time_file = "led_times.txt"

# Setup GPIO
GPIO.setmode(GPIO.BCM)  # Use BCM pin numbering
GPIO.setup(led_pin, GPIO.OUT)  # Set LED pin as output

def read_times_from_file(filename):
    """Read on-time and off-time from a file."""
    try:
        with open(filename, "r") as file:
            times = file.readline().strip().split()
            on_time = float(times[0])  # First value is on-time
            off_time = float(times[1])  # Second value is off-time
            return on_time, off_time
    except Exception as e:
        print(f"Error reading file: {e}")
        return 1.0, 1.0  # Default values if file reading fails

try:
    while True:
        # Read on-time and off-time from the file
        on_time, off_time = read_times_from_file(time_file)
        print(f"On Time: {on_time}s, Off Time: {off_time}s")

        # Turn on the LED
        GPIO.output(led_pin, GPIO.HIGH)
        time.sleep(on_time)  # Wait for on-time

        # Turn off the LED
        GPIO.output(led_pin, GPIO.LOW)
        time.sleep(off_time)  # Wait for off-time

except KeyboardInterrupt:
    # Clean up GPIO on CTRL+C exit
    GPIO.cleanup()
    print("Program exited cleanly")

except Exception as e:
    print(f"An error occurred: {e}")
    GPIO.cleanup()
4) Switch on a relay at a given time using cron, where the relay’s contact terminals are connected to a load.

import RPi.GPIO as GPIO
import time import sys # Pin configuration RELAY_PIN = 17 # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setup(RELAY_PIN, GPIO.OUT) # Get action from command line argument if len(sys.argv) != 2: print("Usage: python3 relay_control.py [on|off]") GPIO.cleanup() sys.exit(1) action = sys.argv[1].lower() if action == "on": GPIO.output(RELAY_PIN, GPIO.HIGH) # Switch relay on elif action == "off": GPIO.output(RELAY_PIN, GPIO.LOW) # Switch relay off else: print("Invalid argument! Use 'on' or 'off'.") GPIO.cleanup() sys.exit(1) time.sleep(1) # Keep the state for a short period GPIO.cleanup()



5. Access an image through a Pi web cam




6. Control a light source using web page.


from flask import Flask, render_template, request import RPi.GPIO as GPIO # Pin configuration LED_PIN = 17 # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) # Flask app setup app = Flask(__name__) # Initial LED state (OFF) GPIO.output(LED_PIN, GPIO.LOW) @app.route("/") def index(): return render_template("index.html") # Render the web page @app.route("/led_control", methods=["POST"]) def led_control(): action = request.form["action"] if action == "ON": GPIO.output(LED_PIN, GPIO.HIGH) elif action == "OFF": GPIO.output(LED_PIN, GPIO.LOW) return f"LED is now {action}" if __name__ == "__main__": try: app.run(host="0.0.0.0", port=5000) # Accessible on your Pi's IP address except KeyboardInterrupt: GPIO.cleanup()

<!DOCTYPE html> <html> <head> <title>LED Control</title> </head> <body> <h1>Control the LED</h1> <form action="/led_control" method="POST"> <button type="submit" name="action" value="ON">Turn ON</button> <button type="submit" name="action" value="OFF">Turn OFF</button> </form> </body> </html>


7. Implement an intruder system that sends an alert to the given email


import smtplib
from gpiozero import MotionSensor
from email.mime.text import MIMEText

# PIR sensor setup
pir = MotionSensor(17)

# Email setup
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
EMAIL_ADDRESS = "your_email@gmail.com"
EMAIL_PASSWORD = "your_password"
TO_EMAIL = "recipient_email@gmail.com"

def send_email_alert():
    try:
        # Create email content
        msg = MIMEText("Intruder detected!")
        msg["Subject"] = "Intruder Alert"
        msg["From"] = EMAIL_ADDRESS
        msg["To"] = TO_EMAIL

        # Connect to SMTP server and send email
        server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        server.starttls()
        server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        server.sendmail(EMAIL_ADDRESS, TO_EMAIL, msg.as_string())
        server.quit()
        print("Email alert sent!")
    except Exception as e:
        print(f"Failed to send email: {e}")

# Monitor PIR sensor
print("Monitoring for motion...")
while True:
    pir.wait_for_motion()
    print("Motion detected!")
    send_email_alert()
    pir.wait_for_no_motion()

9. Get the status of a bulb at a remote place (on the LAN) through web.

from flask import Flask, jsonify import RPi.GPIO as GPIO # GPIO setup BULB_PIN = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(BULB_PIN, GPIO.IN) # Set as an input pin to read the state # Flask app setup app = Flask(__name__) @app.route("/") def index(): # Check the bulb's status (ON or OFF) bulb_status = GPIO.input(BULB_PIN) status = "ON" if bulb_status == GPIO.HIGH else "OFF" return jsonify({"Bulb Status": status}) if __name__ == "__main__": try: app.run(host="0.0.0.0", port=5000) # Access via LAN except KeyboardInterrupt: GPIO.cleanup()





No comments:

Post a Comment