import network
import time
import json
from umqtt.simple import MQTTClient
from machine import Pin
from time import sleep
import dht
Sensor_Data = dht.DHT22(Pin(4))
#Connecting the Controller with Internet
print("Connecting to Internet")
sta=network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST','')
while not sta.isconnected():
print(".",end="")
time.sleep(0.2)
print("connected")
#Declaring Constant
mqtt_bro="broker.hivemq.com"
mqtt_port=1883
mqtt_topic="T"
client_id="subigeer"
#MQTT Instance
mqtt=MQTTClient(client_id,mqtt_bro,port=mqtt_port)
#function for connecting mqtt
def conn_mqtt():
try:
print("Connecting MQTT")
mqtt.connect()
except Exception as e:
print("Exception due to",str(e))
conn_mqtt()
while True:
try:
sleep(2)
Sensor_Data.measure()
Temperature_in_Celsius = Sensor_Data .temperature()
Temperature_in_Fahrenheit= Temperature_in_Celsius * (1.8) + 32.0
Humidity = Sensor_Data .humidity()
mqtt.publish(mqtt_topic,str(Temperature_in_Celsius))
print('Data published with temp as topic')
except OSError as e:
print('Failed to read sensor.')