Friday, April 04, 2014

Running Python Scripts on Arduino Yun

Completely inexplicably, I am unable to find an example of running a python script using the Bridge library in the official Arduino Yun documentation, despite this being a main selling point of using the Yun.

What You Need to Know Beforehand

Python scripts in the www directory of your sketch get uploaded to /mnt/sd/arduino/www/YOUR_SKETCH_NAME_HERE
on the Yun.

However, when you create a process on the ATMega using the bridge library, it does not appear to run from that directory automatically, so you will need to provide a full path to your python script.

Additionally, output from stdout is captured by the bridge library and can be read on the ATMega side, but error output is NOT.  You can fix this by adding an additional parameter &2>1.  See below.

Below is an example.
Process p;
p.begin("python");
p.addParameter("/mnt/sd/arduino/www/mysketch/myscript.py");
p.addParameter("foo"); // A command line parameter for the script
p.addParameter("&2>1"); // pipe error output to stdout
p.run(); // blocking call to run python; ATMega execution halts until complete

while(p.available()>0) {
    Console.print(p.read());
}

runShellCommand() is Funky

I initially tried p.runShellCommand(), however, this did not appear to work reliably.  Some Python scripts ran, others didn't, and there was no error output available.  The only difference that I could discern between scripts that did work and that didn't was the length of the command string.  The documentation doesn't state any specific length limit.  I don't know.

How do I know if My Script Ran?

I took a simple approach; the very beginning of my Python script writes to a file.
file = open("/mnt/sd/arduino/www/mysketch/i_ran_yo.txt", "w")
file.write("code ran\n")
file.close()
Check the date on that script using "ls -l" to see if you're python script has been called.

The Arduino Documentation for available() is Wrong

p.available() returns the number of characters of script output that are available.  The documentation says if none are available, the script returns -1.  This is incorrect.  It returns 0.

Outstanding Questions

Does the blocking call to run() have any effect on interrupt handlers?

Dear Arduino Team

Please provide more complete documentation (or let us edit it somehow so we can fix it) and error logging in the bridge library.  

1 comment:

Unknown said...

Hi Peter,
I am having some difficulty with Python scripts on the Yun ... simple file creation script works fine when run by itself, but running from Arduino via Bridge doesn't seem to execute. I can do Linux "ps" through SSH and even see the command line created in the Arduino sketch, but no execution. Can you provide a Bullet proof example of a sketch and companion Python script as template for troubleshooting.
Thanks,
Alan

Labels

Blog Archive

Contributors