[{"element_type":"text","content":"\n  \n  \n  \n        \u003cp\u003e\u003cspan\u003eI was recently able to get this project working with a UFM01 ultrasonic water flow sensor from ScioSense\u0026nbsp;\u003c/span\u003e\u003ca class=\"postlink\" href=\"https://www.sciosense.com/ufm-01-ultrasonic-flow-sensing-module/\"\u003ehttps://www.sciosense.com/ufm-01-ultras ... ng-module/\u003c/a\u003e\u003cspan\u003e\u0026nbsp;(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.\u003c/span\u003e\u003cbr\u003e\u003cspan\u003eThe 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.\u003c/span\u003e\u003cbr\u003e\u003cspan\u003eOnce 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).\u003c/span\u003e\u003cbr\u003e\u003cspan\u003eI 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.\u003c/span\u003e\u003cbr\u003e\u003cspan\u003eThis 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.\u003c/span\u003e\u003c/p\u003e\n\u003cp\u003e\u003cspan\u003eTechnical notes:\u0026nbsp; \u0026nbsp;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.\u003cbr\u003eScioSense 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.\u003cbr\u003eThe 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.\u003cbr\u003eThere 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.\u003c/span\u003e\u003c/p\u003e\n\u003cp\u003e\u003cspan\u003eThe first python code is a driver that parses the hex BCD output from the sensor.\u0026nbsp; It is called ufm01_circuitpython.\u0026nbsp; The second code has the webserver, etc.\u0026nbsp; 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.\u003c/span\u003e\u003c/p\u003e\n      \n\n\n","metadata":{}},{"element_type":"code","content":"\"\"\"\nUFM01 CircuitPython Driver for Adafruit Metro ESP32-S2\nBased on working Arduino implementation with manual hex parsing\n\nHardware Connections for Metro ESP32-S2:\n- UFM01 TX -\u003e Metro IO6 (UART RX)\n- UFM01 RX -\u003e Metro IO5 (UART TX)\n- UFM01 VCC -\u003e 5V\n- UFM01 GND -\u003e GND\n\nAlternative: You can use any two IO pins that support UART\n\nProtocol: 2400 baud, 8 data bits, Even parity, 1 stop bit\nFrame Format: \u003c3C\u003e\u003c32\u003e[...28 data bytes...]\u003c16\u003e\n\"\"\"\n\nimport time\nimport board\nimport busio\n\n# UFM01 Protocol Constants\nUFM01_BAUDRATE = 2400\nUFM01_START_BYTE_1 = 0x3C\nUFM01_START_BYTE_2 = 0x32\nUFM01_END_BYTE = 0x16\nUFM01_EXPECTED_LENGTH = 32  # bytes in complete frame\n\n# Data packet indices (from your Arduino code)\nUFM_AF_START = 9    # Accumulated Flow start\nUFM_AF_END = 15     # Accumulated Flow end\nUFM_IF_START = 16   # Instantaneous Flow start\nUFM_IF_END = 20     # Instantaneous Flow end\nUFM_IF_SIGN = 20    # Sign byte for IF\nUFM_TC_START = 25   # Temperature start\nUFM_TC_END = 28     # Temperature end\n\n# Command opcodes\nUFM_OPCODE_CLEAR_VOLUME = 0x5A\n\n\nclass UFM01:\n    \"\"\"Driver for ScioSense UFM01 ultrasonic flow sensor\"\"\"\n    \n    def __init__(self, tx_pin=board.IO5, rx_pin=board.IO6, baudrate=UFM01_BAUDRATE):\n        \"\"\"\n        Initialize UFM01 sensor\n        \n        Args:\n            tx_pin: Board TX pin (connects to UFM01 RX) - Default IO5\n            rx_pin: Board RX pin (connects to UFM01 TX) - Default IO6\n            baudrate: UART baudrate (default 2400)\n            \n        For Metro ESP32-S2:\n            Use IO5 (TX) and IO6 (RX) for hardware UART\n            Or any other IO pins that support UART\n        \"\"\"\n        # Initialize UART with Even parity (8E1)\n        self.uart = busio.UART(\n            tx_pin, \n            rx_pin, \n            baudrate=baudrate,\n            bits=8,\n            parity=busio.UART.Parity.EVEN,\n            stop=1,\n            timeout=0.1  # Non-blocking with short timeout\n        )\n        \n        # Sensor readings\n        self.accumulated_flow = -999.0  # Liters (invalid when \u003c -900)\n        self.instantaneous_flow = -999.0  # L/h (invalid when \u003c -900)\n        self.temperature = 0.0  # Celsius\n        self.max_flow_rate = 0.0  # L/h peak\n        \n        # Frame parsing state\n        self._frame_buffer = bytearray()\n        self._hex_string = \"\"\n        self._start1_detected = False\n        self._start2_detected = False\n        self._start1_previous = False\n        self._frame_complete = True\n        \n        # Statistics\n        self.stats = {\n            'frames_received': 0,\n            'frames_parsed': 0,\n            'parse_errors': 0,\n            'last_frame_time': 0\n        }\n        \n        print(\"UFM01 initialized on UART\")\n        print(f\"  Baud: {baudrate}, Parity: Even, Bits: 8, Stop: 1\")\n    \n    @property\n    def is_valid(self):\n        \"\"\"Check if current readings are valid\"\"\"\n        return self.accumulated_flow \u003e -900\n    \n    def _parse_bcd_value(self, data, start, end, divisor=1.0):\n        \"\"\"\n        Parse BCD (Binary Coded Decimal) value from data bytes\n        \n        Args:\n            data: bytearray of raw data\n            start: Start index\n            end: End index (exclusive)\n            divisor: Value to divide result by\n            \n        Returns:\n            float: Parsed value\n        \"\"\"\n        multiplier = 1\n        value = 0\n        \n        for x in range(start, end):\n            bcd_byte = data[x]\n            bcd_value = (bcd_byte \u0026 0x0F) + ((bcd_byte \u003e\u003e 4) * 10)\n            value += bcd_value * multiplier\n            multiplier *= 100\n        \n        return value / divisor\n    \n    def _parse_accumulated_flow(self, data):\n        \"\"\"Parse accumulated flow from frame (BCD format, 7 bytes)\"\"\"\n        value = self._parse_bcd_value(data, UFM_AF_START, UFM_AF_END, 1000.0)\n        self.accumulated_flow = value\n        return value\n    \n    def _parse_instantaneous_flow(self, data):\n        \"\"\"Parse instantaneous flow from frame (BCD format with sign, 5 bytes)\"\"\"\n        value = self._parse_bcd_value(data, UFM_IF_START, UFM_IF_END, 100.0)\n        \n        # Check sign byte\n        if data[UFM_IF_SIGN] == 0x80:\n            value *= -1\n        \n        self.instantaneous_flow = value\n        \n        # Track maximum flow rate\n        if value \u003e self.max_flow_rate:\n            self.max_flow_rate = value\n        \n        return value\n    \n    def _parse_temperature(self, data):\n        \"\"\"Parse temperature from frame (BCD format, 4 bytes)\"\"\"\n        value = self._parse_bcd_value(data, UFM_TC_START, UFM_TC_END, 100.0)\n        self.temperature = value\n        return value\n    \n    def _process_complete_frame(self):\n        \"\"\"Process a complete frame and extract all values\"\"\"\n        try:\n            # Convert buffer to hex string for display\n            self._hex_string = ''.join(f'{b:02x}' for b in self._frame_buffer)\n            \n            # Parse all values\n            af = self._parse_accumulated_flow(self._frame_buffer)\n            ifr = self._parse_instantaneous_flow(self._frame_buffer)\n            temp = self._parse_temperature(self._frame_buffer)\n            \n            # Update statistics\n            self.stats['frames_received'] += 1\n            self.stats['frames_parsed'] += 1\n            self.stats['last_frame_time'] = time.monotonic()\n            \n            # Print parsed values (comment out for production)\n            print(f\"\\n✓ Frame received (#{self.stats['frames_received']})\")\n            print(f\"  Accumulated Flow: {af:.3f} L\")\n            print(f\"  Instantaneous Flow: {ifr:.1f} L/h\")\n            print(f\"  Temperature: {temp:.1f}°C\")\n            print(f\"  Max Flow Rate: {self.max_flow_rate:.1f} L/h\")\n            \n            return True\n            \n        except Exception as e:\n            print(f\"✗ Frame parse error: {e}\")\n            self.stats['parse_errors'] += 1\n            return False\n    \n    def _reset_frame_parser(self):\n        \"\"\"Reset frame parsing state machine\"\"\"\n        self._start1_detected = False\n        self._start2_detected = False\n        self._start1_previous = False\n        self._frame_complete = True\n        self._frame_buffer = bytearray()  # Recreate instead of clear()\n    \n    def update(self):\n        \"\"\"\n        Process incoming UART data and parse frames\n        Call this frequently (in main loop) to process sensor data\n        \n        Returns:\n            bool: True if a new frame was successfully parsed\n        \"\"\"\n        frame_parsed = False\n        \n        # Process all available bytes\n        while True:\n            byte_data = self.uart.read(1)\n            if not byte_data:\n                break  # No more data available\n            \n            current_byte = byte_data[0]\n            \n            if self._start1_detected and self._start2_detected:\n                # Collecting data bytes\n                self._frame_buffer.append(current_byte)\n                \n                # Check for end of frame\n                if (current_byte == UFM01_END_BYTE and \n                    len(self._frame_buffer) \u003e= UFM01_EXPECTED_LENGTH):\n                    \n                    frame_parsed = self._process_complete_frame()\n                    self._reset_frame_parser()\n                \n                self._start1_previous = False\n                \n            elif current_byte == UFM01_START_BYTE_1 and self._frame_complete:\n                # Start of new frame\n                self._frame_buffer = bytearray()  # Recreate instead of clear()\n                self._frame_buffer.append(current_byte)\n                self._start1_detected = True\n                self._start1_previous = True\n                \n            elif current_byte == UFM01_START_BYTE_2 and self._start1_previous:\n                # Second start byte confirmed\n                self._frame_buffer.append(current_byte)\n                self._start2_detected = True\n                self._start1_previous = False\n                self._frame_complete = False\n                \n            else:\n                # Invalid byte sequence\n                self._reset_frame_parser()\n        \n        return frame_parsed\n    \n    def clear_accumulated_flow(self):\n        \"\"\"\n        Send command to clear sensor's accumulated flow counter\n        \n        Returns:\n            bool: True if command sent successfully\n        \"\"\"\n        try:\n            # Build command packet (from your Arduino code)\n            cmd_packet = bytearray([\n                0xFE,  # Header byte 1\n                0xFE,  # Header byte 2\n                0x11,  # Command type\n                UFM_OPCODE_CLEAR_VOLUME,  # Opcode\n                0xFD,  # Value\n                (UFM_OPCODE_CLEAR_VOLUME + 0xFD) \u0026 0xFF,  # Checksum\n                0x16   # End byte\n            ])\n            \n            self.uart.write(cmd_packet)\n            print(\"Command sent: Clear accumulated flow\")\n            \n            # Reset local max flow rate\n            self.max_flow_rate = 0.0\n            \n            time.sleep(0.1)  # Give sensor time to process\n            return True\n            \n        except Exception as e:\n            print(f\"Error sending command: {e}\")\n            return False\n    \n    def get_last_frame_hex(self):\n        \"\"\"Get hex string of last received frame for debugging\"\"\"\n        return self._hex_string\n    \n    def print_stats(self):\n        \"\"\"Print communication statistics\"\"\"\n        print(\"\\n=== UFM01 Statistics ===\")\n        print(f\"Frames received: {self.stats['frames_received']}\")\n        print(f\"Frames parsed: {self.stats['frames_parsed']}\")\n        print(f\"Parse errors: {self.stats['parse_errors']}\")\n        \n        if self.stats['last_frame_time'] \u003e 0:\n            elapsed = time.monotonic() - self.stats['last_frame_time']\n            print(f\"Time since last frame: {elapsed:.1f}s\")\n        \n        print(\"========================\\n\")\n\n\n# ============================================================================\n# EXAMPLE USAGE / TEST CODE\n# ============================================================================\n\nif __name__ == \"__main__\":\n    print(\"\\n\" + \"=\"*50)\n    print(\"UFM01 CircuitPython Test\")\n    print(\"Based on working Arduino implementation\")\n    print(\"=\"*50 + \"\\n\")\n    \n    # Initialize sensor with Metro ESP32-S2 pins\n    # TX=IO5, RX=IO6\n    sensor = UFM01(board.IO5, board.IO6)\n    \n    print(\"\\nWaiting for sensor data...\")\n    print(\"Sensor should send data automatically at ~1Hz\\n\")\n    \n    # Main loop\n    loop_count = 0\n    last_stats_print = time.monotonic()\n    no_data_count = 0\n    \n    while True:\n        loop_count += 1\n        \n        # Update sensor (process incoming data)\n        if sensor.update():\n            # New frame was parsed\n            no_data_count = 0\n            \n            # Print summary line\n            if sensor.is_valid:\n                print(f\"\\n📊 Current: {sensor.instantaneous_flow:.1f} L/h | \"\n                      f\"Total: {sensor.accumulated_flow:.2f} L | \"\n                      f\"Temp: {sensor.temperature:.1f}°C | \"\n                      f\"Peak: {sensor.max_flow_rate:.1f} L/h\")\n            else:\n                print(\"\\n⚠️  Sensor offline (no valid data)\")\n        else:\n            # No new frame this cycle\n            no_data_count += 1\n            \n            # Warn if no data for extended period\n            if no_data_count \u003e 50:  # ~5 seconds at 100ms per loop\n                print(\"⏳ Waiting for data...\")\n                no_data_count = 0\n        \n        # Print statistics every 60 seconds\n        if time.monotonic() - last_stats_print \u003e 60:\n            sensor.print_stats()\n            last_stats_print = time.monotonic()\n        \n        # Small delay (sensor sends at ~1Hz, check more frequently)\n        time.sleep(0.1)","metadata":{"language":"python","linenums":false,"filename":""}},{"element_type":"code","content":"\"\"\"\nUFM01 Web Monitor for Adafruit Metro ESP32-S2\nCreates WiFi Access Point and serves real-time flow data via web interface\n\nSave this as code.py on the CIRCUITPY drive\n\nREQUIRED LIBRARY:\nInstall adafruit_httpserver library:\n1. Download library bundle from: https://circuitpython.org/libraries\n2. Extract adafruit_httpserver folder to CIRCUITPY/lib/\n\nFeatures:\n- WiFi Access Point mode\n- Real-time web interface with auto-refresh\n- Responsive design (mobile-friendly)\n- Same styling as Arduino version\n\"\"\"\n\nimport board\nimport time\nimport wifi\nimport socketpool\nfrom adafruit_httpserver import Server, Request, Response\nfrom ufm01_circuitpython import UFM01\n\n# ============================================================================\n# CONFIGURATION\n# ============================================================================\n\n# WiFi Access Point Settings\nWIFI_SSID = \"Circuitpython-UFM01\"\nWIFI_PASSWORD = \"12345678\"  # Must be 8+ characters\nWIFI_CHANNEL = 1\n\n# Web Server Settings\nWEB_PORT = 80\nWEB_REFRESH_RATE = 2  # seconds\n\n# Sensor Settings\nSENSOR_TX_PIN = board.IO5\nSENSOR_RX_PIN = board.IO6\n\n# ============================================================================\n# INITIALIZE HARDWARE\n# ============================================================================\n\nprint(\"\\n\" + \"=\"*50)\nprint(\"UFM01 Web Monitor - CircuitPython\")\nprint(\"=\"*50)\n\n# Initialize WiFi Access Point\nprint(\"\\nInitializing WiFi Access Point...\")\nprint(f\"  SSID: {WIFI_SSID}\")\nprint(f\"  Password: {WIFI_PASSWORD}\")\n\ntry:\n    wifi.radio.start_ap(\n        ssid=WIFI_SSID,\n        password=WIFI_PASSWORD,\n        channel=WIFI_CHANNEL\n    )\n    print(f\"✓ Access Point created\")\n    print(f\"  IP Address: {wifi.radio.ipv4_address_ap}\")\nexcept Exception as e:\n    print(f\"✗ WiFi AP failed: {e}\")\n    raise\n\n# Initialize UFM01 sensor\nprint(\"\\nInitializing UFM01 sensor...\")\nprint(f\"  TX: {SENSOR_TX_PIN}\")\nprint(f\"  RX: {SENSOR_RX_PIN}\")\n\nsensor = UFM01(SENSOR_TX_PIN, SENSOR_RX_PIN)\nprint(\"✓ Sensor initialized\")\n\n# Initialize HTTP Server\nprint(f\"\\nInitializing web server on port {WEB_PORT}...\")\npool = socketpool.SocketPool(wifi.radio)\nserver = Server(pool, \"/static\", debug=False)\n\n# ============================================================================\n# WEB SERVER ROUTES\n# ============================================================================\n\n@server.route(\"/\")\ndef base(request: Request):\n    \"\"\"Main page with sensor data\"\"\"\n\n    # Determine if sensor is online\n    sensor_online = sensor.is_valid\n\n    # Build HTML response\n    html = f\"\"\"\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\u003chead\u003e\n\u003cmeta name='viewport' content='width=device-width, initial-scale=1.0'/\u003e\n\u003cmeta charset='utf-8'\u003e\n\u003cmeta http-equiv='refresh' content='{WEB_REFRESH_RATE}'\u003e\n\u003cstyle\u003e\n* {{ margin: 0; padding: 0; box-sizing: border-box; }}\nbody {{ font-family: Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }}\n#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; }}\nheader {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px 20px; text-align: center; }}\nh1 {{ font-size: 28px; font-weight: 600; margin-bottom: 5px; }}\n.subtitle {{ font-size: 14px; opacity: 0.9; }}\n.content {{ padding: 30px 20px; }}\n.metric-card {{ background: #f8f9fa; border-radius: 10px; padding: 20px; margin-bottom: 15px; border-left: 4px solid #667eea; }}\n.metric-label {{ font-size: 12px; color: #6c757d; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }}\n.metric-value {{ font-size: 32px; font-weight: 700; color: #2c3e50; margin-bottom: 5px; }}\n.metric-unit {{ font-size: 16px; color: #6c757d; font-weight: 400; }}\n.status-indicator {{ display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; }}\n.status-online {{ background: #28a745; }}\n.status-offline {{ background: #dc3545; }}\n.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; }}\n.button:hover {{ transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102,126,234,0.4); }}\n.button:active {{ transform: translateY(0); }}\n.footer {{ text-align: center; padding: 15px; font-size: 12px; color: #6c757d; border-top: 1px solid #e9ecef; }}\n.info-box {{ background: #e7f3ff; border-left: 4px solid #2196F3; padding: 15px; margin-top: 15px; border-radius: 5px; }}\n.info-box p {{ font-size: 13px; color: #1976D2; margin: 5px 0; }}\n@media (max-width: 480px) {{\n  .metric-value {{ font-size: 24px; }}\n  h1 {{ font-size: 24px; }}\n}}\n\u003c/style\u003e\n\u003ctitle\u003eUFM01 Monitor\u003c/title\u003e\n\u003c/head\u003e\u003cbody\u003e\n\u003cdiv id='main'\u003e\n\u003cheader\u003e\n\u003ch1\u003eUFM01 Flow Monitor\u003c/h1\u003e\n\u003cp class='subtitle'\u003eCircuitPython Edition\u003c/p\u003e\n\u003c/header\u003e\n\u003cdiv class='content'\u003e\"\"\"\n\n    # Accumulated Flow Card\n    html += \"\u003cdiv class='metric-card'\u003e\"\n    html += \"\u003cdiv class='metric-label'\u003e\"\n    html += f\"\u003cspan class='status-indicator {'status-online' if sensor_online else 'status-offline'}'\u003e\u003c/span\u003e\"\n    html += \"Accumulated Flow\"\n    if not sensor_online:\n        html += \" (Offline)\"\n    html += \"\u003c/div\u003e\"\n    html += \"\u003cdiv class='metric-value'\u003e\"\n    html += f\"{sensor.accumulated_flow:.2f}\" if sensor_online else \"---\"\n    html += \"\u003c/div\u003e\"\n    html += \"\u003cdiv class='metric-unit'\u003eLiters\u003c/div\u003e\"\n    html += \"\u003c/div\u003e\"\n\n    # Instantaneous Flow Card\n    html += \"\u003cdiv class='metric-card'\u003e\"\n    html += \"\u003cdiv class='metric-label'\u003e\"\n    html += f\"\u003cspan class='status-indicator {'status-online' if sensor_online else 'status-offline'}'\u003e\u003c/span\u003e\"\n    html += \"Instantaneous Flow Rate\"\n    if not sensor_online:\n        html += \" (Offline)\"\n    html += \"\u003c/div\u003e\"\n    html += \"\u003cdiv class='metric-value'\u003e\"\n    html += f\"{sensor.instantaneous_flow:.1f}\" if sensor_online else \"---\"\n    html += \"\u003c/div\u003e\"\n    html += \"\u003cdiv class='metric-unit'\u003eLiters/hour\u003c/div\u003e\"\n    html += \"\u003c/div\u003e\"\n\n    # Temperature Card\n    html += \"\u003cdiv class='metric-card'\u003e\"\n    html += \"\u003cdiv class='metric-label'\u003eTemperature\u003c/div\u003e\"\n    html += \"\u003cdiv class='metric-value'\u003e\"\n    html += f\"{sensor.temperature:.1f}\" if sensor_online else \"---\"\n    html += \"\u003c/div\u003e\"\n    html += \"\u003cdiv class='metric-unit'\u003e°Celsius\u003c/div\u003e\"\n    html += \"\u003c/div\u003e\"\n\n    # Peak Flow Card\n    html += \"\u003cdiv class='metric-card'\u003e\"\n    html += \"\u003cdiv class='metric-label'\u003ePeak Flow Rate\u003c/div\u003e\"\n    html += \"\u003cdiv class='metric-value'\u003e\"\n    html += f\"{sensor.max_flow_rate:.1f}\"\n    html += \"\u003c/div\u003e\"\n    html += \"\u003cdiv class='metric-unit'\u003eLiters/hour\u003c/div\u003e\"\n    html += \"\u003c/div\u003e\"\n\n    # Statistics Info Box\n    html += \"\u003cdiv class='info-box'\u003e\"\n    html += f\"\u003cp\u003e\u003cstrong\u003eStatistics:\u003c/strong\u003e\u003c/p\u003e\"\n    html += f\"\u003cp\u003eFrames Received: {sensor.stats['frames_received']}\u003c/p\u003e\"\n    html += f\"\u003cp\u003eParse Errors: {sensor.stats['parse_errors']}\u003c/p\u003e\"\n    if sensor.stats['last_frame_time'] \u003e 0:\n        elapsed = time.monotonic() - sensor.stats['last_frame_time']\n        html += f\"\u003cp\u003eLast Update: {elapsed:.1f}s ago\u003c/p\u003e\"\n    html += \"\u003c/div\u003e\"\n\n    # Reset Button\n    html += \"\u003ca href='/reset' class='button'\u003eReset Accumulated Flow\u003c/a\u003e\"\n\n    html += \"\u003c/div\u003e\"\n    html += f\"\u003cdiv class='footer'\u003eAuto-refresh every {WEB_REFRESH_RATE} seconds | Powered by CircuitPython\u003c/div\u003e\"\n    html += \"\u003c/div\u003e\u003c/body\u003e\u003c/html\u003e\"\n\n    return Response(request, html, content_type=\"text/html\")\n\n\n@server.route(\"/reset\")\ndef reset_flow(request: Request):\n    \"\"\"Reset accumulated flow and redirect back to main page\"\"\"\n    print(\"🔄 Reset button pressed - clearing accumulated flow\")\n\n    success = sensor.clear_accumulated_flow()\n    if success:\n        print(\" ✓ Accumulated flow cleared successfully\")\n        message = \"Reset OK\"\n    else:\n        print(\" ✗ Failed to clear accumulated flow\")\n        message = \"Reset failed\"\n\n    # Robust redirect: 302 + Location header + meta refresh + JS\n    html = f\"\"\"\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\u003chead\u003e\n\u003cmeta charset='utf-8'\u003e\n\u003ctitle\u003eRedirecting…\u003c/title\u003e\n\u003cmeta http-equiv='refresh' content='0; url=/' /\u003e\n\u003cscript\u003elocation.replace('/');\u003c/script\u003e\n\u003cstyle\u003ebody{{font-family:Arial,sans-serif}} .msg{{margin:2rem}}\u003c/style\u003e\n\u003c/head\u003e\u003cbody\u003e\n\u003cdiv class='msg'\u003e{message}. Returning to main page… \u003ca href='/'\u003eContinue\u003c/a\u003e\u003c/div\u003e\n\u003c/body\u003e\u003c/html\u003e\n\"\"\"\n    return Response(\n        request,\n        html,\n        content_type=\"text/html\",\n        headers={\"Location\": \"/\"},\n        status=(302, \"Found\"),\n    )\n\n\n# ============================================================================\n# START SERVER AND MAIN LOOP\n# ============================================================================\n\nprint(\"✓ Web server initialized\")\nprint(\"\\n\" + \"=\"*50)\nprint(\"System Ready!\")\nprint(\"=\"*50)\nprint(f\"\\nConnect to WiFi: {WIFI_SSID}\")\nprint(f\"Visit: http://{wifi.radio.ipv4_address_ap}\")\nprint(\"\\nMonitoring sensor data...\\n\")\n\n# Start the server\nserver.start(str(wifi.radio.ipv4_address_ap), port=WEB_PORT)\n\n# Main loop\nlast_sensor_print = time.monotonic()\n\nwhile True:\n    # Update sensor data\n    if sensor.update():\n        # Print to console occasionally\n        if time.monotonic() - last_sensor_print \u003e 5:\n            print(f\"📊 Flow: {sensor.instantaneous_flow:.1f} L/h | \"\n                  f\"Total: {sensor.accumulated_flow:.2f} L | \"\n                  f\"Temp: {sensor.temperature:.1f}°C\")\n            last_sensor_print = time.monotonic()\n\n    # Poll the server (handles incoming requests)\n    try:\n        server.poll()\n    except Exception as e:\n        print(f\"Server error: {e}\")\n        time.sleep(0.1)\n\n    # Small delay to prevent CPU hogging\n    time.sleep(0.001)","metadata":{"language":"python","linenums":false,"filename":""}},{"element_type":"user_image","content":"https://cdn-learn.adafruit.com/user_assets/assets/000/002/178/original/ufm01.jpg?1767975291","metadata":{}},{"element_type":"user_image","content":"https://cdn-learn.adafruit.com/user_assets/assets/000/002/179/original/ufm01_circuitpython_webpage.jpg?1767975851","metadata":{}},{"element_type":"user_image","content":"https://cdn-learn.adafruit.com/user_assets/assets/000/002/180/original/ufm01metro.jpg?1767975960","metadata":{}}]