import network
import time
from machine import Pin
import dht
import BlynkLib
import utime as time
led0 = Pin(19, Pin.OUT)
led2 = Pin(2, Pin.OUT)
# Blynk App
# BLYNK_TEMPLATE_ID = "TMPLVGh_Emkv"
# BLYNK_AUTH_TOKEN = "FlrYr2KcJ9tFlzJd_Ybq7iIqbwPK7rsO"
BLYNK_AUTH = 'FlrYr2KcJ9tFlzJd_Ybq7iIqbwPK7rsO'
# Handle connection error
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# DHT Pin
dht22 = dht.DHT22(Pin(4))
def get_temperature_and_humidity():
dht22.measure()
temperature = dht22.temperature()
humidity = dht22.humidity()
print("Temperature: ", temperature, "Humidity: ", humidity)
return temperature, humidity
# ########## Blynk sent ################ #
def Blynk_sent():
try:
#blynk = BlynkLib.Blynk(BLYNK_AUTH)
#blynk = BlynkLib.Blynk(BLYNK_AUTH, insecure=True)
temperature, humidity = get_temperature_and_humidity()
blynk.virtual_write(3, temperature)
blynk.virtual_write(4, humidity)
blynk.run()
except OSError as e:
print("Error to connecting Blynk")
# ##################################### #
blynk = BlynkLib.Blynk(BLYNK_AUTH, insecure=True)
# Loop Condition
# Register virtual pin handler
@blynk.on("V0") #virtual pin V0
def v0_write_handler(value): #read the value
print("Virtual PinV0 Status: ", value[0])
if int(value[0]) == 1:
#led1.value(1) #turn the led on
led0.on() #turn the led on
print("Trun ON")
else:
#led1.value(0) #turn the led off
led0.off()
print("Trun OFF")
@blynk.on("V1") #virtual pin V0
def v1_write_handler(value): #read the value
print("Virtual PinV1 Status: ", value[0])
if int(value[0]) == 1:
#led1.value(1) #turn the led on
led2.on() #turn the led on
print("Trun ON")
else:
#led1.value(0) #turn the led off
led2.off()
print("Trun OFF")
while True:
try:
# dht22.measure()
# temperature = dht22.temperature()
# humidity = dht22.humidity()
# print("Temperature: ", temperature, "Humidity: ", humidity)
# blynk.virtual_write(3, temperature)
# blynk.virtual_write(4, humidity)
# blynk.run()
# print("sent ")
get_temperature_and_humidity()
Blynk_sent()
print("Data sent to blynk ...")
time.sleep(1)
except OSError as e:
print("Error in loop")