"""
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
"""
import network
import time
from machine import Pin, ADC
import dht
import ujson
from umqtt.simple import MQTTClient
import onewire, ds18x20
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
soil_sensor1 = ADC(Pin(14) )
soil_sensor2 = ADC(Pin(13) )
soil_sensor3 = ADC(Pin(12) )
threshold_low = 20
threshold_high = 80
max_level = 65535
ds_pin = Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
roms = ds_sensor.scan()
print('Found DS devices: ', roms)
#print("Connecting to WiFi", end="")
#sta_if = network.WLAN(network.STA_IF)
#sta_if.active(True)
#sta_if.connect('Wokwi-GUEST', '')
#while not sta_if.isconnected():
# print(".", end="")
# time.sleep(0.1)
#print(" Connected!")
#print("Connecting to MQTT server... ", end="")
#client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
#client.connect()
#print("Connected!")
moisture=[0,0,0]
temperature=[0.0,0.0,0.0]
prev_weather = ""
while True:
print("Measuring soil conditions... ", end="")
moisture[0] = int(soil_sensor1.read_u16()*100/max_level)
moisture[1] = int(soil_sensor2.read_u16()*100/max_level)
moisture[2] = int(soil_sensor3.read_u16()*100/max_level)
ds_sensor.convert_temp()
time.sleep_ms(750)
for rom in roms:
i=roms.index(rom)
temperature[i]=ds_sensor.read_temp(rom)
message = ujson.dumps({
"m1": moisture[0],
"m2": moisture[1],
"m3": moisture[2],
"t1": temperature[0],
"t2": temperature[1],
"t3": temperature[2],
})
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
# client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print("No change")
time.sleep(1)