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

I'm trying to publish DHT11 sensor data to test. mosquitto.org. However, when I choose option 1, I keep getting failed to read sensor. The sensor is functioning and it is wired correctly to pin 17 for power and pin 18 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.mqtt.client as mqtt
import dht11
import threading
# GPIO pin configuration
POWER_PIN =17
DATA_PIN =18
# MQTT broker configuration
brokerAddress = "test.mosquitto.org"
topic ="DHT11/test"
sensorID ="DHT11"
sensorLocation = "Batcave"
# Global flags
publish_flag = False
dice_roll_flag = False
def connect_to_broker():
client = mqtt.Client()
client.connect(brokerAddress,1883,60)
return client
def read_dht11_data():
instance = dht11.DHT11(pin=DATA_PIN)
time.sleep(1)# Wait for sensor to stabilize
result = instance.read()
if result.is_valid():
return result.temperature, result.humidity
pritn(result.temperature, result.humidity)
else:
print("Failed to read sensor data")
return None, None
def publish_data():
global publish_flag
client = connect_to_broker()
client.loop_start()
while publish_flag:
temperature, humidity = read_dht11_data()
if temperature is not None and humidity is not None:
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
message = f"{sensorID},{sensorLocation},{current_time},{temperature:.1f},{humidity:.1f}"
client.publish(topic, message)
print("Published sensor data:", message)
print("Sensor is connected and publishing data.")
time.sleep(5)
client.disconnect()
def roll_dice():
return random.randint(1,20)
def main():
global publish_flag
global dice_roll_flag
GPIO.setmode(GPIO.BCM)
try:
while True:
print("Menu:")
print("1. Begin temperature / humidity monitoring")
print("2. End temperature / humidity monitoring")
print("3. Test (Post a random dice roll)")
print("4. Quit")
choice = input("Enter your choice: ")
if choice =='1':
if not publish_flag:
publish_flag = True
# Start publishing data in a separate thread
threading.Thread(target=publish_data, daemon=True).start()
else:
print("Monitoring is already running.")
elif choice =='2':
publish_flag = False
elif choice =='3':
dice_roll = roll_dice()
client = connect_to_broker()
client.publish(topic, str(dice_roll))
client.disconnect()
print("Published random dice roll:", dice_roll)
elif choice =='4':
print("Exiting... Thank you!")
publish_flag = False
break
else:
print("Invalid choice. Please try again.")
finally:
GPIO.cleanup()
if __name__=="__main__":
main()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!