from machine import Pin, I2C
from time import sleep, sleep_ms, ticks_ms
import dht
import network
import urequests
import json
from i2c_lcd import I2cLcd
# LCD (16 x 2) (I2C)
AddressOfLcd = 0x27
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000) # connect scl to GPIO 22, sda to GPIO 21
lcd = I2cLcd(i2c, AddressOfLcd, 2, 16)
# Led
led=Pin(12,Pin.OUT)
# Firebase
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST","")
id_lectura = 0
id_sensor = 1
# Sensor
sensor = dht.DHT22(Pin(15))
estado = ""
fecha = ""
while not wlan.isconnected():
pass
while True:
try:
sensor.measure()
temp = sensor.temperature()
fecha = "04-09-2022"
if (temp < 20):
estado = "frio"
elif (temp >= 20 and temp <= 35):
estado = "agradable"
else:
estado = "caliente"
lcd.move_to(0,0)
lcd.putstr(" ")
lcd.move_to(0,1)
lcd.putstr(" ")
lcd.move_to(0,0)
lcd.putstr("Temp: " + str(temp) + "C")
lcd.move_to(0,1)
lcd.putstr("Est: " + estado)
URL = "https://tc2022-cadf2-default-rtdb.firebaseio.com/lecturas/01.json"
dato = "{\""+ str(id_lectura) + "\":{\"estado\":\""+estado+"\",\"fecha\":\""+str(fecha)+"\",\"idSensor\":\""+str(id_sensor)+"\",\"temperatura\":"+str(temp)+"}}"
r = urequests.patch(URL,data = dato)
led.value(1)
sleep(1)
led.value(0)
sleep(1)
led.value(1)
sleep(1)
led.value(0)
sleep(1)
led.value(1)
sleep(1)
led.value(0)
results = r.json()
id_lectura += 1
except OSError as e:
print('Falla el sensor')