Can I make my plants less thirsty? Part 2 #
This week, our assignment was to create a user interface to interact with one of our input or output devices. I decided to build off of last week’s assignment and make a web interface for the soil moisture sensor.
For this assignment, I used Google’s handy firebase to store the data that the Xiao ESP32-C6 read. Firebase also created an easy way to build a web interface to see the data being read.
import network
import urequests
import time
from machine import Pin, ADC
import random
# Wi-Fi credentials
WIFI_SSID = "MIT 2"
WIFI_PASSWORD = "***"
# Firebase credentials
API_KEY = "**"
DATABASE_URL = "***" # Without "https://"
# Global variables
last_send_time = 0
count = 0
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to Wi-Fi", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.3)
print("\nConnected with IP:", wlan.ifconfig()[0])
def write_firebase_data(path, value):
url = f"https://{DATABASE_URL}/{path}.json?auth={API_KEY}"
try:
response = urequests.put(url, json=value)
if response.status_code == 200:
print(f"PASSED: {path}")
else:
print(f"FAILED: {path} - {response.status_code}: {response.text}")
except Exception as e:
print(f"Error writing to Firebase: {str(e)}")
def main():
global last_send_time, count
soil_in = ADC(0)
moisture = soil_in.read_u16() / 65535.0
connect_to_wifi()
while True:
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_send_time) > 15000:
soil_in = ADC(0)
moisture = soil_in.read_u16() / 65535.0
last_send_time = current_time
# Write an integer to the database path "test/int"
write_firebase_data("test/int", count)
count += 1
# Write a float to the database path "test/float"
float_value = round(0.01 + random.randint(0, 100), 2)
write_firebase_data("test/float", moisture)
write_firebase_data("test/float", float_value)
print("---")
if __name__ == "__main__":
main()
I then used raw HTML to create a simple user interface to read out the data from the moisture sensor, using the firebase authentication keys.