DHT11/DHT22 with Raspberry Pi

Try this

import adafruit_dht
from board import *
import cayenne.client as cayenne
import time

#GPIO17
SENSOR_PIN = D17

dht22 = adafruit_dht.DHT22(SENSOR_PIN, use_pulseio=False)

#time.sleep(60) #Sleep to allow wireless to connect before starting MQTT

MQTT_USERNAME = " "
MQTT_PASSWORD = " "
MQTT_CLIENT_ID = " "
client = cayenne.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

timestamp = 0

while True:
	client.loop()
	
	if (time.time() > timestamp + 5):
		temperature = dht22.temperature
		humidity = dht22.humidity
		
	if temp22 is not None:
		temp22 = "temp,c=" + str(temp22)
		Print(temp22)
		mqttc.publish(topic_dht22_temp, payload=temp22, retain=True)
	else:
		Print("Sensor error")
		
	if humidity22 is not None:
		humidity22 = "rel_hum,p=" + str(humidity22)
		Print(humidity22)
		mqttc.publish(topic_dht22_humidity, payload=humidity22, retain=True)
	else:
		Print("Sensor error")
		
	timestamp = time.time()

hi adam, i received this log

mqttc.publish(topic_dht22_temp, payload=temp22, retain=True)
NameError: name ‘mqttc’ is not defined

I only changed the code you pasted above. Was this always the issue?

hi adam, i manage to get it works using this code, made few changes on the code and save it in cayenne directory, the widget appears but it keep showing the device is offline and online, non-stop connecting and disconnecting.

import adafruit_dht
from board import *
import cayenne.client as cayenne
import time

#GPIO17
SENSOR_PIN = D17

dht22 = adafruit_dht.DHT22(SENSOR_PIN, use_pulseio=False)

time.sleep(30) #Sleep to allow wireless to connect before starting MQTT

MQTT_USERNAME = " "
MQTT_PASSWORD = " "
MQTT_CLIENT_ID = " "
client = cayenne.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

timestamp = 0

while True:
client.loop()

if (time.time() > timestamp + 5):
temp22 = dht22.temperature
humidity22 = dht22.humidity

if temp22 is not None:
temp22 = “temp,c=” + str(temp22)
print(temp22)
client.virtualWrite(1, temp22, “temp”, “c”)
else:
print(“Sensor error”)

if humidity22 is not None:
humidity22 = “rel_hum,p=” + str(humidity22)
print(humidity22)
client.virtualWrite(2, humidity22, “rel_hum”, “p”)
else:
print(“Sensor error”)

timestamp = time.time()

Do you have more than 1 device using the same MQTT client ID?

You appear to have some wiring problems. It shouldn’t take that long to get a valid reading. Are you sure the adafruit test python script was working correctly?

hi adam, sorry for the late reply, im feeling under the weather, i have double check the wiring, its connected right. and i have follow the adafruit test python script correctly. i have double confirm by changing all the wiring, but still it keep online and offline for a while then it appear offline.