Iot Lab
Iot Lab
Iot Lab
Reference Books
1. Dr. SRN Reddy, Rachit Thukral and Manasi Mishra, “Introduction to Internet of Things: A
practical Approach”, ETI Labs 2014
2. Jeeva Jose, “Internet of Things”, Khanna Publishing House, Delhi, 2012
3. Adrian McEwen, “Designing the Internet of Things”, Wiley, 2007
4. Cuno Pfister, “Getting Started with the Internet of Things”, O Reilly Media, 2015
5. Pethuru Raj and Anupama C. Raman, “The Internet of Things: Enabling Technologies, Platforms,
and Use Cases”, CRC Press
Web References
1. https://www.i-scoop.eu/internet-of-things-guide/
2. https://www.theinternetofthings.eu/
3. https://www.udemy.com/course/complete-guide-to-build-iot-things-from-scratch-to-market/
4. https://www.coursera.org/learn/iot
5. https://onlinecourses.nptel.ac.in/noc21_ee85/preview
TABLE OF CONTENTS
The ETS IoT kit is an all-in-one prototype platform for sensor-based IoT projects. It is packed with state-
of-the-art sensor technology and ready-to-use software applications, capable of fulfilling all your IoT application
needs. It has an inbuilt Raspberry pi3 with an all-in-one sensor platform to enable infinite IoT application prototype
possibilities.
Hardware Specification:
Connect your ETS IoT KIT to the VGA converter cable and power adaptor with a monitor using HDMI.
Switch on the power supply and start working. Once the power adaptor is turned ON, you will see the image below.
FUNCTIONAL DESCRIPTION
Block Diagram:
The following figure shows a simplified block diagram of an IoT Kit.
The DFN package had a footprint of 2.5 x 2.5 mm2 while maintaining a height of 0.9 mm. This allows
t h e integration of SHT3x-DIS into a wide variety of applications. Additionally, a wide supply voltage range of
2.15V to 5.5V guarantees compatibility with diverse assembly situations. Overall, SHT3x- DIS incorporates
15years of knowledge of Sensirion, the leader in the humidity sensor industry.
Wireless Radio
Inbuilt wireless radio is exceedingly small, its markings can only be properly seen through a microscope
or magnifying glass, the Broadcom BCM43438 chip provides 2.4GHz 802.11n wireless LAN, Bluetooth Low
Energy, and Bluetooth 4.1 Classic radio support.Cleverly built directly onto the board to reduce costs, rather than
the more commonfully qualified module approach, its only unused feature is a disconnected FM radio receiver.
Antenna
There is no need to connect an external antenna to a Raspberry Pi 3. Radios were connected to the chip
antenna soldered directly to the board to minimize the size of the device. Despite its diminutive stature, this antenna
should be capable of picking up wireless LAN and Bluetooth signals, even through walls.
SD Card
Raspberry Pi should work with any compatible SD card.
SPI Devices
PIN CONFIGURATION
Memory Size:
For the installation of NOOBS, the smallest recommended card size is 8GB. For image installation, we
recommend a minimum of 4GB. Some distributions, specificallyLibrary ELEC and Arch, can run on much
smaller cards.
Card Class:
The card class determines the sustained write speed for the card; a class 4 card will be able to write at
4MB/s, while class 10 should be able to write at 10 MB/s. However, it should be noted that this does not mean that
a class 10 card will outperform a class 4 card for general usage because this writing speed is often achieved at the
cost of reading speed and increased seek times.
I2C Devices:
It has six i2c devices.
MCP23017-IC1
MCP23017-IC2
AXDL345
SHT31
OLED
The diagram on the left-hand side describes the PIN configuration details of the ETS IoT KIT, which has
an IC called MCP3008 10Bit ADC converter connected with Chip Enable 0 (CE0).
The ETS IoT KIT consists of two MCP23017 and one MCP3008, which are used for the I/O expander and
on-board part connectivity. The following tables describe the PIN mapping details.
MXII3008 – Y5
MCP3008-U5 User Interface
CH0 A0
CH1 A1
CH2 A2
CH3 A3
CH4 A4
CH5 A5
CH6 A6
Aim: To explore and understand various Linux commands through the command terminal window on a Raspberry
Pi to enhance understanding and proficiency in the use of these commands for learning purposes.
Components Required:
ET S IoT Trainer Kit
Power adaptor
Monitor
HDMI to VGI converter
Mouse and Keyboard
1 Command: ls
Description: The ls command is used to view the content of a directory. By default, thiscommand displays the
content of the current working directory. There are variations that can be used with the ls command.
Syntax: ls
ls choice Description
In Linux, hidden files start with. (dot) symbol and they are not visible in the regular directory.
ls -a
The (ls -a) command will enlist the whole list of the current directory including the hidden files.
ls -g or ls -lG With this you can exclude column of group information and owner.
ls -li This command prints the index number if file is in the first column.
ls -p It is used to find the directory easily by marking the directorieswith a slash (/) line sign.
ls -lX It will group the files with same extensions together in the list.
ls -lt It will sort the list by displaying recently changed filed at top.
2. Command: cd
Description: The Linux CD command is used to change the current working directory. The "cd" stands for
'change directory.
Syntax: cd <dirname>
3. Command: touch
Description: This was used to create a file without any content. The file created using the touch command
was empty. This command can be used when the user does not have data to be stored at the time of file
creation.
Syntax: touch file_name
Example: touch document.txt
4. Command: mv
Description: mv stands for movement / mv is used to move one or more files or directories from one place
to another inthe file system.
1. It has two distinct functions:
2. It then renames the file or folder.
3. It moves a group of files in a different directory.
Syntax: mv [Option] source destination
Example: $ lsa.txt b.txt c.txt d.txt $ mv a.txt geek.txt
5. Command: rm
Description: rm stands for remove here. / rm command is used to remove objects such as files, directories,
symbolic links,and so on from the file system
Example: Let us consider five files with names a.txt, b.txt, etc. until e.txt.
$ ls
a.txt b.txt c.txt d.txt e.txt Removing one file at a time.
$ rm a.txt
$ ls
b.txt c.txt d.txt e.txt
Removing more than one file at a time
$ rm b.txt c.txt
$ ls
d.txt e.txt
6. Command: man
Description: man, command in Linux is used to display the user manual of any commandthat we can run on
the terminal
Syntax: $man [OPTION…] [Command Name]
Example: $ man printf
7. Command: mkdir
Description: The mkdir command in Linux allows users to create directories.
Syntax: mkdir [options...] [directories ...]
Example: mkdir–version
8. Command: rmdir
Description: The rmdir command is used t o remove empty directories from the Linux file system. The
rmdir command removes each directory specified in the command line only if the directories are empty.
Syntax: rmdir <dirname>
Example: rmdir–p
9. Command: tar
Description: Tar stands for the tape archive, is used to create a n archive, and extracts the archivefiles.
Syntax: tar [options] [archive-file] [file or directory to be archived]
14. Command: ps
Description: ps for viewing information related to the processes on a system that stands as an abbreviation for
“Process Status.” ps command is used to list the currently running processes.
Syntax: ps [options]
Result: The exploration of various Linux commands was successfully completed using the command terminal on
a Raspberry Pi.
Connection Diagram:
Connect LED +ve to any GPIO pin (mention in the program) and -ve pin to ground.
Exp. No. 1
LED interface with Raspberry Pi
Date
Aim: To Develop a Python program to effectively control the activation and deactivation of the LED.
The program aims to provide users with the capability to turn the LED on and off using a well-structured
script.
Components Required:
1. RASPBERRY Pi 3
2. 1K resistor
3. Breadboard
4. LED
5. Connecting wires
Theory:
Interfacing an LED with a Raspberry Pi involves using the General-Purpose Input/Output
(GPIO) pins to control the LED's state (on or off). The Raspberry Pi's GPIO pins can be programmed to
output a voltage, which can then be used to power the LED. When a GPIO pin is set to high, it outputs
3.3V, causing the LED to light up. Conversely, setting the pin to low turns the LED off. A current-
limiting resistor is often placed in series with the LED to prevent excessive current from damaging it.
This simple setup can be used in various applications, from basic status indicators to more complex
signalling systems. Programming languages like Python are commonly used to write scripts that control
the GPIO pins, making it easy to create interactive projects that include LED indicators.
When the Python script controlling the GPIO pins is executed, the LED connected to the Raspberry Pi
should exhibit the following behavior:
1. Initial State: Upon running the script, the LED will be initially off.
2. Turning On the LED: When the script sends a high signal (3.3V) to the GPIO pin connected to
the LED, the LED will turn on, emitting light.
3. Turning Off the LED: When the script sends a low signal (0V) to the GPIO pin, the LED will
turn off, ceasing to emit light.
4. Blinking: If the script is designed to toggle the GPIO pin between high and low states at regular
intervals, the LED will blink on and off according to the specified timing.
Program:
import RPi.GPIO as GPIO
import time
# Define the GPIO pin connected to the LED
LED_Pin=8
#Allows you to control whether these warnings are displayed.
GPIO.setwarnings(False)
# Set up the GPIO numbering scheme (BCM or BOARD)
GPIO.setmode(GPIO.BOARD)
# Set the LED pin as an output pin
GPIO.setup(LED, GPIO.OUT)
while True:
# Turn the LED on
GPIO.output(LED, GPIO.HIGH)
# Wait for 1 second
time.sleep(1)
# Turn the LED off
GPIO.output(LED, GPIO.LOW)
# Wait for 1 second
time.sleep(1)
Result:
The LED's behavior confirms that the Raspberry Pi can successfully control an external device using its
GPIO pins, showcasing basic output functionality in a hardware interface project.
Circuit Diagram:
Connect LED +ve to any GPIO pin (mention in the program) and -ve pin to ground after that continue
the execution procedure
Exp. No 2
LED interface with Raspberry Pi using BLYNK app
Dt.:
Aim: To develop a Python program that effectively controls an LED using the Blynk app. The
objective is to provide users with the capability to remotely turn the LED on and off.
Components Required:
1. RASPBERRY PI 3
2. 3.3K resistor
3. Breadboard
4. Buzzer
5. Connecting wire.
Theory
The LED interface with a Raspberry Pi using the Blynk app combines hardware control and
cloud-based IoT type devices. The Blynk platform is used to build smartphone applications for
controlling hardware remotely. You can connect an LED with the GPIO pins of the Raspberry Pi, and
with the help of a virtual button in the Blynk app, you can turn the LED on and off. This in turn makes
use of a Python library supporting Blynk that enables communication between the Raspberry Pi and the
Blynk server. It will create a Blynk project, obtain an Auth Token, and write a Python script to handle
control of the GPIOs based on Blynk app inputs. This kind of integration brings out the power of IoT in
allowing real-time and remote control over physical devices through a user-friendly mobile interface.
Execution: LED Interface with Raspberry Pi Using Blynk App.
When the setup and Python script are correctly configured, the following outputs can be expected:
1. Initial State: Upon starting the Python script, the Raspberry Pi will connect to the Blynk server
using the provided Auth Token.
2. Blynk App Control:
- LED On: When the virtual button on the Blynk app is pressed, it sends a signal to the
Raspberry Pi, which sets the corresponding GPIO pin to high, turning the LED on.
- LED Off: When the virtual button is released, the Blynk app sends a signal to the Raspberry
Pi, which sets the GPIO pin to low, turning the LED off.
3. Remote Control: The LED can be controlled from any location, if the Raspberry Pi is connected
to the internet and the Blynk app is functioning.
4. Real-Time Response: The LED responds almost instantly to the commands sent from the Blynk
app, demonstrating seamless real-time control.
Output:
Program:
import BlynkLib
import RPi.GPIO as GPIO
BLYNK_AUTH_TOKEN =’ofRuPzgr27sQgErXoy1KvbrYJFYZjPmt’
led1=11
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led1, GPIO.OUT)
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH_TOKEN)
# Led control through V0 virtual pin
@blynk.on("V4")
def v0_write_handler(value):
# global led_switch
if int (value [0])! = 0:
GPIO.output(led1, GPIO.HIGH)
print ('LED1 HIGH')
else:
GPIO.output(led1, GPIO.LOW)
print ('LED1 LOW')
# Led control through V0 virtual pin
#function to sync the data from virtual pins
@blynk.on("connected")
def blynk_connected():
print("Raspberry Pi Connected to New Blynk")
while True:
blynk.run()
RESULT:
The successful execution of these steps shows that the Raspberry Pi can interact with external devices
through a cloud-based interface, making it a powerful tool for IoT applications.
Circuit Diagram:
Connect LED +ve to any GPIO pin (mention in the program) w.r.t ground.
Exp. No 3
Push the button interface with Raspberry Pi to turn On / Off the
Dt.: LED
Aim: To Develop a Python program to interface a push button with Raspberry Pi to control an LED
based on the button press: turn on when pressed, turn off on the next press. The program aims to provide
a responsive and user-friendly interface for controlling the LED.
Components Required:
1. RASPBERRY PI 3
2. 1K resistor
3. Breadboard
4. LED
5. Push Button
6. Connecting wire.
Theory
Interfacing of a push button with a Raspberry Pi to control an LED would typically include
setting up a very simple and basic input/output system using the GPIO pins. The push button acts as a
digital input device, while the LED is usually an output device. When it is pushed, it makes a completion
of circuitry and sends a high signal to a designated GPIO input pin of the Raspberry Pi. A Python script
thus watches the state of such a GPIO pin. When the script sees a high signal, it can either turn on the
state of another GPIO pin that is connected to the LED to light it up or turn it off. In this, some techniques
such as debouncing can be applied when handling any noise or false triggers that may be received from
the pressing of the button. It configures the simplest yet most basic case in digital input/output control in
embedded systems.
Execution: Push Button Interface with Raspberry Pi to Turn On/Off the LED
When the push button is properly interfaced with the Raspberry Pi and the corresponding Python script
is running, the expected outputs are:
1. Initial State: When the Python script starts, the LED will be in its default state (either on or off, as
specified in the script).
2. Button Press:
i. First Press: Pressing the push button sends a high signal to the GPIO input pin, and the script
detects this change, turning the LED on if it was initially off.
ii. Subsequent Presses: Each subsequent press of the button will toggle the LED's state. If the
LED is on, it will turn off, and if it is off, it will turn on.
3. Real-Time Response: The LED's state changes almost instantly in response to the button presses,
demonstrating effective real-time input and output control.
4. Debouncing Handling: If debouncing is implemented, the script will filter out any noise or false
triggers, ensuring that the LED only toggles with intentional button presses.
Sample Observations:
while True:
if GPIO.input(BUTTON_Pin) == 0:
print ("LED_Pin is on")
GPIO.output(LED, True)
else:
print ("LED_Pin is off")
GPIO.output(LED, False)
Result:
This output confirms that the Raspberry Pi can successfully interface with input devices (like a push
button) to control output devices (like an LED) in a reliable and responsive manner.
Exercise:
To interface the digital sensor (IR/LDR) with Raspberry Pi and write a program to turn ON the LED
when the push button is pressed or during sensor detection.
a. Write a program that: Detects the presence of an object in front of the IR sensor. (Prints a message
to the console or triggers an LED to indicate object detection.)
b. Write a program that: Reads the analog voltage output from the LDR (which varies based on light
intensity). (Convert the voltage reading to a light intensity value (e.g., percentage or arbitrary
units).
Circuit Diagram:
Exp no 4
Interfacing OLED with Raspberry Pi and reading DHT11/22
Dt.: sensor data
Aim: To Develop a Python program to interface the OLED with Raspberry Pi and to read the data from the
DHT11/22 sensor and display the temperature and humidity values. The goal of the program is to facilitate effective
communication between the Raspberry Pi and OLED display.
Components Required:
1. RASPBERRY Pi 3
2. I2C OLED Display (128 x 64 0.96' SSD1306 chip)
3. DHT11 Temperature and Humidity Sensor
4. Resistor 4.7 K Ohm
5. Connecting wires
Program:
import board
import time
import adafruit_dht
from luma.core.interface.serial import i2c_serial
from luma.oled.device import ssd1306
Temp: 22.5 C
Humidity: 58.2 %
Result:
The program will continuously read temperature and humidity values from the DHT22 sensor and display them on
the OLED display. The output will be updated every 2 seconds (as defined by time.sleep(2)).
Exercise
1. Write a program that uses the RTC module to obtain the current date and time.
Formats the date and time information (e.g., day, month, year, hours, minutes, seconds).
Displays the formatted date and time information on the OLED display in a clear and
readable format.
Optionally, update the display periodically (e.g., every second) to show a real-time clock.
2. Write a program that reads sensor data from multiple sensors connected to the Raspberry Pi.
Processes the sensor data (e.g., convert raw readings to meaningful units).
Displays the sensor readings (temperature, humidity, pressure) on the OLED display in
a well-organized layout.
Optionally, include labels for each sensor reading and update the display periodically for
real-time monitoring.
3. Write a program that: Displays a text-based menu on the OLED with different options (e.g.,
"Show Temperature", "Show Humidity", "Exit").
Aim: To Develop a Python program Python program to interface a DC motor using a motor driver circuit
(L298N) with Raspberry Pi to control its direction (clockwise and anticlockwise). The aim was to establish an
effective interface for manipulating the movements of the servomotor motor.
Material Required:
1 Raspberry Pi
2 DC Motor
3 Motor driver circuit (L298N)
4 Jumper Wires
Program:
The program successfully controls the motor's direction based on user input
(clockwise, anticlockwise, or stop).
The motor runs for 2 seconds in the selected direction before prompting for the next
input.
try:
# Set initial motor state (stopped)
GPIO.output(IN1_PIN, False)
GPIO.output(IN2_PIN, False)
GPIO.output(ENA_PIN, True) # Enable motor (adjust based on driver)
while True:
# User input for direction selection
direction = input ("Enter 'c' for clockwise, 'a' for anticlockwise, or 's' to stop:")
if direction == 'c':
# Set motor to rotate clockwise
GPIO.output(IN1_PIN, True)
GPIO.output(IN2_PIN, False)
print("Motor rotating clockwise...")
time.sleep(2) # Motor runs for 2 seconds
elif direction == 'a':
# Set motor to rotate anticlockwise
GPIO.output(IN1_PIN, False)
GPIO.output(IN2_PIN, True)
print("Motor rotating anticlockwise...")
time.sleep(2) # Motor runs for 2 seconds
elif direction == 's':
# Stop the motor
GPIO.output(IN1_PIN, False)
GPIO.output(IN2_PIN, False)
print("Motor stopped.")
break # Exit the loop
else:
print("Invalid input. Please enter 'c', 'a', or 's'.")
except KeyboardInterrupt:
# Exit program on keyboard interrupt (Ctrl+C)
print("Exiting program...")
finally:
# Clean up GPIO pins on program exit
GPIO.cleanup()
Result:
The program established control over a DC motor's direction (clockwise and anticlockwise) through user input.
This experiment highlighted the ability to drive motors using Raspberry Pi and motor driver circuits.
Exercise:
Write a Python program to interface a servo motor with a Raspberry Pi. Demonstrate how to control the servo
motor's angle using PWM signals.
Circuit Diagram:
Exp no 6
Ultrasonic Sensor interface with Raspberry Pi using BLYNK
Dt.:
Aim: To write a Python program to interface an Ultrasonic Sensor (HC-SR04) with a Raspberry Pi, we focus
on accurately detecting and displaying the distance measured by the sensor. The aim is to establish effective
communication and control between the Raspberry Pi and ultrasonic sensor.
Components Required:
1. Raspberry Pi
2. Ultrasonic sensor (HC-SR04)
3. 1k Resistor
4. 1.5k Resistor
5. Breadboard
6. Connecting Wires
Program:
import RPi.GPIO as GPIO
import time
import BlynkLib
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH_TOKEN)
# Setup GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.output(TRIG, True)
time.sleep(0.00001) # 10µs pulse
GPIO.output(TRIG, False)
Inference
# Wait for echo end
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
return distance
# Main loop
try:
while True:
print ("Distance measurement in progress")
distance = measure_distance()
print ("Distance:", distance, "cm")
send_distance_to_blynk(distance) # Send the distance to Blynk
time.sleep(2) # Delay between measurements
except KeyboardInterrupt:
print ("Measurement stopped by user")
finally:
GPIO.cleanup() # Clean up GPIO on exit
Result:
Upon successful execution, the program will demonstrate the capability of the Raspberry Pi to interface with the
ultrasonic sensor, accurately measure distances, and display the results according to the program's logic.
Circuit Diagram:
Exp no: 7
IR Sensor interface with Raspberry Pi using BLYNK
Dt.:
Aim:
To Write a Python program to interface an IR sensor with a Raspberry Pi to detect the presence of an obstacle and
indicating with through LED. The objective is to establish effective communication between the Raspberry Pi and
the IR sensor for obstacle detection.
Components Required:
1. Raspberry Pi
2. IR Module (LM393)
3. LED
4. Breadboard
5. Connecting Wires
Program:
import BlynkLib
import RPi.GPIO as GPIO
import time
# Set up GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor_pin, GPIO.IN)
@blynk.on("connected")
def blynk_connected():
print("Raspberry Pi Connected to Blynk")
Output:
try:
while True:
update_blynk_sensor_status()
time.sleep(0.2) # Adjust the sleep time as needed
blynk.run()
except KeyboardInterrupt:
print("Script interrupted by user")
finally:
GPIO.cleanup()
print("GPIO cleanup completed")
while True:
# Read sensor value
sensor_reading = GPIO.input(SENSOR_PIN)
else:
GPIO.output(LED, GPIO.LOW)
except KeyboardInterrupt:
GPIO.cleanup()
Result:
The program showcases Raspberry Pi's ability to interface with the IR sensor, detect obstacles, and potentially
generate an alert or response.
Circuit Diagram
Exp no 8
Thingspeak Humidity and Temperature – Raspberry pi
Dt.:
Aim: To develop a Python program to interface a DHT1/DHT22 sensor with a Raspberry Pi with the goal of
verifying and uploading humidity and temperature data to Thingspeak. The aim was to establish communication
between the Raspberry Pi and the sensor for real-time monitoring.
Components Required
1. Raspberry Pi
2. DHT11/22
3. Connecting wires
Program:
import urllib.request as urllib2
from time import sleep
import Adafruit_DHT as dht
# Enter Your API key here
myAPI = 'U90UVY9W2REYRMYE'
# URL where we will send the data, Don't change it
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
def DHT22_data():
# Reading from DHT22 and storing the temperature and humidity
humi, temp = dht.read_retry(dht.DHT11, 15)
return humi, temp
while True:
try:
humi, temp = DHT22_data()
print(humi,temp)
# If Reading is valid
if isinstance(humi, float) and isinstance(temp, float):
# Formatting to two decimal places
humi = '%.2f' % humi
temp = '%.2f' % temp
Aim:
To Write a C program to interface a DHT11 / DHT22 sensor with an ESP8266 module with the goal of verifying
and obtaining humidity and temperature readings. The aim was to establish effective communication between the
ESP8266 module and the sensor for data retrieval.
Components Required
1. ESP8266 NODE MC
2. DHT11/22
3. Connecting wires
Program
#include <DHT.h> // Including library for dht
#include <ESP8266WiFi.h>
String apiKey = "83KCN4VCEGD6FCR5”; // Enter your Write API key from ThingSpeak
const char *ssid = "Vivo iq z3”; // replace with your wifi ssid and wpa2 key // SMVEC_CONFERANCE1 //
Xperia XZ
const char *pass = "1234567890”; // smvec12345 // 123456789
const char* server = "api.thingspeak.com”
#define DHTPIN 0 //pin where the dht11 is connected
DHT dht (DHTPIN, DHT11);
WiFiClient client.
void setup ()
{
Output
Serial.begin(9600);
delay (10);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status()! = WL_CONNECTED)
{
delay (500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop ()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
Aim: To Create a Python program to establish a connection with a MySQL database on a Raspberry Pi and
perform basic SQL queries. The aim is to demonstrate the Raspberry Pi's capability to interact with a MySQL
database and execute fundamental SQL operations.
Configuration / Installations:
1. Before we get started with installing MySQL to our Raspberry Pi, we must first updt. our package list and
all installed packages.
#sudo – admin privilege – super do
#apt (linux server)
sudo apt update
sudp apt upgrade
2. The next step is to install the MySQL server software on your Raspberry Pi.
sudo mysql_secure_installation
4. if you want to access your Raspberry Pi’s MySQL server and start making changes to your databases, you
can enter the following command.
Result
Upon successful execution, the program will showcase the Raspberry Pi's ability to connect to a MySQL database,
perform basic SQL queries such as SELECT, INSERT and display or manipulate data accordingly. The result
demonstrates the integration of MySQL with the Raspberry Pi, providing a foundation for database interaction in
various applications.
MQTT Block Diagram:
Output:
MQTT_publisher.py
Ex. No. 10(a)
MQTT Publisher
Dt.:
Aim: Develop a Python program to act as an MQTT (Message Queuing Telemetry Transport) publisher. The
objective is to create a script that can publish messages or data to an MQTT broker, facilitating communication
with other MQTT-enabled devices or subscribers.
Component Required:
1 x Raspberry Pi
Stable internet access
Program:
mqtt_publisher.py:
import time
import random
import paho.mqtt.client as mqtt
# MQTT Settings for HiveMQ Public Broker
mqtt_broker_address = "broker.hivemq.com"
mqtt_port = 1883
mqtt_topic = "temperature"
# Create MQTT client instance
mqtt_client = mqtt.Client()
# Connect to MQTT broker
mqtt_client.connect(mqtt_broker_address, mqtt_port, 60)
# Loop to publish temperature data
while True:
temperature = random.uniform(20, 30) # Simulating temperature data
print (f"Publishing Temperature: {temperature:.2f} °C")
# Publish temperature to MQTT broker
mqtt_client.publish(mqtt_topic, str(temperature))
time.sleep(5)
Output:
MQTT_subscriber.py
Ex. No. 10(b)
MQTT Subscriber
Dt.:
Aim: Develop a Python program to act as an MQTT (Message Queuing Telemetry Transport) subscriber. The
objective is to create a script that can subscriber messages or data to an MQTT broker, facilitating communication
with other MQTT-enabled devices or subscribers.
Component Required:
1 x Raspberry Pi
Stable internet access
mqtt_subscriber.py:
Aim: To Develop a Python program on the Raspberry Pi to establish TCP (Transmission Control Protocol)
communication. The objective is to create a script that enables the Raspberry Pi to act as either a TCP server or
client, facilitating data exchange over a TCP connection.
Component Required:
1 x Raspberry Pi
Stable internet access
Program:
Client.py
import socket
host = ' ' #enter host address of the server
#example INET 192.168.43.2
port = 9090
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((host,port))
server.send("Hello server !".encode('utf-8'))
print(server.recv(1024).decode('utf-8'))
Output:
Client.py
Server.py
Server.py
import socket
host = ' ' #find the ip address from
#in terminal type:
# and check find the INET address
#example INET 192.168.43.2
port = 8080
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((host,port))
server.listen(5)
while True:
com_soc, address = server.accept()
print (f"connted to {address}")
message = com_soc.recv(1024).decode('utf-8')
print (f"Message from client is: {message}")
com_soc.send(f"Message recived ! Thank you!".encode('utf-8'))
com_soc.close()
print (f"connection with {address} ended!")
Result
Upon successful execution, the program will demonstrate the Raspberry Pi's ability to establish and participate in
TCP communication. The result showcases the integration of TCP functionality, providing a means for the
Raspberry Pi to send and receive data over a TCP network, fostering versatile communication capabilities for
various applications.
UDP Communication block diagram:
Aim: To write a Python program on the Raspberry Pi to implement UDP (User Datagram Protocol) communication.
The goal is to develop a script that allows the Raspberry Pi to function as either a UDP server or client, facilitating
data exchange over a UDP connection.
Component Required:
1 x Raspberry Pi
Stable internet access
Program:
Client.py
import socket
# Define server host and port
host = ' ' #enter host address of the server
port = 8080
# Create a TCP socket
server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
Client.py
Server.py
Server.py
import socket
# Define server host and port
host = ' ‘ #find the ip address from
#in terminal type:
#ifconfig and check find the INET address
#example INET 192.168.43.2
port = 8080
# Create a TCP socket
server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# Bind the socket to the address and port
server.bind((host,port))
# Receive data from the client
message, address = server.recvfrom(1024)
print(message.decode('utf-8'))
server.sendto("Message from server".encode('utf-8'), address)
Result
Upon successful execution, the program will showcase the Raspberry Pi's capability to establish and engage in
UDP communication. The result demonstrates the integration of UDP functionality, enabling the Raspberry Pi to
transmit and receive data over a UDP network, providing a lightweight and connectionless communication method
for diverse applications.
Appendix
Build the UI by adding two buttons and rename them an ON and OFF, web component in the Design part.
To add functionalities, click on Blocks and create the logic for On and Off button.
Download MIT AI2companion app from the Google play store.
To create connection type the code or scan the QR code to simultaneously control the led from your
mobile phone.
Build the final application and run your application. You can download it on an android phone by scanning
the code or sharing the .apk file.
Pip install
Sudo apt update
Reference
Exp:
IoT Controlled LED using Blynk and ESP8266 (Node MCU) (iotdesignpro.com)
Exp.:
DHT11 Humidity Temperature Monitor with NodeMCU on ThingSpeak (how2electronics.com)
Exp. :
Setup a Raspberry Pi MYSQL Database - Pi My Life Up