Code Review: PWMP100/main.py (for Embedded Beginners)

This review looks at the MicroPython script main.py designed for a Raspberry Pi Pico W. It reads a DS18B20 temperature sensor, logs data to a file, and sends the latest reading via UDP.

Overall Structure & Readability

Good: The script is well-structured with clear sections:

Good: Using functions (like connect_to_wifi, read_ds18b20_temp, etc.) makes the code modular and easier to understand and maintain.

Good: Variable and function names are generally descriptive (e.g., WIFI_SSID, send_udp_message, MAX_FILE_SIZE_BYTES).

Good: Comments are used effectively to explain the purpose of the script and different sections.

Info: The if __name__ == "__main__": block is standard Python practice. It ensures that the code inside it only runs when the script is executed directly, not when it's imported as a module into another script.

Configuration


# --- Configuration ---
WIFI_SSID = "HW01"  # Your Wi-Fi SSID
WIFI_PASSWORD = "Embd0mm0" # Your Wi-Fi Password
UDP_TARGET_HOST = "www.wirelessip.info"
UDP_TARGET_PORT = 3219
ONEWIRE_PIN = 1      # GPIO pin for DS18B20 data line
DATA_FILENAME = "temp_ds18B20.json" # Log file
SEND_INTERVAL_S = 60 # Interval in seconds to read sensor and send UDP
MAX_FILE_SIZE_BYTES = 10 * 1024 # 10 KB limit for log file

# Set country code
rp2.country('JP') # Change to your country code
            

Good: Configuration values are grouped together at the top as constants (using uppercase names). This makes it easy to find and change settings like Wi-Fi credentials, pins, or server addresses without searching through the entire code.

Good: Setting the country code with rp2.country('JP') is important for Wi-Fi regulatory compliance.

Suggestion: For sensitive information like Wi-Fi passwords, beginners should be aware that storing them directly in the code is common for simple projects but less secure for production devices. More advanced methods involve configuration files or secure storage, but this is fine for learning.

Error Handling

Good: The script uses try...except blocks in many places (initialization, Wi-Fi connection, sensor reading, UDP sending, file operations, main loop). This prevents the entire script from crashing if one part fails.

Good: Specific exceptions are caught where possible (e.g., OSError, onewire.OneWireError, uerrno.ENOENT). This allows for more targeted error handling than just catching a generic Exception.


# Example: Specific OSError check for file not found
except OSError as e:
    if e.args[0] == uerrno.ENOENT:
        # File doesn't exist, which is fine.
        pass
    else:
        print(f"Error checking file size for '{filename}': {e}")
            

Good: The sensor reading function attempts to rescan for sensors if none are found initially or if a read error occurs, making it more robust if the sensor connection is intermittent.

Suggestion: In the main loop's generic except Exception as e: block, adding a short time.sleep(5) is a good practice to prevent the script from rapidly printing errors if a persistent problem occurs.

Suggestion: The fatal error during OneWire/DS18B20 initialization causes a machine.reset(). This is a valid strategy for simple devices to attempt recovery, but beginners should understand it restarts the entire script. Depending on the application, other strategies might be needed (e.g., entering a safe mode, blinking an error code).

Wi-Fi Connection (`connect_to_wifi`)


def connect_to_wifi(ssid, password):
    # ... (setup) ...
    max_wait_seconds = 15
    connect_start_time = time.ticks_ms() # Good: Using ticks_ms for non-blocking timeout
    while not wlan.isconnected() and wlan.status() >= 0 and time.ticks_diff(time.ticks_ms(), connect_start_time) < max_wait_seconds * 1000:
        print("Waiting for connection...")
        if led: set_led_state(not led.value()) # Good: Visual feedback
        time.sleep(0.5)
    # ... (check status and return) ...
            

Good: Uses a timeout (max_wait_seconds) combined with time.ticks_ms and time.ticks_diff to prevent waiting forever if connection fails. This is better than just looping a fixed number of times with time.sleep(1).

Good: Checks wlan.isconnected() and wlan.status() for reliable connection status.

Good: Provides visual feedback using the LED while connecting and indicates success/failure.

Good: Deactivates the Wi-Fi interface (wlan.active(False)) on failure, which can save power.

UDP Sending (`send_udp_message`)


def send_udp_message(message_bytes, target_ip, target_port):
    sock = None # Initialize sock to None
    bytes_sent = 0
    success = False
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Create socket
        bytes_sent = sock.sendto(message_bytes, (target_ip, target_port)) # Send
        success = True
    except OSError as e:
        print(f"UDP send error: {e}")
    except Exception as e:
        print(f"An unexpected error occurred during UDP send: {e}")
    finally:
        if sock: # Important: Check if socket was created before closing
            sock.close() # Always close the socket
    return success, bytes_sent
            

Good: Creates a new socket for each message and closes it in the finally block. This is simple and generally reliable for infrequent sending. The finally block ensures sock.close() is called even if an error occurs during sending.

Good: Checks if sock was successfully created before trying to close it (if sock: sock.close()).

Good: Handles potential OSError during sending.

Info: UDP is "fire and forget" - there's no guarantee the message arrived. The function correctly returns a success status indicating whether the sendto operation completed without error locally, not whether the server received it.

Suggestion: The function takes message_bytes. It's good practice to be explicit about expecting bytes, as network sockets work with bytes, not strings directly.

Sensor Reading (`read_ds18b20_temp`)


def read_ds18b20_temp():
    # ... (check globals) ...
    if not roms:
        print("Warning: No DS18B20 sensors detected. Attempting rescan...")
        # ... (rescan logic) ...

    first_rom = roms[0] # Assumes only one sensor or uses the first found
    try:
        ds_sensor.convert_temp() # Start conversion
        time.sleep_ms(750) # Wait for conversion (blocking)
        temp_c = ds_sensor.read_temp(first_rom) # Read temperature
        return temp_c
    except onewire.OneWireError as ow_error:
        print(f"OneWire bus error during read: {ow_error}")
        roms = [] # Force rescan next time
        return None
    # ... (other exception handling) ...
            

Good: Handles the case where no sensors are found initially and attempts a rescan.

Good: Follows the correct procedure for DS18B20: start conversion, wait, read temperature.

Good: Catches specific onewire.OneWireError and resets the roms list to trigger a rescan on the next attempt if a bus error occurs.

Info: The time.sleep_ms(750) makes this function *blocking*. The Pico can't do anything else during this wait. For simple applications like this, it's often acceptable. More advanced applications might use asynchronous techniques or timers to avoid blocking.

Suggestion: The code currently uses the *first* sensor found (roms[0]). If multiple sensors were connected, it would ignore the others. For beginners, this is usually fine, but it's worth noting. A more robust solution for multiple sensors would iterate through all `roms` and perhaps include the sensor's unique ROM address in the logged data.

File Handling (`save_json_to_file`, `check_and_manage_file_size`)


# Appending to file
def save_json_to_file(json_string, filename):
    try:
        with open(filename, "a") as f: # 'a' for append mode
            f.write(json_string + "\\n") # Add newline
        return True
    # ... (error handling) ...

# Managing file size
def check_and_manage_file_size(filename, max_size):
    try:
        stat_info = os.stat(filename)
        current_size = stat_info[6] # Index 6 is st_size
        if current_size > max_size:
            print(f"File '{filename}' size ... exceeds limit ... Deleting file.")
            os.remove(filename) # Delete the whole file
    # ... (error handling for file not found etc.) ...
            

Good: Uses with open(...) as f: which ensures the file is automatically closed even if errors occur.

Good: Opens the file in append mode ("a") to add new readings without overwriting old ones.

Good: Adds a newline character ("\\n") after each JSON entry, making the file easier to read and process line by line later.

Good: Includes a mechanism (check_and_manage_file_size) to prevent the log file from growing indefinitely and filling up the limited flash storage on the Pico. Uses os.stat to get file size and os.remove to delete it.

Good: Handles the OSError with uerrno.ENOENT in the size check, correctly ignoring the error if the file doesn't exist yet.

Suggestion: The current file management strategy deletes the *entire* log file when it exceeds the limit. For some applications, a "rolling log" approach (e.g., deleting the oldest lines instead of the whole file) might be preferred, but this is more complex to implement on a microcontroller. Deleting the whole file is a simple and effective strategy for many use cases.

Main Loop


while True:
    try:
        # 1. Read Sensor
        temperature = read_ds18b20_temp()

        if temperature is not None:
            # 2. Format Data
            # ... (create json_output) ...
            print(f"Reading: {json_output}") # Log locally

            # 3. Save Data to File
            save_success = save_json_to_file(json_output, DATA_FILENAME)

            # 4. Send Latest Reading via UDP
            if save_success:
                # ... (send udp) ...
            else:
                 print("Skipping UDP send due to file save error.")

            # 5. Check and Manage File Size
            check_and_manage_file_size(DATA_FILENAME, MAX_FILE_SIZE_BYTES)
        else:
            print("Failed to read sensor this interval.")

        # 6. Wait for the next interval
        print(f"Waiting for {SEND_INTERVAL_S} seconds...")
        time.sleep(SEND_INTERVAL_S) # Blocking sleep

    except KeyboardInterrupt:
        print("\\nExiting loop.")
        break
    except Exception as e:
        print(f"An error occurred in the main loop: {e}")
        time.sleep(5) # Delay before retrying
            

Good: The loop structure is clear: read, format, save, send, manage file, wait.

Good: Checks if the temperature reading was successful (temperature is not None) before proceeding.

Good: Only attempts to send UDP if the file save was successful.

Good: Handles KeyboardInterrupt (Ctrl+C) gracefully to exit the loop.

Info: The time.sleep(SEND_INTERVAL_S) is a blocking delay. The Pico does nothing else during this time. For this application (reading every 60 seconds), this is perfectly fine and simple.

Cleanup


# --- Cleanup ---
print("Cleaning up...")
if wlan_instance and wlan_instance.isconnected():
    wlan_instance.disconnect()
    print("Wi-Fi disconnected.")
if wlan_instance:
    wlan_instance.active(False)
    print("Wi-Fi deactivated.")
if led: set_led_state(False) # Ensure LED is off at the end
print("Program finished.")
            

Good: Attempts to disconnect Wi-Fi and deactivate the interface cleanly when the script exits (e.g., via Ctrl+C).

Good: Checks if wlan_instance exists and is connected before trying to disconnect/deactivate.

Good: Turns the LED off at the end.

Overall Conclusion

This is a solid, well-structured MicroPython script suitable for its purpose. It demonstrates good practices for embedded development, including:

For a beginner, this code provides excellent examples of how to handle common tasks like networking, sensor reading, file I/O, and error management on a microcontroller like the Pico W. The identified suggestions are minor improvements or points of awareness rather than significant flaws.