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

IOT Algo

It's Practical notes of IoT

Uploaded by

secretsimper26
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

IOT Algo

It's Practical notes of IoT

Uploaded by

secretsimper26
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

IOT Practical Algorithms

2. a. Blinking of LED with Raspberry Pi.

2. b. Different LED Patterns with Raspberry Pi.

3. a. Display Time Over 4 Digit 7-Segment Display Using Raspberry Pi.

3. b. Display Random Numbers Over 4 Digit 7-Segment Display Using Raspberry pi.

4. Raspberry pi Based Oscilloscope.

5. Controlling Raspberry Pi Using Telegram.

6. Visitor Monitoring with Raspberry Pi Camera.

7. a. Interfacing Raspberry Pi with RFID (Read Card)

7. b. Interfacing Raspberry Pi with RFID (Check Authorization)


(ChatGPT Generated Comments)
2. a. Blinking of LED with Raspberry Pi.
Hardware Requirements :
a. LED
b. Resistor
c. Two Jumper Wires
d. BreadBoard
Connection :
Connect resistor and led horizontally
Connect jumper wire of longer(positive)
leg of led to GPIO pin and
shorter (negative) pin to Ground pin

# Import the RPi.GPIO library to control the Raspberry Pi's GPIO pins
import RPi.GPIO as GPIO
# Import the time library to introduce delays
import time

# Set the GPIO mode to use physical pin numbering (BOARD mode)
GPIO.setmode(GPIO.BOARD)
# Set up GPIO pin 18 as an output pin
GPIO.setup(18, GPIO.OUT)

# Create an infinite loop


while True:
# Print a message indicating that the LED is on
print("LED on")

# Turn the LED on by setting the GPIO pin 18 to HIGH


GPIO.output(18, GPIO.HIGH)

# Sleep for 2 seconds to keep the LED on


time.sleep(2)

# Print a message indicating that the LED is off


print("LED off")

# Turn the LED off by setting the GPIO pin 18 to LOW


GPIO.output(18, GPIO.LOW)
# Sleep for 2 seconds to keep the LED off before the next iteration
time.sleep(2)
2. b. Different LED Patterns with Raspberry Pi.

Hardware Requirements :
a. Four LEDs
b. Four Resistors
c. Eight Jumper Wires
d. BreadBoard
Connection : Connect resistors and leds horizontally
Connect jumper wires to longer(positive)
leg of led to GPIO pins and
shorter (negative) pin to Ground pins according to code

# Import the RPi.GPIO library to control GPIO pins


import RPi.GPIO as GPIO
import time

# Set the pin numbering mode to BOARD (physical pin numbers)


GPIO.setmode(GPIO.BOARD)

# Configure four GPIO pins as outputs


GPIO.setup(3, GPIO.OUT)
GPIO.setup(8, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)

# Create an infinite loop


while True:
# Turn on pins 3 and 12 (LEDs, for example)
GPIO.output(3, GPIO.HIGH)
GPIO.output(12, GPIO.HIGH)
# Pause for 0.4 seconds
time.sleep(0.4)
# Turn off pins 3 and 12
GPIO.output(3, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
# Pause for 0.4 seconds

# Repeat the above steps for pins 8 and 16


GPIO.output(8, GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
time.sleep(0.4)
GPIO.output(8, GPIO.LOW)
GPIO.output(16, GPIO.LOW)
time.sleep(0.4)

# Create a different blinking pattern by turning on pins 3 and 16


GPIO.output(3, GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
time.sleep(0.4)
GPIO.output(3, GPIO.LOW)
GPIO.output(16, GPIO.LOW)
time.sleep(0.4)

# Create another pattern by turning on pins 8 and 12


GPIO.output(8, GPIO.HIGH)
GPIO.output(12, GPIO.HIGH)
time.sleep(0.4)
GPIO.output(8, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
time.sleep(0.4)
3. a. Display Time Over 4 Digit 7-Segment Display Using Raspberry Pi.
Hardware Requirements :
a. TM1637 library
b. Seven segment display
c. Four Jumper Wires
Connection :

# Import necessary libraries


import time
import datetime
import RPi.GPIO as GPIO
import sys
import tm1637
# Initialize the 4-digit 7-segment LED display
Display = tm1637.TM1637(23, 24, tm1637.BRIGHT_TYPICAL)
Display.Clear() # Clear the display
Display.SetBrightness(1) # Set the display brightness level to 1

while True:
# Get the current date and time
now = datetime.datetime.now()
hour = now.hour # Get the current hour
minute = now.minute # Get the current minute
second = now.second # Get the current second

# Create a list representing the current time in the format [HH, HH, MM, MM]
currenttime = [int(hour/10), hour%10, int(minute/10), minute%10]

# Show the current time on the 7-segment display


Display.Show(currenttime)

# Toggle the colon (double point) on the display every second


Display.ShowDoublepoint(second % 2)
# This will alternate between displaying and hiding the colon
# Pause for 1 second before updating the display again
time.sleep(1)
3. b. Display Random Numbers Over 4 Digit 7-Segment Display Using Raspberry pi.
Hardware Requirements :
a. TM1637 library
b. Seven segment display
c. Four Jumper Wires
Connection :

# Import necessary libraries


import time
import datetime
import RPi.GPIO as GPIO
import sys
import tm1637
import random

# Initialize the 4-digit 7-segment LED display


Display = tm1637.TM1637(23, 24, tm1637.BRIGHT_TYPICAL)
Display.Clear() # Clear the display
Display.SetBrightness(1) # Set the display brightness level to 1 (you can adjust this)

while True:
# Generate a random 4-digit number in the format [AB, CD]
currenttime = [random.randint(0, 9), random.randint(0, 9), random.randint(0, 9),
random.randint(0, 9)]

# Show the random number on the 7-segment display


Display.Show(currenttime)

# Pause for 1 second before updating the display with another random number
time.sleep(1)
4. Raspberry pi Based Oscilloscope.
Hardware Requirements :
1. ADS1115 ADC
2. Four Jumper Wires
Connection :

Steps/Prerequisites:
Step 1: Enable I2C
Run the following command from the terminal:
$ sudo raspi-config
In the configuration panel, select "Interface Options," then select "I2C" and enable it.

Step 2: Update and install dependencies


$ sudo apt-get update
$ sudo apt-get upgrade
$ cd ~
$ sudo apt-get install build-essential python-dev python-smbus git
$ git clone https://github.com/adafruit/Adafruit_python_AdS1x15.git
$ cd Adafruit_Python_ADS1x15
$ sudo python setup.py install

Step 3: Test the library and I2C communication


$ cd examples
Run the sampletest.py example, which displays the value of the four channels on the ADC in a tabular form.
$ python simpletest.py

Step 4: Install matplotlib for data visualization


$ sudo apt-get install python-matplotlib
$ pip3 install matplotlib

Step 5: Install drawnow for live updates to the data plot


$ sudo apt-get install python-pip
$ sudo pip3 install drawnow
To Check I2C devices
$ i2cdetect -y 1
# Import necessary libraries
import time
import matplotlib.pyplot as plt # Importing Matplotlib for plotting
from drawnow import *
import Adafruit_ADS1x15 # Import Adafruit_ADS1x15 library for reading analog data

# Initialize the ADC (Analog to Digital Converter)


adc = Adafruit_ADS1x15.ADS1115()
GAIN = 1 # Set the gain value for the ADC
val = [] # Initialize an empty list to store ADC values
cnt = 0 # Initialize a counter
plt.ion() # Turn on interactive mode for Matplotlib
adc.start_adc(0, gain=GAIN) # Start reading from ADC channel 0 with the specified
gain
print("Reading ADS1x15 channel 0")

# Function to create and update the plot


def makeFig():
plt.ylim(300, 500) # Set the y-axis limits for the plot
plt.title("Oscilloscope") # Set the title of the plot
plt.grid(True) # Enable grid lines on the plot
plt.ylabel("ADC Outputs") # Set the y-axis label
plt.plot(val, 'ro-', label='lux') # Plot the ADC values as red dots
plt.legend(loc="lower right") # Display a legend in the lower-right corner

# Main loop
while True:
value = adc.get_last_result() # Read the last result from the ADC
print('Channel 0: {0}'.format(value)) # Print the ADC value to the console
time.sleep(0.5) # Pause for 0.5 seconds
val.append(int(value)) # Add the ADC value to the list
drawnow(makeFig) # Update the plot using the makeFig function
plt.pause(0.1) # Pause for 0.1 seconds to update the plot
cnt = cnt + 1 # Increment the counter
if cnt > 50:
val.pop(0)
# Remove the oldest ADC value from the list if it exceeds 50 values
5. Controlling Raspberry Pi Using Telegram.
Hardware Requirements :
a. Three LEDs
b. Three Resistors
c. Six Jumper Wires
d. Phone with telegram
Connection :

Install telegram bot on raspberry pi :-


$ sudo apt-get install python-pip
$ sudo pip install telepot
Steps to be follow to access LED through the Telegram:
I. Install Telegram app on smartphone from playstore.
II. To open Telegram, request the bot father to create a new bot.
III. Search “BotFather” and click on it.
IV. Request to start a service using /start.
V. Create a new bot using /newbot.
VI. Provide the name for new bot that we want to create and give same name followed by _bot postfix (e.g. tyit_bot).
In exam Add Roll no. as botname e,g (13_Aayush_bot)
VII. After this process the BotFather wil give a Token for access.
VIII. Now search for the bot that we have created.
IX. Now give the command to LEDs as per your requirements

# Import necessary libraries


import RPi.GPIO as GPIO # Import the RPi.GPIO library to control GPIO pins
import telepot # Import the telepot library for Telegram bot functionality
from telepot.loop import MessageLoop # Import MessageLoop to handle Telegram
messages
import time

# Set up GPIO mode and suppress warnings


GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

# Define GPIO pin numbers for the LEDs


blue = 7
red = 11
yellow = 13

# Set up GPIO pins as outputs and turn them off


GPIO.setup(blue, GPIO.OUT)
GPIO.output(blue, False)
GPIO.setup(red, GPIO.OUT)
GPIO.output(red, False)
GPIO.setup(yellow, GPIO.OUT)
GPIO.output(yellow, False)

# Define a function to handle incoming Telegram messages


def action(msg):
chat_id = msg['chat']['id']
command = msg['text']
print('Received: %s' % command)
message = ''

# Check for 'on' command and control LEDs accordingly


if 'on' in command:
message = 'on'
if 'blue' in command:
message += " blue"
GPIO.output(blue, 1)
if 'yellow' in command:
message += " yellow"
GPIO.output(yellow, 1)
if 'red' in command:
message += " red"
GPIO.output(red, 1)
if 'all' in command:
message += " all"
GPIO.output(blue, 1)
GPIO.output(yellow, 1)
GPIO.output(red, 1)
message += " lights"
telegram_bot.sendMessage(chat_id, message)

# Check for 'off' command and turn off LEDs accordingly


if 'off' in command:
message = 'off'
if 'blue' in command:
message += " blue"
GPIO.output(blue, 0)
if 'yellow' in command:
message += " yellow"
GPIO.output(yellow, 0)
if 'red' in command:
message += " red"
GPIO.output(red, 0)
if 'all' in command:
message += " all"
GPIO.output(blue, 0)
GPIO.output(yellow, 0)
GPIO.output(red, 0)
message += " lights"
telegram_bot.sendMessage(chat_id, message)
# Initialize the Telegram bot with your token
telegram_bot = telepot.Bot('Your-Telegram-Bot-Token-Goes-Here')
print('Up and Running…')
# Start the MessageLoop to listen for incoming Telegram messages
MessageLoop(telegram_bot, action).run_as_thread()
# Keep the script running
while True:
time.sleep(10) # Sleep for 10 seconds to avoid excessive CPU usage
6. Visitor Monitoring with Raspberry Pi Camera.
Hardware Requirements :
a. Camera module

Connection :
Prerequisites/Workaround:
sudo apt update
sudo apt upgrade
pip install picamera
pip3 install picamera
sudo apt-get install python-picamera.
sudo apt-get install python3-picamera.
sudoraspi-config
Select Enable camera and Enable it
sudo reboot
To verify connection:
raspistill -o test.jpg
To connect the Pi Camera:
Insert the Ribbon cable of Pi Camera into camera slot,
slightly pull up the tabs of the connector at RPi board
and insert the Ribbon cable into the slot,
then gently push down the tabs again to fix the ribbon cable
# Import necessary libraries
import time
import picamera

# Create a PiCamera object


camera = picamera.PiCamera()

try:
# Start the camera preview (displaying on the screen)
camera.start_preview()

# Sleep for 5 seconds (camera preview is shown during this time)


time.sleep(5)

# Capture an image and save it to the specified file path


camera.capture('/home/pi/Desktop/test.png')

# Stop the camera preview


camera.stop_preview()

# Ensure that the camera is closed even if an exception occurs


finally:
camera.close()
7. a. Interfacing Raspberry Pi with RFID (Read Card)
Hardware Requirements :
a. EM-18 RFID Reader Module
b. RS232 – to – USB Adapter
c. RFID Cards
d. Four Connected Jumper Wires
Connection :
1) $sudoraspi-config.
2) Select the “Serial” option
To access the login shell over serial
communication, Select “No” option
3) $dmesg | greptty.
# Import the serial library for communication with the RFID reader
import serial

# Define a function to read RFID data


def read_rfid():
# Initialize a serial connection to the RFID reader on /dev/ttyUSB0
ser = serial.Serial("/dev/ttyUSB0")

# Set the baud rate for communication with the RFID reader to 9600
ser.baudrate = 9600

# Read 16 bytes of data from the RFID reader


data = ser.read(16)

# Close the serial connection


ser.close()

# Return the read RFID data


return data

# Print a message to prompt the user to place the card


print("Place the card")

# Call the read_rfid function to read RFID data and store it in the 'id' variable
id = read_rfid()

# Print the read RFID data


print(id)
7. b. Interfacing Raspberry Pi with RFID (Check Authorization)
Hardware Requirements :
a. EM-18 RFID Reader Module
b. RS232 – to – USB Adapter
c. RFID Cards
d. Four Connected Jumper Wires
Connection :
1) $sudoraspi-config.
2) Select the “Serial” option
To access the login shell over
serial communication,
Select “No” option
3) $dmesg | greptty.
# Import necessary libraries
import time
import serial
# Initialize a serial connection to the RFID reader on /dev/ttyUSB0
data = serial.Serial
(
port='/dev/ttyUSB0', # Specify the serial port
baudrate=9600, # Set the baud rate for communication
parity=serial.PARITY_NONE, # Set no parity bit
stopbits=serial.STOPBITS_ONE, # Use one stop bit
bytesize=serial.EIGHTBITS # Use eight data bits
)
try:
while True:
print("Place the RFID card")

# Read 12 bytes of data from the RFID reader and decode it as UTF-8
id = data.read(12).decode('utf-8')

# Check if the read RFID card ID matches a predefined value


if id == "1E00CBDE718":
print("Card no:", id)
print("Welcome TYBSCIT\n")
else:
print("Wrong card........\n")

except KeyboardInterrupt:
# Close the serial connection when the script is interrupted (e.g., with Ctrl+C)
data.close()

You might also like