🤖 Level 4 – Mobile Robotics

Project 4.4: "Weather Station with DHT11"

 

What You’ll Learn

  • Goal 1: Leer temperatura y humedad con el bloque oficial dhtx.DHT11(pin).temperature() y dhtx.DHT11(pin).humidity().
  • Goal 2: Mostrar valores en la pantalla OLED con bloques oficiales.
  • Goal 3: Enviar lecturas al PC por Serial (print) y por Bluetooth (ble_peripheral).
  • Goal 4: Activar alertas cuando los valores superen límites definidos.
  • Goal 5: Actualizar periódicamente para evitar valores desactualizados.

Blocks Glossary

  • external sensor → dhtx.DHT11(pin).temperature(): devuelve temperatura en °C.
  • external sensor → dhtx.DHT11(pin).humidity(): devuelve humedad en %.
  • oled128x64.OLED(…): crea pantalla OLED y dibuja texto/gráficos.
  • oled.shows(text,x,y,size,…): muestra texto en pantalla.
  • oled.rect/line/show: dibuja marcos y actualiza pantalla.
  • serial port → print(…): envía texto al monitor serial.
  • bluetooth → ble_peripheral.BLESimplePeripheral(name): crea periférico Bluetooth.
  • bluetooth → ble_handle.Handle().recv(cb): recibe comandos.

What You Need

ComponenteCantidadConexión
D1 R321USB cable
DHT111Señal → Pin 26, VCC 5V, GND
OLED 128×641SCL → Pin 22, SDA → Pin 21
Bluetooth1Interno

Before You Start

  • Conecta DHT11 al pin 26.
  • Conecta OLED a SCL=22 y SDA=21.
  • Abre el monitor serial.
  • Bloque de prueba:
print("Ready!")  # Confirmar que el sistema está listo

Microprojects

Microproject 4.4.1 – Lectura de temperatura y humedad

import dhtx                                        # Bloque: importar librería DHT11
import time                                        # Bloque: importar librería de tiempo

t = dhtx.DHT11(26).temperature()                   # Bloque: leer temperatura directamente del pin 26
h = dhtx.DHT11(26).humidity()                      # Bloque: leer humedad directamente del pin 26

print("[DHT11] T=", t, "C  H=", h, "%")            # Bloque: enviar valores al monitor serial
time.sleep_ms(800)                                 # Bloque: pequeña pausa para observar

Reflection: Lectura directa, simple y clara.
Challenge: Haz tres lecturas y muestra el promedio.


Microproject 4.4.2 – Mostrar en OLED

import machine                                     # Bloque: importar librería hardware
import oled128x64                                  # Bloque: importar librería OLED
import time                                        # Bloque: importar librería tiempo

i2c_extend = machine.SoftI2C(                      # Bloque: crear bus I2C
    scl = machine.Pin(22),                         # Pin SCL = 22
    sda = machine.Pin(21),                         # Pin SDA = 21
    freq = 100000                                  # Frecuencia 100 kHz
)

oled = oled128x64.OLED(i2c_extend, address=0x3c, font_address=0x3A0000, types=0)  # Bloque: crear objeto OLED

oled.rect(0,0,128,64,1)                            # Bloque: dibujar marco
oled.shows("Weather",x=4,y=4,size=1,space=0,center=False)  # Bloque: título
oled.shows("T:"+str(t)+"C",x=4,y=24,size=1,space=0,center=False)  # Bloque: temperatura
oled.shows("H:"+str(h)+"%",x=4,y=40,size=1,space=0,center=False)  # Bloque: humedad
oled.show()                                        # Bloque: actualizar pantalla
print("[OLED] Valores mostrados")                  # Bloque: confirmar en serial

Reflection: Marco y texto organizados.
Challenge: Añade línea horizontal bajo el título.


Microproject 4.4.3 – Enviar por Serial y Bluetooth

import ble_peripheral                              # Bloque: importar periférico Bluetooth
import ble_handle                                  # Bloque: importar manejador Bluetooth
import time                                        # Bloque: importar tiempo
import dhtx                                        # Bloque: importar DHT11

ble_p = ble_peripheral.BLESimplePeripheral("Weather-R32")  # Bloque: crear periférico BLE
print("[BLE] Weather-R32 listo")                   # Bloque: confirmar periférico

handle = ble_handle.Handle()                       # Bloque: crear manejador RX
print("[BLE] Handle listo")                        # Bloque: confirmar handle

def send_bt(msg):                                  # Bloque: función enviar BT
    ble_p.send(msg)                                # Bloque: enviar mensaje
    print("[BLE] TX:", msg)                        # Bloque: reflejar en serial

def handle_method(msg):                            # Bloque: función callback RX
    s = str(msg)                                   # Bloque: convertir a string
    print("[BLE] RX:", s)                          # Bloque: mostrar recibido
    if s == "REQ:NOW":                             # Bloque: condición comando
        t = dhtx.DHT11(26).temperature()           # Bloque: leer temperatura
        h = dhtx.DHT11(26).humidity()              # Bloque: leer humedad
        send_bt("DATA:T="+str(t)+";H="+str(h))     # Bloque: enviar datos
    else:                                          # Bloque: comando desconocido
        send_bt("ERR:UNKNOWN")                     # Bloque: enviar error

handle.recv(handle_method)                         # Bloque: registrar callback
print("[BLE] Callback registrado")                 # Bloque: confirmar

while True:                                        # Bloque: bucle infinito
    t = dhtx.DHT11(26).temperature()               # Bloque: leer temperatura
    h = dhtx.DHT11(26).humidity()                  # Bloque: leer humedad
    print("[Serial] T=",t,"C H=",h,"%")            # Bloque: enviar a serial
    send_bt("PERIODIC:T="+str(t)+";H="+str(h))     # Bloque: enviar por BT
    time.sleep_ms(2000)                            # Bloque: esperar 2 segundos

Reflection: Lecturas enviadas periódicamente y bajo demanda.
Challenge: Añade comandos REQ:STOP y REQ:START.


Microproject 4.4.4 – Alertas (versión completa)

import dhtx                                        # Bloque: importar librería oficial DHT11
import ble_peripheral                              # Bloque: importar periférico Bluetooth
import ble_handle                                  # Bloque: importar manejador Bluetooth
import machine                                     # Bloque: importar librería hardware para I2C
import oled128x64                                  # Bloque: importar librería oficial OLED
import time                                        # Bloque: importar librería tiempo

ble_p = ble_peripheral.BLESimplePeripheral("Weather-R32")  # Bloque: crear periférico BLE con nombre
handle = ble_handle.Handle()                       # Bloque: crear manejador RX
print("[Alert] BLE listo")                         # Bloque: confirmar periférico en serial

i2c_extend = machine.SoftI2C(                      # Bloque: crear bus I2C para OLED
    scl = machine.Pin(22),                         # Bloque: pin SCL = 22
    sda = machine.Pin(21),                         # Bloque: pin SDA = 21
    freq = 100000                                  # Bloque: frecuencia 100 kHz
)

oled = oled128x64.OLED(i2c_extend, address=0x3c, font_address=0x3A0000, types=0)  # Bloque: crear objeto OLED

TH_T_MAX = 30                                      # Bloque: umbral de temperatura en °C
TH_H_MAX = 80                                      # Bloque: umbral de humedad en %

while True:                                        # Bloque: bucle infinito para monitoreo
    t = dhtx.DHT11(26).temperature()               # Bloque: leer temperatura directamente del pin 26
    h = dhtx.DHT11(26).humidity()                  # Bloque: leer humedad directamente del pin 26

    oled.rect(0,0,128,64,1)                        # Bloque: dibujar marco en pantalla
    oled.shows("T:"+str(t)+"C",4,24,1,0,False)     # Bloque: mostrar temperatura en OLED
    oled.shows("H:"+str(h)+"%",4,40,1,0,False)     # Bloque: mostrar humedad en OLED

    if (t>=TH_T_MAX) or (h>=TH_H_MAX):             # Bloque: condición alerta si supera umbrales
        oled.shows("ALERT!",84,4,1,0,False)        # Bloque: mostrar texto ALERT en OLED
        ble_p.send("ALERT:T="+str(t)+";H="+str(h)) # Bloque: enviar alerta por Bluetooth
    else:                                          # Bloque: condición normal
        ble_p.send("OK:T="+str(t)+";H="+str(h))    # Bloque: enviar estado normal por Bluetooth

    oled.show()                                    # Bloque: actualizar pantalla OLED
    time.sleep_ms(1000)                            # Bloque: esperar 1 segundo antes de nueva lectura

Microproject 4.4.5 – Actualización periódica

import dhtx                                        # Bloque: importar DHT11
import time                                        # Bloque: importar tiempo
import ble_peripheral                              # Bloque: importar periférico Bluetooth

ble_p = ble_peripheral.BLESimplePeripheral("Weather-R32")  # Bloque: crear periférico BLE

while True:                                        # Bloque: bucle infinito
    t = dhtx.DHT11(26).temperature()               # Bloque: leer temperatura
    h = dhtx.DHT11(26).humidity()                  # Bloque: leer humedad
    ble_p.send("PERIODIC:T="+str(t)+";H="+str(h))  # Bloque: enviar valores periódicos por Bluetooth
    print("[Periodic] T=",t,"C H=",h,"%")          # Bloque: mostrar valores en serial
    time.sleep_ms(2000)                            # Bloque: esperar 2 segundos antes de repetir

Main Project – Weather Station completa

import dhtx                                        # Bloque: importar DHT11
import machine                                     # Bloque: importar hardware
import oled128x64                                  # Bloque: importar OLED
import ble_peripheral                              # Bloque: importar Bluetooth
import ble_handle                                  # Bloque: importar manejador BT
import time                                        # Bloque: importar tiempo

# Configuración OLED
i2c_extend = machine.SoftI2C(scl=machine.Pin(22), sda=machine.Pin(21), freq=100000)  # Bloque: bus I2C
oled = oled128x64.OLED(i2c_extend,address=0x3c,font_address=0x3A0000,types=0)        # Bloque: OLED

# Configuración Bluetooth
ble_p = ble_peripheral.BLESimplePeripheral("Weather-R32")  # Bloque: periférico BLE
handle = ble_handle.Handle()                               # Bloque: manejador RX
print("[Main] BLE listo")                                  # Bloque: confirmar

# Umbrales
TH_T_MAX = 30                                              # Bloque: umbral temperatura
TH_H_MAX = 80                                              # Bloque: umbral humedad

while True:                                                # Bloque: bucle principal
    t = dhtx.DHT11(26).temperature()                       # Bloque: leer temperatura
    h = dhtx.DHT11(26).humidity()                          # Bloque: leer humedad

    oled.rect(0,0,128,64,1)                                # Bloque: marco OLED
    oled.shows("T:"+str(t)+"C",4,24,1,0,False)             # Bloque: mostrar temperatura
    oled.shows("H:"+str(h)+"%",4,40,1,0,False)             # Bloque: mostrar humedad

    if (t>=TH_T_MAX) or (h>=TH_H_MAX):                     # Bloque: condición alerta
        oled.shows("ALERT!",84,4,1,0,False)                # Bloque: mostrar alerta
        ble_p.send("ALERT:T="+str(t)+";H="+str(h))         # Bloque: enviar alerta BT
    else:                                                  # Bloque: condición normal
        ble_p.send("OK:T="+str(t)+";H="+str(h))            # Bloque: enviar estado normal BT

    oled.show()                                            # Bloque: actualizar OLED
    print("[Main] T=",t,"C H=",h,"%")                      # Bloque: mostrar en serial
    time.sleep_ms(1000)                                    # Bloque: esperar 1 segundo

External Explanation

El proyecto completo se arma con bloques oficiales: lecturas directas de DHT11, visualización en OLED, envío por Bluetooth y alertas. No se usan listas, tuplas ni estructuras inventadas. Cada línea está comentada para guiar al estudiante.


Story Time

Tu estación meteorológica mide cada segundo, muestra en pantalla y te avisa por Bluetooth si la temperatura o la humedad se pasan de los límites. Es como tener un pequeño guardián del clima.


Debugging (2)

Debugging 4.4.A – Lecturas nulas

  • Añade bloque time.sleep_ms(800) entre lecturas.
  • Revisa cables y alimentación.

Debugging 4.4.B – OLED no actualiza

  • Asegúrate de usar oled.show() después de cada actualización.
  • Verifica que el bus I2C esté configurado con los pines correctos.

Final Checklist

  • Lecturas de DHT11 aparecen en Serial.
  • OLED muestra valores con marco.
  • Bluetooth envía mensajes periódicos.
  • Alertas se activan al superar límites.
  • Bucle actualiza cada segundo.

Extras

  • Tip estudiante: Cambia los límites de alerta para experimentar.
  • Tip instructor: Haz que los alumnos comparen lecturas con un termómetro real.
  • Glossary:
    • DHT11: Sensor de temperatura y humedad.
    • OLED: Pantalla gráfica pequeña.
    • BLE: Bluetooth Low Energy.
  • Mini tips:
    • Siempre usar oled.show() para ver cambios.
    • Mantener cadencia de 1 segundo para lecturas estables.
On this page