This is something that perplexed me a few years ago with Flash Forth on a PIC18/PIC24/Arduino Uno. I was using the Python serial emulator S-Term because it is simple in the source code and worked. I really wanted a way to load more structured Words into the FF dictionary with bookmarks in a way that made sense structurally. That lead to a desire to execute code from the uC on the host system, but I never wrapped my head around how to do this in practice.
As a random simple example, let’s say I set up an interrupt based on the internal temperature sensor of the PIC18. Once triggered the uC must call a Python script on the host system and this script defines a new FF word on the uC by defining the Word in the interpreter.
How do you connect these dots to make this work at the simplest ‘hello world’ level? I tried modifying S-Term at one point, but I didn’t get anywhere useful with my efforts.
My approach would be to have the Python script read the serial console of the microcontroller in a loop and parse the text data exchanged through it. Binary can work too but then you’d need to implement the necessary logic to figure out if you’re done reading or not.
Through things like udev rules you can automatically start such a script when the device is detected (i.e. the cable is plugged in).
Something like this should work, depending on the settings of your serial connection:
#!/usr/bin/env python3 import serial ser = serial.Serial( port='/dev/ttyUSB0, baudrate=57600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS ) while(True): line = ser.readline() # Do something with the line of text that was just read print(line) ser.close()
Coupled with a udev rule like:
ACTION=="add", SUBSYSTEM=="usb", ENV{ID_VENDOR_ID}=="0123", ENV{ID_MODEL_ID}=="4567", RUN+="/path/to/your/script.py"
The udev rule depends on how you connect to the device, of course. Also make sure to mark the script as executable if you call it directly. First improvement I’d make is to figure out how to detect the device (instead of hard coding ttyUSB0) and the correct parity settings.