Bird
0
0

You want to publish temperature and humidity data from a Raspberry Pi to two MQTT topics sensor/temp and sensor/humidity. Which code snippet correctly publishes both values and disconnects properly?

hard🚀 Application Q15 of 15
Raspberry Pi - MQTT for IoT

You want to publish temperature and humidity data from a Raspberry Pi to two MQTT topics sensor/temp and sensor/humidity. Which code snippet correctly publishes both values and disconnects properly?

import paho.mqtt.client as mqtt
client = mqtt.Client()
client.connect('broker.hivemq.com', 1883)
# Fill in the blanks
client.publish('sensor/temp', '23.1')
client.publish('sensor/humidity', '60')
client.disconnect()
AMust publish only one topic per connection
BMissing client.loop_start() before publishing
CShould call disconnect() before publishing
DCorrect as shown, publishes both then disconnects
Step-by-Step Solution
Solution:
  1. Step 1: Verify connection and publishing order

    Connect first, then publish each topic's data, then disconnect.
  2. Step 2: Check if loop_start() is required

    For simple publish, loop_start() is optional; synchronous publish works fine.
  3. Step 3: Confirm multiple publishes per connection

    Multiple publishes can be done before disconnecting.
  4. Final Answer:

    Correct as shown, publishes both then disconnects -> Option D
  5. Quick Check:

    Connect -> publish multiple -> disconnect [OK]
Quick Trick: Publish multiple topics after connect, then disconnect [OK]
Common Mistakes:
MISTAKES
  • Disconnecting before publishing
  • Thinking loop_start() is always needed
  • Believing only one publish per connection allowed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes