0
0
Raspberry Piprogramming~30 mins

Subscribing to control topics in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
Subscribing to control topics
📖 Scenario: You are working on a Raspberry Pi project that listens to control messages sent over MQTT. These messages tell the Pi to perform actions like turning on a light or starting a motor.To do this, you need to subscribe to specific MQTT topics and handle incoming messages.
🎯 Goal: Build a simple Python program that connects to an MQTT broker, subscribes to control topics, and prints the received messages.
📋 What You'll Learn
Create a dictionary called mqtt_config with broker details
Create a list called control_topics with the topics to subscribe
Write a function called on_message to handle incoming messages
Subscribe to the topics in control_topics
Print the received messages with topic and payload
💡 Why This Matters
🌍 Real World
MQTT is widely used in IoT projects to control devices remotely. Subscribing to control topics lets your Raspberry Pi react to commands sent from other devices or apps.
💼 Career
Understanding MQTT and how to subscribe to topics is important for IoT developers, embedded systems engineers, and anyone working with connected devices.
Progress0 / 4 steps
1
Setup MQTT configuration dictionary
Create a dictionary called mqtt_config with these exact entries: 'broker': 'test.mosquitto.org', 'port': 1883, and 'client_id': 'raspberry_pi_client'.
Raspberry Pi
Need a hint?

Use curly braces {} to create a dictionary with keys and values.

2
Create list of control topics
Create a list called control_topics with these exact strings: 'home/livingroom/light' and 'home/kitchen/motor'.
Raspberry Pi
Need a hint?

Use square brackets [] to create a list with the given topic strings.

3
Define message handling function and subscribe
Import paho.mqtt.client as mqtt. Create a client using mqtt.Client(mqtt_config['client_id']). Define a function called on_message that takes client, userdata, and message as parameters and prints Received message on {message.topic}: {message.payload.decode()}. Set this function as the client's on_message callback. Connect the client to mqtt_config['broker'] and mqtt_config['port']. Subscribe to all topics in control_topics using a for loop.
Raspberry Pi
Need a hint?

Use the paho-mqtt library to create a client and subscribe to topics.

4
Start the MQTT client loop and print messages
Start the MQTT client loop with client.loop_start(). Add a print statement print('Subscribed to control topics and waiting for messages...') to show the program is ready.
Raspberry Pi
Need a hint?

Use client.loop_start() to keep the client listening for messages.