Question: I ' m trying to publish DHT 1 1 sensor data to test. mosquitto.org. However, when I choose option 1 , I keep getting failed
Im trying to publish DHT sensor data to test. mosquitto.org. However, when I choose option I keep getting failed to read sensor The sensor is functioning and it is wired correctly to pin for power and pin for data on my raspberry pi What am I doing wrong? I can not use Adafruit library or functionality. import RPi.GPIO as GPIO
import time
import datetime
import random
import paho.mqttclient as mqtt
import dht
import threading
# GPIO pin configuration
POWERPIN
DATAPIN
# MQTT broker configuration
brokerAddress "test.mosquitto.org"
topic DHTtest
sensorID DHT
sensorLocation "Batcave"
# Global flags
publishflag False
dicerollflag False
def connecttobroker:
client mqttClient
client.connectbrokerAddress
return client
def readdhtdata:
instance dhtDHTpinDATAPIN
time.sleep# Wait for sensor to stabilize
result instance.read
if result.isvalid:
return result.temperature, result.humidity
pritnresulttemperature, result.humidity
else:
printFailed to read sensor data"
return None, None
def publishdata:
global publishflag
client connecttobroker
client.loopstart
while publishflag:
temperature, humidity readdhtdata
if temperature is not None and humidity is not None:
currenttime datetime.datetime.nowstrftimeYmd H:M:S
message fsensorIDsensorLocationcurrenttimetemperature:fhumidity:f
client.publishtopic message
printPublished sensor data:", message
printSensor is connected and publishing data."
time.sleep
client.disconnect
def rolldice:
return random.randint
def main:
global publishflag
global dicerollflag
GPIO.setmodeGPIOBCM
try:
while True:
printMenu:
print Begin temperature humidity monitoring"
print End temperature humidity monitoring"
print Test Post a random dice roll
print Quit"
choice inputEnter your choice:
if choice :
if not publishflag:
publishflag True
# Start publishing data in a separate thread
threading.Threadtargetpublishdata, daemonTruestart
else:
printMonitoring is already running."
elif choice :
publishflag False
elif choice :
diceroll rolldice
client connecttobroker
client.publishtopic strdiceroll
client.disconnect
printPublished random dice roll:", diceroll
elif choice :
printExiting Thank you!"
publishflag False
break
else:
printInvalid choice. Please try again."
finally:
GPIO.cleanup
if namemain:
main
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
