0
0
Raspberry Piprogramming~5 mins

Why MQTT is the IoT standard in Raspberry Pi

Choose your learning style9 modes available
Introduction

MQTT is a simple way for devices to talk to each other over the internet. It uses very little data and works well even if the connection is slow or unreliable.

When you want smart home devices like lights and sensors to communicate easily.
When you have many small devices sending small messages often.
When your devices have limited power and need to save battery.
When you want to control devices remotely with low delay.
When your internet connection is not very stable or fast.
Syntax
Raspberry Pi
client = mqtt.Client()
client.connect('broker.hivemq.com', 1883)
client.publish('home/livingroom/temperature', '22')
client.loop_forever()
This example shows how a device connects to a broker and sends a message.
The broker is like a post office that forwards messages to devices that want them.
Examples
This code turns on a kitchen light by sending 'ON' to the topic 'home/kitchen/light'.
Raspberry Pi
import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect('broker.hivemq.com', 1883)
client.publish('home/kitchen/light', 'ON')
client.loop_start()
This code listens for temperature messages from any room and prints them.
Raspberry Pi
def on_message(client, userdata, message):
    print(f"Received message: {message.payload.decode()} on topic {message.topic}")

client = mqtt.Client()
client.on_message = on_message
client.connect('broker.hivemq.com', 1883)
client.subscribe('home/+/temperature')
client.loop_forever()
Sample Program

This program connects to a public MQTT broker, sends a temperature value, and listens for messages on the same topic.

Raspberry Pi
import paho.mqtt.client as mqtt

# Called when a message is received
def on_message(client, userdata, message):
    print(f"Message received on {message.topic}: {message.payload.decode()}")

client = mqtt.Client()
client.on_message = on_message
client.connect('broker.hivemq.com', 1883)
client.subscribe('home/livingroom/temperature')

# Publish a temperature reading
client.publish('home/livingroom/temperature', '23')

client.loop_start()

import time
# Wait a bit to receive messages
time.sleep(2)
client.loop_stop()
OutputSuccess
Important Notes

MQTT uses a 'publish-subscribe' model, which means devices send messages to topics and others listen to those topics.

It is lightweight, so it works well on small devices like Raspberry Pi or sensors.

MQTT brokers handle message delivery, so devices don't need to know about each other directly.

Summary

MQTT is simple and uses little data, perfect for small devices.

It works well even with slow or unreliable internet.

It helps many devices talk easily by sending messages to topics.