How to Use MQTT with Raspberry Pi: Simple Setup Guide
To use
MQTT with a Raspberry Pi, first install an MQTT broker like Mosquitto on the Pi. Then use MQTT client commands or scripts to publish and subscribe to messages between devices.Syntax
MQTT communication involves three main parts: the broker, the publisher, and the subscriber.
- Broker: The server that routes messages (e.g., Mosquitto).
- Publisher: Sends messages to a topic.
- Subscriber: Listens for messages on a topic.
Basic MQTT commands on Raspberry Pi use mosquitto_pub to publish and mosquitto_sub to subscribe.
bash
mosquitto_pub -h <broker_ip> -t <topic> -m <message> mosquitto_sub -h <broker_ip> -t <topic>
Example
This example shows how to install Mosquitto on Raspberry Pi, start the broker, and send a test message.
bash
# Install Mosquitto broker and clients sudo apt update sudo apt install -y mosquitto mosquitto-clients # Start Mosquitto service sudo systemctl start mosquitto sudo systemctl enable mosquitto # Open a terminal and subscribe to topic 'test/topic' mosquitto_sub -h localhost -t test/topic # Open another terminal and publish a message mosquitto_pub -h localhost -t test/topic -m "Hello from Raspberry Pi"
Output
Hello from Raspberry Pi
Common Pitfalls
- Not starting the Mosquitto broker before publishing or subscribing causes connection errors.
- Using wrong topic names or misspelling them leads to no message reception.
- Firewall or network settings blocking port 1883 (default MQTT port) prevent communication.
- Publishing and subscribing on different brokers or IP addresses causes no message flow.
bash
Wrong way: mosquitto_pub -h localhost -t wrong/topic -m "Test" Right way: mosquitto_pub -h localhost -t test/topic -m "Test"
Quick Reference
| Command | Description |
|---|---|
| sudo apt install mosquitto mosquitto-clients | Install MQTT broker and clients |
| sudo systemctl start mosquitto | Start MQTT broker service |
| mosquitto_sub -h | Subscribe to a topic |
| mosquitto_pub -h | Publish a message to a topic |
| sudo systemctl enable mosquitto | Enable broker to start on boot |
Key Takeaways
Install and run Mosquitto broker on Raspberry Pi before using MQTT commands.
Use mosquitto_pub to send messages and mosquitto_sub to receive messages on topics.
Ensure the broker is running and topics match exactly to avoid connection issues.
Check network and firewall settings to allow MQTT traffic on port 1883.
Test MQTT locally on Raspberry Pi before connecting other devices.