import machine
import network
import urequests
import time
from machine import Pin, I2C, PWM
import ssd1306
import dht
from hcsr04 import HCSR04
from servo import Servo
import umail
#Alterar dependiendo de las conexiones
ssid = 'Wokwi-GUEST'
password = ''
url_base = "https://api.thingspeak.com/update?api_key=TF02XVCL8KB20Z7Q"
def conectar_wifi():
red = network.WLAN(network.STA_IF)
if not red.isconnected():
red.active(True)
red.connect(ssid, password)
while not red.isconnected():
print("Conectando a la red...")
time.sleep(1)
print('Conexión establecida:', red.ifconfig())
def net_conn():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def enviar_datos(**kwargs):
try:
url = url_base
for key, value in kwargs.items():
url += f"&{key}={value}"
respuesta = urequests.get(url)
print("Datos enviados. Respuesta:", respuesta.status_code)
respuesta.close()
except Exception as e:
print("Error al enviar datos:", e)
#Set max/min level and actuators setpoints
max_level = 40 #max height
min_level = 190 #min height
def calculate_percentage(height):
# if(height < 40 or height > 190):
# return "Out of bounds"
envelope = max_level - min_level
corrected_height = height - min_level
percentage = (corrected_height * 100)/envelope
alerta_20(percentage)
return percentage
# Inicializar motor
servo_motor = Servo(pin = 23)
servo_motor.move(0)
pos_servo = 0
def motor_control(woter_percentage, motor_pos):
if(woter_percentage > 90):
servo_motor.move(0)
return 0
if(woter_percentage < 30):
servo_motor.move(90)
return 1
return motor_pos
#conectar_wifi()
net_conn()
#Configuracion LED indicador
led_alerta = Pin(12, Pin.OUT)
def alerta_20(woter_fill):
if(woter_fill < 20):
led_alerta.on()
else:
led_alerta.off()
#Configuracion alerta tablero abierto
switch_tablero = Pin(22, Pin.IN)
last_state = -1
def email_alert():
smtp = umail.SMTP('smtp.gmail.com', 465, ssl=True)
smtp.login('[email protected]', 'cnxt awhe gjob xfzr')
smtp.to('[email protected]')
smtp.write('Alerta tablero abierto')
smtp.send()
smtp.quit()
print('Email Sent')
#Configuracion de pines en los sensores y display
i2c = I2C(sda=Pin(19), scl=Pin(18)) #display
display = ssd1306.SSD1306_I2C(128, 64, i2c)
#sensor ultrasonico
sonic_sensor = HCSR04(trigger_pin = 16, echo_pin = 17,echo_timeout_us = 1000000)
#sensor temperatura humedad
temp_sensor = dht.DHT22(Pin(21))
ultimo_envio = time.ticks_ms()
ultimo_refresco = time.ticks_ms()
while True:
try:
actual = time.ticks_ms()
# Si la diferencia entre el tiempo actual y el ultimo refesco es mayor o igual a 500ms
if time.ticks_diff(actual, ultimo_refresco) >= 500:
# Leer datos del sensor temperatura
temp_sensor.measure()
temp = temp_sensor.temperature() # Temperatura en grados Celsius
hum = temp_sensor.humidity() # Humedad relativa en porcentaje
# Leer datos del sensor ultrasonico
woter = sonic_sensor.distance_cm()
woter_per = calculate_percentage(woter)
#Usar datos para mover motor
pos_servo = motor_control(woter_per, pos_servo)
#Revisar tablero
current_state = switch_tablero.value()
if(current_state == 0):
if(last_state == 1):
print("Enviando email")
email_alert()
status_tablero = 'Open'
else:
status_tablero = 'Closed'
last_state = current_state
# Limpiar la pantalla antes de mostrar nuevos datos
display.fill(0)
# Mostrar los datos en la pantalla OLED
display.text('Temp: {:.1f} C'.format(temp), 0, 0, 1)
display.text('Hum: {:.1f} %'.format(hum), 0, 10, 1)
display.text('Fill: {:.0f} %'.format(woter_per), 0, 20, 1)
display.text('Motor: {:.0f} '.format(pos_servo), 0, 30, 1)
display.text('Tablero: {}'.format(status_tablero), 0, 40, 1)
# Enviar los datos a la pantalla
display.show()
ultimo_refresco = actual
# Si la diferencia entre el tiempo actual y el ultimo envio es mayor o igual a 15s
if time.ticks_diff(actual, ultimo_envio) >= 15000:
# Envío de datos a ThingSpeak
enviar_datos(field1=temp, field2=hum, field3=woter_per, field4=pos_servo, field5=current_state) #agregue los fields necesarios
ultimo_envio = actual
except OSError as e:
print("Error leyendo el sensor DHT22")
time.sleep(1)
except Exception as e:
print("Error en la ejecución del programa:", e)
conectar_wifi() # Reintentar conexión si hay un error