Consider this Python code running on a Raspberry Pi that reads a temperature sensor and publishes the data to a server. What will be printed when the code runs?
import time def read_temperature(): return 25.5 def publish_data(temp): print(f"Publishing temperature: {temp}°C") for _ in range(2): temp = read_temperature() publish_data(temp) time.sleep(1)
Look at the loop and how many times the print happens.
The loop runs twice, each time reading the temperature 25.5 and printing it. So the output is printed two times.
When sending sensor data from a Raspberry Pi to a cloud server, which protocol is most commonly used for lightweight, reliable messaging?
Think about a protocol designed for small devices and low bandwidth.
MQTT is a lightweight messaging protocol designed for IoT devices like Raspberry Pi to publish sensor data efficiently.
Analyze the following code snippet that tries to publish sensor data. What error will it raise when run?
import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("broker.hivemq.com", 1883) sensor_value = 42 client.publish("sensor/data", sensor_value) client.disconnect() print("Data published")
Check the data type expected by the publish method.
The publish method expects a string or bytes payload. Passing an integer causes a TypeError.
Given a Raspberry Pi sensor reading, which code snippet correctly publishes the data as JSON to an MQTT topic?
import json import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("broker.hivemq.com", 1883) sensor_data = {"temperature": 22.5, "humidity": 60} # Publish code here client.disconnect()
Think about how to convert a dictionary to a string format suitable for transmission.
json.dumps converts the dictionary to a JSON string, which is the correct format for publishing.
Consider this Python script that reads sensor data and publishes it every 2 seconds for 5 iterations. How many MQTT publish messages will be sent?
import time import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("broker.hivemq.com", 1883) for i in range(5): temp = 20 + i client.publish("sensor/temperature", str(temp)) time.sleep(2) client.disconnect()
Count how many times the loop runs and publishes.
The loop runs 5 times, publishing once each iteration, so 5 messages are sent.