import time
import dht
import network
import machine
from machine import Pin, PWM
import urequests
from umqtt.simple import MQTTClient
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
MQTT_Broker = "mqtt3.thingspeak.com"
MQTT_Client = "Bg81JCAPKS0mDSQ4JAc4HSM"
MQTT_Username = "Bg81JCAPKS0mDSQ4JAc4HSM"
MQTT_Password = "nxTNdJP4VG0Nobw7qThc86/B"
MQTT_Topic = "channels/2462557/publish"
Channel_Write_Key = "9L1Y1PC184QI35F2"
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to network...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
pass
print('Network config:', wlan.ifconfig())
dht_pin = Pin(27)
dht_sensor = dht.DHT22(dht_pin)
pir_sensor = Pin(22, Pin.IN, Pin.PULL_UP)
connect_to_wifi()
client = MQTTClient(MQTT_Client, MQTT_Broker, port = 1883, user = MQTT_Username, password = MQTT_Password)
client.connect()
def send_thingspeak_mqtt(temp, hum, motion, client):
payload = 'field1={}&field2={}&field3={}&api_key={}'.format(temp,hum,motion,Channel_Write_Key)
client.publish(MQTT_Topic,payload)
while True:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
motion = pir_sensor.value()
send_thingspeak_mqtt(temp,hum,motion,client)
time.sleep(15)