# This file is executed on every boot (including wake-boot from deepsleep) import machine import gc import webrepl import network import time import urequests # Debug ENABLE_SENSORS = True # set deep sleep time ms_sleep_time = 600000 def do_connect(): wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect('wifiwifi', 'passwordpassword') while not wlan.isconnected(): print('retrying in 1 sec') time.sleep(1) print('network config:', wlan.ifconfig()) do_connect() webrepl.start() gc.collect() # NOTE: you MUST connect GPIO16 (D) to the RST pin for the board to wake after deep sleep def deep_sleep(msecs): # configure RTC.ALARM0 to be able to wake the device rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) # set RTC.ALARM0 to fire after X ms rtc.alarm(rtc.ALARM0, msecs) machine.deepsleep() def send_to_adafruit_io(feed, value): username = "XXX" aio_key = "XXXX" url = "https://io.adafruit.com/api/v2/{}/feeds/{}/data".format(username, feed) headers = {"Content-Type": "application/json", "X-AIO-Key": aio_key} data = {"value": value} try: response = urequests.post(url, headers=headers, json=data) if response.status_code == 200: print("Data sent to {} feed successfully.".format(feed)) else: print("Failed to send data to {} feed. Status code: {}".format(feed, response.status_code)) response.close() except Exception as e: print("An error occurred: {}".format(e)) if ENABLE_SENSORS: import dht # D5 on board dht_pin = machine.Pin(14) sensor = dht.DHT11(dht_pin) adc = machine.ADC(0) while True: try: # Retry reading from the sensor for _ in range(3): sensor.measure() temperature = sensor.temperature() humidity = sensor.humidity() if temperature is not None and humidity is not None: print("good") break time.sleep(1) if temperature is None or humidity is None: print("failed to get sensor readings after 3 attempts") temperature = 0 humidity = 0 for _ in range(3): adc_value = adc.read() if adc_value is not None: voltage = adc_value * (1.8 / 1023.0) sensor_voltage = voltage * (11 / 5) print("we also good") break time.sleep(1) if sensor_voltage is None: sensor_voltage = 0 # Higher moisture levels result in higher output voltages print(f"temp {temperature} humidity {humidity} voltage {sensor_voltage}") send_to_adafruit_io("temperature", temperature) send_to_adafruit_io("humidity", humidity) send_to_adafruit_io("soil-moisture", sensor_voltage) except OSError as e: print(f"Failed to read sensor. {e}") except ValueError as e: print(f"Error: {e}") gc.collect() time.sleep(20) deep_sleep(ms_sleep_time)