0% found this document useful (0 votes)
8 views12 pages

Experiment 6

Uploaded by

FS20EC008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views12 pages

Experiment 6

Uploaded by

FS20EC008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Sardar Patel Institute of Technology

Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India


(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025
Class: TE EXTC-A Subject: IoT
Semester: 5 Experiment 6 Batch: - A3
Name: Rohan Milind Kadam Roll No.: 2023201010

Aim: Implement device to device communication with the help of Mosquitto broker

Objective:
Establish Device-to-Device CommunicationSet up a broker or server to handle the
communication between IoT devices.
Demonstrate Real-Time Data Exchange

Software • Thonny IDE


Required:
Theory • What is MicroPython?
Ans. MicroPython is a lightweight version of Python 3 designed for microcontrollers and
embedded systems. It allows you to write and run Python code on devices with limited
resources, like the ESP32 and Raspberry Pi Pico. MicroPython is ideal for controlling hardware,
such as sensors and displays, making it easy to prototype and develop projects quickly.

• What is MQTT Protocol?


Ans. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol
designed for low-bandwidth or unreliable networks, commonly used in IoT. It follows a
publish/subscribe model where devices (clients) send (publish) messages to a central broker
under specific "topics," and other devices (subscribers) receive these messages by subscribing to
those topics. MQTT is efficient, using minimal bandwidth, and supports three levels of Quality
of Service (QoS) for message delivery reliability. It is ideal for constrained environments,
making it useful in IoT applications like your ESP32 project to transmit sensor data to an MQTT
app in real-time.

• What is QoS?
Ans: Quality of Service (QoS):
MQTT offers three levels of QoS for message delivery:
o QoS 0 (At most once): Messages are delivered once, with no acknowledgment.
o QoS 1 (At least once): Messages are delivered at least once, with
acknowledgment.
o QoS 2 (Exactly once): Messages are delivered exactly once, ensuring no
duplication.
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025
Algorithm:

Figure 1Algorithm for 1st code

Figure 2Algorithm for 2nd code


Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025
Main.py
Program: Sending the message string:

import time
from umqtt.simple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
import gc

# Initialize ESP settings


esp.osdebug(None)
gc.collect()

# Wi-Fi credentials and MQTT broker details


mqtt_server = '172.16.80.156' # Your MQTT broker IP
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'notification' # Topic to subscribe to
topic_pub = b'hello' # Topic to publish to

# Initialize variables
last_message = 0
message_interval = 5
counter = 0

# Callback function for received messages


def sub_cb(topic, msg):
print((topic, msg))
if topic == topic_pub and msg == b'received':
print('ESP received hello message')

# Connect to MQTT broker and subscribe


def connect_and_subscribe():
global client_id, mqtt_server, topic_sub
client = MQTTClient(client_id, mqtt_server)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
return client

# Restart and reconnect if there's an error


def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()

# Main loop
try:
client = connect_and_subscribe() # Connect to MQTT
while True:
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025
Program:
try:

client.check_msg() # Check for incoming messages


if (time.time() - last_message) > message_interval:
msg = b'Hello#%d' % counter
client.publish(topic_pub, msg) # Publish message
print('Published:', msg)
last_message = time.time()
counter += 1
except OSError as e:
restart_and_reconnect() # Handle connection errors
except Exception as e:
print('Exception occurred:', e)
restart_and_reconnect() # Handle startup exceptions

Boot.py
import time
import network
import esp
import gc
import machine

# Disable debug output


esp.osdebug(None)
gc.collect()

# Wi-Fi credentials
ssid = 'Room-301' # Replace with your Wi-Fi SSID
password = 'etrx@301' # Replace with your Wi-Fi password

# Function to connect to Wi-Fi


def connect_wifi():
station = network.WLAN(network.STA_IF)
station.active(True)

print('Connecting to Wi-Fi...')
station.connect(ssid, password)

# Wait for connection


for attempt in range(20): # Wait for up to 20 seconds
if station.isconnected():
print('Connection successful')
print('IP address:', station.ifconfig()[0])
return
time.sleep(1)
print('Attempting to connect...')

print('Failed to connect to Wi-Fi. Check credentials and network settings.')


Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025

# Connect to Wi-Fi on boot


try:
connect_wifi()
except Exception as e:
print('Error occurred while connecting to Wi-Fi:', e)

Main.py

Code for ESP 1 (Ultrasonic sensor -> ESP 2, IR sensor <- ESP 2):

import time
from umqtt.simple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
import gc

# Sensor setup (Ultrasonic sensor, assuming trigger pin 12, echo pin 13)
trigger_pin = machine.Pin(12, machine.Pin.OUT)
echo_pin = machine.Pin(13, machine.Pin.IN)

esp.osdebug(None)
gc.collect()

# Wi-Fi credentials and MQTT broker details


mqtt_server = '172.16.80.156' # Your MQTT broker IP
client_id = ubinascii.hexlify(machine.unique_id())
topic_pub_1 = b'ultrasonic/data' # Topic to publish ultrasonic data
topic_sub_1 = b'ir/data' # Topic to receive IR sensor data

# Initialize variables
last_message = 0
message_interval = 5
counter = 0

# Function to get Ultrasonic data


def get_ultrasonic_data():
trigger_pin.off()
time.sleep_us(2)
trigger_pin.on()
time.sleep_us(10)
trigger_pin.off()

while echo_pin.value() == 0:

start = time.ticks_us()
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025

while echo_pin.value() == 1:
end = time.ticks_us()

duration = time.ticks_diff(end, start)


distance = (duration * 0.0343) / 2 # Speed of sound is 343 m/s
return distance

# Callback function for received messages


def sub_cb(topic, msg):
print((topic, msg))
if topic == topic_sub_ESP1:
print('Received IR sensor data: %s' % msg)

# Connect to MQTT broker and subscribe


def connect_and_subscribe():
global client_id, mqtt_server, topic_sub_ESP1
client = MQTTClient(client_id, mqtt_server)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub_ESP1)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub_1))
return client

# Restart and reconnect if there's an error


def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()

# Main loop
try:
client = connect_and_subscribe()
while True:
try:
client.check_msg() # Check for incoming messages

# Send ultrasonic data


if (time.time() - last_message) > message_interval:
ultrasonic_data = get_ultrasonic_data()
msg = b'Ultrasonic: %.2f cm' % ultrasonic_data
client.publish(topic_pub_1, msg) # Publish ultrasonic data
print('Published:', msg)
last_message = time.time()
counter += 1

except OSError as e:
restart_and_reconnect() # Handle connection errors
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025

except Exception as e:

print('Exception occurred:', e)
restart_and_reconnect() # Handle startup exceptions

Main.py

Code for ESP 2 (IR sensor -> ESP 1, Ultrasonic sensor <- ESP 1):

import time
from umqtt.simple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
import gc

# Sensor setup (IR sensor on pin 14)


ir_sensor_pin = machine.Pin(14, machine.Pin.IN)

esp.osdebug(None)
gc.collect()

# Wi-Fi credentials and MQTT broker details


mqtt_server = '172.16.80.25' # Your MQTT broker IP
client_id = ubinascii.hexlify(machine.unique_id())
topic_pub_ESP2 = b'ir/data' # Topic to publish IR sensor data
topic_sub_ESP2 = b'ultrasonic/data' # Topic to receive ultrasonic data

# Initialize variables
last_message = 0
message_interval = 5
counter = 0

# Function to get IR sensor data


def get_ir_data():
return ir_sensor_pin.value()

# Callback function for received messages


def sub_cb(topic, msg):
print((topic, msg))
if topic == topic_sub_ESP2:
print('Received Ultrasonic sensor data: %s' % msg)

# Connect to MQTT broker and subscribe


def connect_and_subscribe():
global client_id, mqtt_server, topic_sub_ESP2
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025

client = MQTTClient(client_id, mqtt_server)


client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub_ESP2)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub_2))
return client

# Restart and reconnect if there's an error


def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()

# Main loop
try:
client = connect_and_subscribe()
while True:
try:
client.check_msg() # Check for incoming messages

# Send IR sensor data


if (time.time() - last_message) > message_interval:
ir_data = get_ir_data()
msg = b'IR Sensor: %d' % ir_data
client.publish(topic_pub_ESP2, msg) # Publish IR sensor data
print('Published:', msg)
last_message = time.time()
counter += 1

except OSError as e:
restart_and_reconnect() # Handle connection errors
except Exception as e:
print('Exception occurred:', e)
restart_and_reconnect() # Handle startup exceptions
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025

Result:

Figure 3sending message string


Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025

Figure 4ESP1

Figure 5ESP2
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025

Figure 6Ultrasonic sensor

Figure 7IR Sensor


Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous Institute Affiliated to University of Mumbai)
Academic Year: 2024-2025

Conclusion: The experiment successfully demonstrated device-to-device communication using the Mosquitto MQTT
in an IoT setup. Two ESP devices were integrated with ultrasonic and IR sensors, respectively, and
utilized the MQTT publish/subscribe model to exchange real-time sensor data. The system efficiently
handled message transmission with robust error recovery mechanisms, ensuring reliable connectivity.
Overall, this experiment highlights the effective use of MQTT for low-latency, real-time communication
between IoT devices in constrained network environments, showcasing its applicability for various
sensor-based applications.

You might also like