from machine import Pin,time_pulse_us
import time
import os
time.sleep(0.1) # Wait for USB to become ready
print("Hello by Pi Pico 2. Let's start!")
print(os.listdir())
'''
# =====================================================================
# ΑΥΤΟΜΑΤΗ ΔΙΟΡΘΩΣΗ ΓΙΑ ΤΟ WOKWI (Δημιουργία εικονικού δίσκου στη μνήμη)
# =====================================================================
try:
os.stat('tank200.csv')
except OSError:
try:
print('trying2')
import vfs
from flashbdev import bdev
vfs.VfsLfs2.mkfs(bdev)
vfs.mount(bdev, '/')
print("Wokwi Storage Initialized Successfully!")
except Exception:
print('trying3')
# Εναλλακτική μέθοδος αν η flashbdev δεν υποστηρίζεται στον εξομοιωτή
try:
os.mount(Flash(), '/')
except:
print('trying4')
pass
# =====================================================================
'''
Trig_Pin = 10 # Connected to GP10
Echo_Pin = 11 # Connecter to GP11
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)
# Initialize Pin State
trig = Pin(Trig_Pin, mode = Pin.OUT)
echo = Pin(Echo_Pin, mode = Pin.IN)
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))
f.close()
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
print("--- Starting Raspberry Pi Pico 2 Water Level Monitor ---")
try:
with open("tank200.csv", "w") as f:
f.write("Timestamp(s),Distance(cm),Level(%)\n")
f.close()
except Exception as e:
print("Could not initialize log file:", e)
xx=0
while xx<=10:
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 secondLoading
pi-pico-2
pi-pico-2