#------------------------------ [IMPORT]------------------------------------
import network, time, urequests
from machine import Pin, ADC, PWM, I2C
from dht import DHT22
from utime import sleep, sleep_ms
import ujson
from umqtt.simple import MQTTClient
from ssd1306 import SSD1306_I2C
#--------------------------- [OBJETOS]---------------------------------------
# MQTT Server Parameters
MQTT_CLIENT_ID = "wilson1651631"
MQTT_BROKER = "industrial.api.ubidots.com"
MQTT_USER = "Keiber89"
MQTT_PASSWORD = "Keiber.1804"
MQTT_TOPIC = "/v1.6/devices/dht_22"
ancho = 128
alto = 64
dht = DHT22(Pin(4))
gas = ADC(Pin(32))
buzzer = Pin(25,Pin.OUT)
led_verde =Pin(15,Pin.OUT)
led_rojo =Pin(5,Pin.OUT)
led_verde2 =Pin(18,Pin.OUT)
led_rojo2 =Pin(16,Pin.OUT)
led_wifi = Pin(26,Pin.OUT)
buzer = Pin(12)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C (ancho, alto,i2c)
#----------------------[ CONECTAR WIFI ]---------------------------------------------------------#
def conectaWifi (red, password):
global miRed
miRed = network.WLAN(network.STA_IF)
if not miRed.isconnected(): #Si no está conectado…
miRed.active(True) #activa la interface
miRed.connect(red, password) #Intenta conectar con la red
print('Conectando a la red', red +"…")
timeout = time.time ()
while not miRed.isconnected(): #Mientras no se conecte..
if (time.ticks_diff (time.time (), timeout) > 10):
return False
return True
#------------------------------------[BOT]---------------------------------------------------------------------#
if conectaWifi ("Wokwi-GUEST", ""):
print ("Conexión exitosa!")
print('Datos de la red (IP/netmask/gw/DNS):', miRed.ifconfig())
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user='BBUS-OlFLoRs4IeNzXJ2YLLiWZBcW2bfja3', password='BBUS-OlFLoRs4IeNzXJ2YLLiWZBcW2bfja3')
client.connect()
print("Connected!")
prev_weather = ""
while True:
dht.measure()
temp = int (dht.temperature())
temperatura = str(temp)
hum = dht.humidity()
humedad= str(hum)
gas.width(ADC.WIDTH_10BIT)
gas.atten(ADC.ATTN_11DB)
sensor_mq2= int(gas.read())
porcentaje = int (sensor_mq2 * 0.0978)
text_gas = str(porcentaje)
led_wifi.value(1)
# print ("t = {:02} °c h = {:02} %".format(temp ,hum))
if porcentaje >= 70:
led_verde.value(0)
led_rojo.value(1)
else:
led_verde.value(1)
led_rojo.value(0)
if temp >= 25:
led_verde2.value(0)
led_rojo2.value(1)
else:
led_verde2.value(1)
led_rojo2.value(0)
oled.text ("temperatura: " , 0,0)
oled.text (temperatura , 98,0)
oled.text ("c", 122,0)
oled.text ("humedad:" , 0,10)
oled.text (humedad , 65,10)
oled.text ("%", 105,10)
oled.text ("gas:",0,20)
oled.text (text_gas, 30,20)
oled.text ('%',55,20)
oled.text ('Keiber Espinoza',0,30)
oled.show()
oled.init_display()
message = ujson.dumps({
"temp": temp,
"hum": hum,
"gas": porcentaje,
})
if message != prev_weather:
client.publish(MQTT_TOPIC, message)
prev_weather = message
sleep(0.5)
else:
print ("Imposible conectar")
miRed.active (False)