I was recently able to get this project working with a UFM01 ultrasonic water flow sensor from ScioSense https://www.sciosense.com/ufm-01-ultras ... ng-module/ (available from Digikey and Mouser for about $37) and an old Metro ESP32-S2 I had laying around. There is a recent Arduino library for the sensor, but I wanted to try it with Circuitpython. The ultrasonic sensor was a huge improvement over the Hall Effect pulse counter sensors I had been using, as they would frequently clog, and Circuitpython isn't as good with interrupts as Arduino.
The sensor itself communicates over UART to a hardware Serial port of the ESP32 (I chose IO5 and 6, as it lined up with my existing Arduino R4 shield). It sends out a BCD hex string with the serial number, flow volume, rate, and -bonus- water temperature, which can be parsed out and displayed on the serial REPL.
Once that was working, it was on to a WiFi enabled interface. The sensors are located away from any wireless networks, so the ESP is set to Access Point (AP) mode, and the user can connect to it as one would any other wireless network (192.168.4.1 and password). Security was not a major factor, so the password was kept simple. The measured parameters are displayed on a web page to either a laptop or cell phone, as well as the max flow rate (the water is pumped through the sensor, so I use it to gauge the pump health). It took a bit to get a reset button working, but the button now resets the accumulated flow logged in the sensor. (the total flow volume remains stored in the sensor's memory after removing power).
I know the styling of the code does not use the standard settings.toml file, but can be modified if needed. The attached code.py and ufm01-circuitpython.py files are all that are needed beyond the stated includes from the adafruit bundle. It is currently working on the ESP32-S2 Metro board; you can try other WiFi enabled boards and tell me how that works.
This is a project ported from the Arduino platform, and has the advantages of much faster changes than re-compiling and downloading, especially if you just need to make minor changes. The Arduino project had the code derive a unique SSID based on the ESP32's MAC address, but I kept it simple here. Most of the code length is for the web page display and controls.
Technical notes: The nature of the ultrasonic sensor is that the elements need to be immersed in water. The sensor will throw an error code if no water is present. Be sure to place is in a way that it stays full of water when any is present, like a P-trap or similar. I have mine placed above a pump's check valve.
ScioSense has a good writeup in their data sheet online. I was very happy to see an affordable and easy to implement ultrasonic flow sensor, as the turbine types I had been using would clog constantly due to small debris in the pump discharge.
The only issues I have had with these sensors are: 1: There is no reverse voltage protection diode, so either add one or be very careful when hooking it up. 2: The point where the wires enter the potting compound on the sensor is weather proof but not water proof. If the sensor is immersed in more than about a foot of water, water will eventually seep in and render the sensor inoperable.
There is also a 1-wire version of the library that uses the brown wire (seen unused in the picture). When I was working with the factory tech support (before the Arduino library came out), it was not yet supported. It now seems to work, with Arduino support for ESP32 and Mega 2560 platforms. I am testing it with the Arduino R4 Wifi, and have had some issues, which is why I gave the Circuitpython a try.
The first python code is a driver that parses the hex BCD output from the sensor. It is called ufm01_circuitpython. The second code has the webserver, etc. This is my first attempt at posting on adafruit-playground.com, so bear with me, and moderators/admin- please feel free to edit this for style and content.
"""
UFM01 CircuitPython Driver for Adafruit Metro ESP32-S2
Based on working Arduino implementation with manual hex parsing
Hardware Connections for Metro ESP32-S2:
- UFM01 TX -> Metro IO6 (UART RX)
- UFM01 RX -> Metro IO5 (UART TX)
- UFM01 VCC -> 5V
- UFM01 GND -> GND
Alternative: You can use any two IO pins that support UART
Protocol: 2400 baud, 8 data bits, Even parity, 1 stop bit
Frame Format: <3C><32>[...28 data bytes...]<16>
"""
import time
import board
import busio
# UFM01 Protocol Constants
UFM01_BAUDRATE = 2400
UFM01_START_BYTE_1 = 0x3C
UFM01_START_BYTE_2 = 0x32
UFM01_END_BYTE = 0x16
UFM01_EXPECTED_LENGTH = 32 # bytes in complete frame
# Data packet indices (from your Arduino code)
UFM_AF_START = 9 # Accumulated Flow start
UFM_AF_END = 15 # Accumulated Flow end
UFM_IF_START = 16 # Instantaneous Flow start
UFM_IF_END = 20 # Instantaneous Flow end
UFM_IF_SIGN = 20 # Sign byte for IF
UFM_TC_START = 25 # Temperature start
UFM_TC_END = 28 # Temperature end
# Command opcodes
UFM_OPCODE_CLEAR_VOLUME = 0x5A
class UFM01:
"""Driver for ScioSense UFM01 ultrasonic flow sensor"""
def __init__(self, tx_pin=board.IO5, rx_pin=board.IO6, baudrate=UFM01_BAUDRATE):
"""
Initialize UFM01 sensor
Args:
tx_pin: Board TX pin (connects to UFM01 RX) - Default IO5
rx_pin: Board RX pin (connects to UFM01 TX) - Default IO6
baudrate: UART baudrate (default 2400)
For Metro ESP32-S2:
Use IO5 (TX) and IO6 (RX) for hardware UART
Or any other IO pins that support UART
"""
# Initialize UART with Even parity (8E1)
self.uart = busio.UART(
tx_pin,
rx_pin,
baudrate=baudrate,
bits=8,
parity=busio.UART.Parity.EVEN,
stop=1,
timeout=0.1 # Non-blocking with short timeout
)
# Sensor readings
self.accumulated_flow = -999.0 # Liters (invalid when < -900)
self.instantaneous_flow = -999.0 # L/h (invalid when < -900)
self.temperature = 0.0 # Celsius
self.max_flow_rate = 0.0 # L/h peak
# Frame parsing state
self._frame_buffer = bytearray()
self._hex_string = ""
self._start1_detected = False
self._start2_detected = False
self._start1_previous = False
self._frame_complete = True
# Statistics
self.stats = {
'frames_received': 0,
'frames_parsed': 0,
'parse_errors': 0,
'last_frame_time': 0
}
print("UFM01 initialized on UART")
print(f" Baud: {baudrate}, Parity: Even, Bits: 8, Stop: 1")
@property
def is_valid(self):
"""Check if current readings are valid"""
return self.accumulated_flow > -900
def _parse_bcd_value(self, data, start, end, divisor=1.0):
"""
Parse BCD (Binary Coded Decimal) value from data bytes
Args:
data: bytearray of raw data
start: Start index
end: End index (exclusive)
divisor: Value to divide result by
Returns:
float: Parsed value
"""
multiplier = 1
value = 0
for x in range(start, end):
bcd_byte = data[x]
bcd_value = (bcd_byte & 0x0F) + ((bcd_byte >> 4) * 10)
value += bcd_value * multiplier
multiplier *= 100
return value / divisor
def _parse_accumulated_flow(self, data):
"""Parse accumulated flow from frame (BCD format, 7 bytes)"""
value = self._parse_bcd_value(data, UFM_AF_START, UFM_AF_END, 1000.0)
self.accumulated_flow = value
return value
def _parse_instantaneous_flow(self, data):
"""Parse instantaneous flow from frame (BCD format with sign, 5 bytes)"""
value = self._parse_bcd_value(data, UFM_IF_START, UFM_IF_END, 100.0)
# Check sign byte
if data[UFM_IF_SIGN] == 0x80:
value *= -1
self.instantaneous_flow = value
# Track maximum flow rate
if value > self.max_flow_rate:
self.max_flow_rate = value
return value
def _parse_temperature(self, data):
"""Parse temperature from frame (BCD format, 4 bytes)"""
value = self._parse_bcd_value(data, UFM_TC_START, UFM_TC_END, 100.0)
self.temperature = value
return value
def _process_complete_frame(self):
"""Process a complete frame and extract all values"""
try:
# Convert buffer to hex string for display
self._hex_string = ''.join(f'{b:02x}' for b in self._frame_buffer)
# Parse all values
af = self._parse_accumulated_flow(self._frame_buffer)
ifr = self._parse_instantaneous_flow(self._frame_buffer)
temp = self._parse_temperature(self._frame_buffer)
# Update statistics
self.stats['frames_received'] += 1
self.stats['frames_parsed'] += 1
self.stats['last_frame_time'] = time.monotonic()
# Print parsed values (comment out for production)
print(f"\nâś“ Frame received (#{self.stats['frames_received']})")
print(f" Accumulated Flow: {af:.3f} L")
print(f" Instantaneous Flow: {ifr:.1f} L/h")
print(f" Temperature: {temp:.1f}°C")
print(f" Max Flow Rate: {self.max_flow_rate:.1f} L/h")
return True
except Exception as e:
print(f"âś— Frame parse error: {e}")
self.stats['parse_errors'] += 1
return False
def _reset_frame_parser(self):
"""Reset frame parsing state machine"""
self._start1_detected = False
self._start2_detected = False
self._start1_previous = False
self._frame_complete = True
self._frame_buffer = bytearray() # Recreate instead of clear()
def update(self):
"""
Process incoming UART data and parse frames
Call this frequently (in main loop) to process sensor data
Returns:
bool: True if a new frame was successfully parsed
"""
frame_parsed = False
# Process all available bytes
while True:
byte_data = self.uart.read(1)
if not byte_data:
break # No more data available
current_byte = byte_data[0]
if self._start1_detected and self._start2_detected:
# Collecting data bytes
self._frame_buffer.append(current_byte)
# Check for end of frame
if (current_byte == UFM01_END_BYTE and
len(self._frame_buffer) >= UFM01_EXPECTED_LENGTH):
frame_parsed = self._process_complete_frame()
self._reset_frame_parser()
self._start1_previous = False
elif current_byte == UFM01_START_BYTE_1 and self._frame_complete:
# Start of new frame
self._frame_buffer = bytearray() # Recreate instead of clear()
self._frame_buffer.append(current_byte)
self._start1_detected = True
self._start1_previous = True
elif current_byte == UFM01_START_BYTE_2 and self._start1_previous:
# Second start byte confirmed
self._frame_buffer.append(current_byte)
self._start2_detected = True
self._start1_previous = False
self._frame_complete = False
else:
# Invalid byte sequence
self._reset_frame_parser()
return frame_parsed
def clear_accumulated_flow(self):
"""
Send command to clear sensor's accumulated flow counter
Returns:
bool: True if command sent successfully
"""
try:
# Build command packet (from your Arduino code)
cmd_packet = bytearray([
0xFE, # Header byte 1
0xFE, # Header byte 2
0x11, # Command type
UFM_OPCODE_CLEAR_VOLUME, # Opcode
0xFD, # Value
(UFM_OPCODE_CLEAR_VOLUME + 0xFD) & 0xFF, # Checksum
0x16 # End byte
])
self.uart.write(cmd_packet)
print("Command sent: Clear accumulated flow")
# Reset local max flow rate
self.max_flow_rate = 0.0
time.sleep(0.1) # Give sensor time to process
return True
except Exception as e:
print(f"Error sending command: {e}")
return False
def get_last_frame_hex(self):
"""Get hex string of last received frame for debugging"""
return self._hex_string
def print_stats(self):
"""Print communication statistics"""
print("\n=== UFM01 Statistics ===")
print(f"Frames received: {self.stats['frames_received']}")
print(f"Frames parsed: {self.stats['frames_parsed']}")
print(f"Parse errors: {self.stats['parse_errors']}")
if self.stats['last_frame_time'] > 0:
elapsed = time.monotonic() - self.stats['last_frame_time']
print(f"Time since last frame: {elapsed:.1f}s")
print("========================\n")
# ============================================================================
# EXAMPLE USAGE / TEST CODE
# ============================================================================
if __name__ == "__main__":
print("\n" + "="*50)
print("UFM01 CircuitPython Test")
print("Based on working Arduino implementation")
print("="*50 + "\n")
# Initialize sensor with Metro ESP32-S2 pins
# TX=IO5, RX=IO6
sensor = UFM01(board.IO5, board.IO6)
print("\nWaiting for sensor data...")
print("Sensor should send data automatically at ~1Hz\n")
# Main loop
loop_count = 0
last_stats_print = time.monotonic()
no_data_count = 0
while True:
loop_count += 1
# Update sensor (process incoming data)
if sensor.update():
# New frame was parsed
no_data_count = 0
# Print summary line
if sensor.is_valid:
print(f"\n📊 Current: {sensor.instantaneous_flow:.1f} L/h | "
f"Total: {sensor.accumulated_flow:.2f} L | "
f"Temp: {sensor.temperature:.1f}°C | "
f"Peak: {sensor.max_flow_rate:.1f} L/h")
else:
print("\n⚠️ Sensor offline (no valid data)")
else:
# No new frame this cycle
no_data_count += 1
# Warn if no data for extended period
if no_data_count > 50: # ~5 seconds at 100ms per loop
print("⏳ Waiting for data...")
no_data_count = 0
# Print statistics every 60 seconds
if time.monotonic() - last_stats_print > 60:
sensor.print_stats()
last_stats_print = time.monotonic()
# Small delay (sensor sends at ~1Hz, check more frequently)
time.sleep(0.1)
"""
UFM01 Web Monitor for Adafruit Metro ESP32-S2
Creates WiFi Access Point and serves real-time flow data via web interface
Save this as code.py on the CIRCUITPY drive
REQUIRED LIBRARY:
Install adafruit_httpserver library:
1. Download library bundle from: https://circuitpython.org/libraries
2. Extract adafruit_httpserver folder to CIRCUITPY/lib/
Features:
- WiFi Access Point mode
- Real-time web interface with auto-refresh
- Responsive design (mobile-friendly)
- Same styling as Arduino version
"""
import board
import time
import wifi
import socketpool
from adafruit_httpserver import Server, Request, Response
from ufm01_circuitpython import UFM01
# ============================================================================
# CONFIGURATION
# ============================================================================
# WiFi Access Point Settings
WIFI_SSID = "Circuitpython-UFM01"
WIFI_PASSWORD = "12345678" # Must be 8+ characters
WIFI_CHANNEL = 1
# Web Server Settings
WEB_PORT = 80
WEB_REFRESH_RATE = 2 # seconds
# Sensor Settings
SENSOR_TX_PIN = board.IO5
SENSOR_RX_PIN = board.IO6
# ============================================================================
# INITIALIZE HARDWARE
# ============================================================================
print("\n" + "="*50)
print("UFM01 Web Monitor - CircuitPython")
print("="*50)
# Initialize WiFi Access Point
print("\nInitializing WiFi Access Point...")
print(f" SSID: {WIFI_SSID}")
print(f" Password: {WIFI_PASSWORD}")
try:
wifi.radio.start_ap(
ssid=WIFI_SSID,
password=WIFI_PASSWORD,
channel=WIFI_CHANNEL
)
print(f"âś“ Access Point created")
print(f" IP Address: {wifi.radio.ipv4_address_ap}")
except Exception as e:
print(f"âś— WiFi AP failed: {e}")
raise
# Initialize UFM01 sensor
print("\nInitializing UFM01 sensor...")
print(f" TX: {SENSOR_TX_PIN}")
print(f" RX: {SENSOR_RX_PIN}")
sensor = UFM01(SENSOR_TX_PIN, SENSOR_RX_PIN)
print("âś“ Sensor initialized")
# Initialize HTTP Server
print(f"\nInitializing web server on port {WEB_PORT}...")
pool = socketpool.SocketPool(wifi.radio)
server = Server(pool, "/static", debug=False)
# ============================================================================
# WEB SERVER ROUTES
# ============================================================================
@server.route("/")
def base(request: Request):
"""Main page with sensor data"""
# Determine if sensor is online
sensor_online = sensor.is_valid
# Build HTML response
html = f"""<!DOCTYPE html>
<html><head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'/>
<meta charset='utf-8'>
<meta http-equiv='refresh' content='{WEB_REFRESH_RATE}'>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }}
#main {{ max-width: 600px; margin: 0 auto; background: white; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); overflow: hidden; }}
header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px 20px; text-align: center; }}
h1 {{ font-size: 28px; font-weight: 600; margin-bottom: 5px; }}
.subtitle {{ font-size: 14px; opacity: 0.9; }}
.content {{ padding: 30px 20px; }}
.metric-card {{ background: #f8f9fa; border-radius: 10px; padding: 20px; margin-bottom: 15px; border-left: 4px solid #667eea; }}
.metric-label {{ font-size: 12px; color: #6c757d; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }}
.metric-value {{ font-size: 32px; font-weight: 700; color: #2c3e50; margin-bottom: 5px; }}
.metric-unit {{ font-size: 16px; color: #6c757d; font-weight: 400; }}
.status-indicator {{ display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; }}
.status-online {{ background: #28a745; }}
.status-offline {{ background: #dc3545; }}
.button {{ display: block; width: 100%; padding: 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; text-decoration: none; text-align: center; margin-top: 20px; transition: transform 0.2s, box-shadow 0.2s; }}
.button:hover {{ transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102,126,234,0.4); }}
.button:active {{ transform: translateY(0); }}
.footer {{ text-align: center; padding: 15px; font-size: 12px; color: #6c757d; border-top: 1px solid #e9ecef; }}
.info-box {{ background: #e7f3ff; border-left: 4px solid #2196F3; padding: 15px; margin-top: 15px; border-radius: 5px; }}
.info-box p {{ font-size: 13px; color: #1976D2; margin: 5px 0; }}
@media (max-width: 480px) {{
.metric-value {{ font-size: 24px; }}
h1 {{ font-size: 24px; }}
}}
</style>
<title>UFM01 Monitor</title>
</head><body>
<div id='main'>
<header>
<h1>UFM01 Flow Monitor</h1>
<p class='subtitle'>CircuitPython Edition</p>
</header>
<div class='content'>"""
# Accumulated Flow Card
html += "<div class='metric-card'>"
html += "<div class='metric-label'>"
html += f"<span class='status-indicator {'status-online' if sensor_online else 'status-offline'}'></span>"
html += "Accumulated Flow"
if not sensor_online:
html += " (Offline)"
html += "</div>"
html += "<div class='metric-value'>"
html += f"{sensor.accumulated_flow:.2f}" if sensor_online else "---"
html += "</div>"
html += "<div class='metric-unit'>Liters</div>"
html += "</div>"
# Instantaneous Flow Card
html += "<div class='metric-card'>"
html += "<div class='metric-label'>"
html += f"<span class='status-indicator {'status-online' if sensor_online else 'status-offline'}'></span>"
html += "Instantaneous Flow Rate"
if not sensor_online:
html += " (Offline)"
html += "</div>"
html += "<div class='metric-value'>"
html += f"{sensor.instantaneous_flow:.1f}" if sensor_online else "---"
html += "</div>"
html += "<div class='metric-unit'>Liters/hour</div>"
html += "</div>"
# Temperature Card
html += "<div class='metric-card'>"
html += "<div class='metric-label'>Temperature</div>"
html += "<div class='metric-value'>"
html += f"{sensor.temperature:.1f}" if sensor_online else "---"
html += "</div>"
html += "<div class='metric-unit'>°Celsius</div>"
html += "</div>"
# Peak Flow Card
html += "<div class='metric-card'>"
html += "<div class='metric-label'>Peak Flow Rate</div>"
html += "<div class='metric-value'>"
html += f"{sensor.max_flow_rate:.1f}"
html += "</div>"
html += "<div class='metric-unit'>Liters/hour</div>"
html += "</div>"
# Statistics Info Box
html += "<div class='info-box'>"
html += f"<p><strong>Statistics:</strong></p>"
html += f"<p>Frames Received: {sensor.stats['frames_received']}</p>"
html += f"<p>Parse Errors: {sensor.stats['parse_errors']}</p>"
if sensor.stats['last_frame_time'] > 0:
elapsed = time.monotonic() - sensor.stats['last_frame_time']
html += f"<p>Last Update: {elapsed:.1f}s ago</p>"
html += "</div>"
# Reset Button
html += "<a href='/reset' class='button'>Reset Accumulated Flow</a>"
html += "</div>"
html += f"<div class='footer'>Auto-refresh every {WEB_REFRESH_RATE} seconds | Powered by CircuitPython</div>"
html += "</div></body></html>"
return Response(request, html, content_type="text/html")
@server.route("/reset")
def reset_flow(request: Request):
"""Reset accumulated flow and redirect back to main page"""
print("🔄 Reset button pressed - clearing accumulated flow")
success = sensor.clear_accumulated_flow()
if success:
print(" âś“ Accumulated flow cleared successfully")
message = "Reset OK"
else:
print(" âś— Failed to clear accumulated flow")
message = "Reset failed"
# Robust redirect: 302 + Location header + meta refresh + JS
html = f"""<!DOCTYPE html>
<html><head>
<meta charset='utf-8'>
<title>Redirecting…</title>
<meta http-equiv='refresh' content='0; url=/' />
<script>location.replace('/');</script>
<style>body{{font-family:Arial,sans-serif}} .msg{{margin:2rem}}</style>
</head><body>
<div class='msg'>{message}. Returning to main page… <a href='/'>Continue</a></div>
</body></html>
"""
return Response(
request,
html,
content_type="text/html",
headers={"Location": "/"},
status=(302, "Found"),
)
# ============================================================================
# START SERVER AND MAIN LOOP
# ============================================================================
print("âś“ Web server initialized")
print("\n" + "="*50)
print("System Ready!")
print("="*50)
print(f"\nConnect to WiFi: {WIFI_SSID}")
print(f"Visit: http://{wifi.radio.ipv4_address_ap}")
print("\nMonitoring sensor data...\n")
# Start the server
server.start(str(wifi.radio.ipv4_address_ap), port=WEB_PORT)
# Main loop
last_sensor_print = time.monotonic()
while True:
# Update sensor data
if sensor.update():
# Print to console occasionally
if time.monotonic() - last_sensor_print > 5:
print(f"📊 Flow: {sensor.instantaneous_flow:.1f} L/h | "
f"Total: {sensor.accumulated_flow:.2f} L | "
f"Temp: {sensor.temperature:.1f}°C")
last_sensor_print = time.monotonic()
# Poll the server (handles incoming requests)
try:
server.poll()
except Exception as e:
print(f"Server error: {e}")
time.sleep(0.1)
# Small delay to prevent CPU hogging
time.sleep(0.001)
This page (Show And Tell: A self contained Circuitpython WiFi enabled Ultrasonic Water Flow Sensor! Post) was last updated on January 09, 2026.