Powerful Arduino Debugging Library for Python

Introduction

Arduino is a widely popular open-source electronic prototyping platform that is extensively used in smart home, IoT, education, and other fields.

However, debugging often poses a challenge when developing Arduino projects.

Traditional debugging methods, such as using serial monitors or LED indicators, are often inefficient and provide limited information.

This is the background for the creation of the arduino-dbg library.

arduino-dbg is a Python library specifically designed for debugging Arduino devices.

It provides a simple yet powerful way for developers to monitor the status and variable values of Arduino devices in real-time, and even execute commands remotely.

This library has a wide range of applications in real life:

1. Smart Home Development

Developers can use arduino-dbg to remotely monitor and debug home automation systems, such as temperature control and lighting systems.

2. Industrial Automation

In factory environments, arduino-dbg can help engineers monitor and debug Arduino controllers on production lines in real-time.

3. Education

Teachers can use arduino-dbg to demonstrate the operation of Arduino programs, helping students better understand how embedded systems work.

4. IoT Projects

When developing IoT devices, arduino-dbg can significantly simplify the debugging process and enhance development efficiency.

5. Scientific Experiments

Researchers can use arduino-dbg to monitor experimental data in real-time, conduct remote debugging, and collect data.

Basic Usage

Install the arduino-dbg library

pip install arduino-dbg

The basic usage of arduino-dbg is as follows:

from arduino_dbg import ArduinoDebugger

# Create a debugger instance
debugger = ArduinoDebugger('/dev/ttyUSB0', 9600)

# Connect to the Arduino device
debugger.connect()

# Read variable value
temperature = debugger.read_variable('temperature')
print(f"Current temperature: {temperature}")

# Execute remote command
debugger.execute_command('turn_on_led')

# Listen for events
@debugger.on_event('button_pressed')
def handle_button_press():
    print("Button was pressed!")

# Start event loop
debugger.start_event_loop()

This simple example demonstrates several core functions of arduino-dbg: connecting to Arduino devices, reading variables, executing remote commands, and event listening.One of the main features of arduino-dbg is its flexible variable monitoring system.

You can easily set up variable watchers that automatically trigger callback functions when variable values change:

asteval disables some built-in functions and modules that may pose security risks by default. For example:

@debugger.watch_variable('temperature', threshold=1.0)
def on_temperature_change(old_value, new_value):
    print(f"Temperature changed from {old_value} to {new_value}")
In addition, arduino-dbg provides powerful logging capabilities:
debugger.start_logging('temperature', interval=5)  # Log temperature every 5 seconds

# Retrieve logs later
log_data = debugger.get_log('temperature')

Typical Usage Example

Now, let’s look at a more complex real-world application case. Suppose we are developing a smart greenhouse system that uses Arduino to control temperature, humidity, and light.
We can use arduino-dbg to remotely monitor and debug this system:
import time
from arduino_dbg import ArduinoDebugger

class SmartGreenhouseMonitor:
    def __init__(self, port, baud_rate):
        self.debugger = ArduinoDebugger(port, baud_rate)
        self.debugger.connect()

    def setup_monitors(self):
        @self.debugger.watch_variable('temperature', threshold=0.5)
        def on_temperature_change(old_value, new_value):
            print(f"Temperature changed: {old_value}°C -> {new_value}°C")
            if new_value > 30:
                self.debugger.execute_command('activate_cooling')
            elif new_value < 20:
                self.debugger.execute_command('activate_heating')

        @self.debugger.watch_variable('humidity', threshold=2)
        def on_humidity_change(old_value, new_value):
            print(f"Humidity changed: {old_value}% -> {new_value}%")
            if new_value < 60:
                self.debugger.execute_command('activate_misting')

        @self.debugger.watch_variable('light_level', threshold=50)
        def on_light_level_change(old_value, new_value):
            print(f"Light level changed: {old_value} -> {new_value}")
            if new_value < 200:
                self.debugger.execute_command('turn_on_grow_lights')
            elif new_value > 800:
                self.debugger.execute_command('close_shades')

    def start_logging(self):
        self.debugger.start_logging('temperature', interval=60)  # Log every minute
        self.debugger.start_logging('humidity', interval=60)
        self.debugger.start_logging('light_level', interval=60)

    def run(self):
        self.setup_monitors()
        self.start_logging()
        self.debugger.start_event_loop()

    def get_daily_report(self):
        temp_log = self.debugger.get_log('temperature')
        humidity_log = self.debugger.get_log('humidity')
        light_log = self.debugger.get_log('light_level')

        avg_temp = sum(temp_log.values()) / len(temp_log)
        avg_humidity = sum(humidity_log.values()) / len(humidity_log)
        avg_light = sum(light_log.values()) / len(light_log)

        print(f"Daily Report:")
        print(f"Average Temperature: {avg_temp:.2f}°C")
        print(f"Average Humidity: {avg_humidity:.2f}%")
        print(f"Average Light Level: {avg_light:.2f}")

        # Reset logs
        self.debugger.clear_logs()

if __name__ == "__main__":
    monitor = SmartGreenhouseMonitor('/dev/ttyUSB0', 115200)
    try:
        monitor.run()
        while True:
            time.sleep(86400)  # Run for 24 hours
            monitor.get_daily_report()
    except KeyboardInterrupt:
        print("Monitoring stopped.")

This example demonstrates how to use the arduino-dbg library to create a smart greenhouse monitoring system.

This case showcases the powerful capabilities of arduino-dbg in real-world applications. It can be used not only for debugging but also as a core component of a complete monitoring and control system.

Leave a Comment