"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
from machine import Pin, I2C
from utime import sleep
import dht
from module_oled import Oled
from module_wifi import Wifi, NotConnectedException
sensor = dht.DHT22(Pin(20, Pin.IN))
heater = Pin(19, Pin.OUT)
wake_up_button = Pin(12, Pin.IN)
# dimensions de l'écran
LARGEUR = 120
HAUTEUR = 32
# initialisation i2c et oled
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=200000)
oled = Oled(scl=17, sda=16)
wifi = Wifi("Wokwi-GUEST", "")
class ReadTempException(Exception):
pass
def get_temperature():
try:
return sensor.temperature()
except OSError as e:
raise ReadTempException('Failed to read sensor.')
prev_temp = prev_hum = None
loop = 0
while True:
oled.clear()
loop += 1
print(f"loop={loop}")
# réaliser la mesure
try:
sensor.measure()
temp = sensor.temperature()
oled.push(f"T={temp}C")
hum = sensor.humidity()
oled.push(f"H={hum}%")
except OSError as e:
oled.push("Erreur mesure")
sleep(2)
continue # on retente une lecture
# on alume ou on éteint la lampe
do_heat = 1
if temp >= 40:
do_heat = 0
elif temp <= 35:
do_heat = 1
heater.value(do_heat)
if prev_temp != temp or prev_hum != hum:
# les données ont changées
# on envoie un relevé au serveur
print(f"Wifi post data: {temp} (prev. {prev_temp}), {hum} (prev. {prev_hum})")
try:
data = {
"board_name": "wokwi",
"temperature": temp,
"humidity": hum,
"heater": do_heat,
}
response = wifi.post("https://log-measure.osc-fr1.scalingo.io", data)
print(response.status_code, response.text)
oled.push("Mesures envoyees")
prev_temp = temp
prev_hum = hum
except NotConnectedException:
oled.push("Erreur wifi")
else:
oled.push("Mesures constantes")
sleep(1)