from machine import Pin,time_pulse_us
import time
import os
import modfile
time.sleep(0.1) # Wait for USB to become ready
print("Hello by Pi Pico 2. Let's start!")
ramdir = '/ramdisk'
ramdir = modfile.mkRAMfs(512,32) #initializing ram disk and obtain it's directory
print(os.listdir())
# Set the Pins
Trig_Pin = 10 # Connected HC-SR04 Trig to GP10
Echo_Pin = 11 # Connecter HC-SR04 Echo to GP11
RELAY_OPEN_PIN = 2 # Controls relay2 (Green LED / Open Valve)
RELAY_CLOSE_PIN = 15 # Controls relay1 (Red LED / Close Valve)
# Water Barrel dimensions
Full_Tank_H = 10 # Heigth from top of the water when tank is full in cm
Empty_Tank_H = 92-12 # Heigth from top of the water when level is at the nozzle in cm
Drained_Tank_H = 92 # Heigth from top of the water when no water at all in cm (probably is not needed)
# Spherical Valve times
VALVE_SPIN_TIME = 5 # 5 seconds to rotate the ball valve 90 degrees
VALVE_OPEN_DURATION = 30 # Simulated 30 "minutes" as 30 seconds for easy testing
# Initialize Pin State
trig = Pin(Trig_Pin, mode = Pin.OUT)
echo = Pin(Echo_Pin, mode = Pin.IN)
relay_open = Pin(RELAY_OPEN_PIN, Pin.OUT)
relay_close = Pin(RELAY_CLOSE_PIN, Pin.OUT)
# Standard safety initialization (0 Watts drawn)
relay_open.low()
relay_close.low()
def log_data(percentage, distance):
"""Saves the measurements to a local CSV file on the Pico 2."""
try:
with open("tank200.csv", "a") as f:
# Χρήση του time.ticks_ms() για σχετικό χρόνο λειτουργίας
timestamp = time.ticks_ms() / 1000
f.write("{:.1f},{:.1f},{:.1f}\n".format(timestamp, distance, percentage))
except Exception as e:
print("Logging error:", e)
def get_level_height():
"""Triggers the ultrasonic sensor and returns measured distance in cm."""
# Ensure trigger is low
trig.value(0)
time.sleep_us(5) #sleep_us in microseconds, sleep_ms in miliseconds
# Send a 10 microsecond pulse to trigger and then back to zero state
trig.value(1) #0,1 for FALSE,TRUE states
time.sleep_us(10)
trig.value(0)
# Measure the duration of the incoming echo pulse
duration = time_pulse_us(echo, 1, 30000) # 30ms timeout, expected value 1. This function has outout -2
# if the value 1 is never met, and -1 if the measurement goes longer than 30ms
if duration < 0:
return duration # Timeout / Error
# Speed of sound is ~343 m/s or 0.0343 cm/microsec.
# Divide by 2 because the sound wave travels to the object and back.
distance = (duration * 0.0343) / 2
return distance
def trigger_valve_cycle():
"""Runs the low-power 3-wire valve execution loop."""
print("\n[CYCLE START] Target acquired within 20cm!")
# 1. Open the valve
print("⚡ Energizing OPEN wire (GP2 High - Green LED On)...")
relay_close.low() # Interlock safety check
relay_open.high()
time.sleep(VALVE_SPIN_TIME)
# 2. Park the valve Open (0 Watts Idle draw)
relay_open.low()
print(f"🔒 Valve fully OPEN. Current cut to 0W. Waiting {VALVE_OPEN_DURATION}s...")
time.sleep(VALVE_OPEN_DURATION)
# 3. Close the valve
print("⚡ Energizing CLOSE wire (GP15 High - Red LED On)...")
relay_open.low() # Interlock safety check
relay_close.high()
time.sleep(VALVE_SPIN_TIME)
# 4. Park the valve Closed (0 Watts Idle draw)
relay_close.low()
print("🔒 Valve fully CLOSED. Current cut to 0W. System standing by.")
print("--- Starting Raspberry Pi Pico 2 Water Level Monitor ---")
# Initializng data file logging
try:
with open(ramdir + "/" +"tank200.csv", "w") as f:
f.write("Timestamp(s),Distance(cm),Level(%)\n")
except Exception as e:
print("Could not initialize log file:", e)
xx=0
while xx<=5:
dist = get_level_height()
if dist == -1:
print("Sensor error: Sensor can not be initialized.")
elif dist == -2:
print("Sensor error: Out of range receiving signal.")
else:
# Calculate water level percentage
# Closer distance means a fuller tank
if dist > Empty_Tank_H:
water_level_pct = 0.0
elif dist < Full_Tank_H:
water_level_pct = 100.0
else:
# Map the distance linearly to a percentage
total_range = Empty_Tank_H - Full_Tank_H
current_fill = Empty_Tank_H - dist
water_level_pct = (current_fill / total_range) * 100.0
print(u"Distance to water: {:.1f} cm | Tank Level: {:.1f}%".format(dist, water_level_pct))
#log_data(water_level_pct, dist) # CSV log
xx=xx+1
time.sleep(1) # Refresh every second
f.close()
Loading
pi-pico-2
pi-pico-2