Raspberry Pi Stand-Alone Programmer

Pages
Contributors: QCPete
Favorited Favorite 12

Parsing Output from avrdude w/ Python

In order to blink those nice new LEDs on the HAT, we'd need the Python module to be able to parse the output from avrdude, and blink the success or fail LED as needed. Oh man, What a dream! Python makes this so easy.

A Little Background on Parsing

Often times, the readout from a program can be pretty lengthy (with useful information), but when you are programming tons and tons of boards, you just want to see Success or Failure in the readout and not have to look through a ton of text.

This is something that we added into our batch files years ago. Using our old batch files, we've been parsing "tokens" returned from stk500.exe and the code is cryptic. Here's what a typical batch file might look like:

language:bash
FOR /F "tokens=*" %%i IN ('"%step1%"') DO (
if "%%i" == "Fuse bits verified successfully" echo Success at %$step1%
) & (
if "%%i" == "Target voltage is within 5%% of wanted value" (echo Target Voltage Good)
) & (
if "%%i" == "Target voltage is NOT within 5%% of wanted value" (echo %%i) & goto menu
) & (
if "%%i" == "WARNING! One or more operations failed! Please examine the output log above!" (echo Failed at %$step1%) & goto menu
) & (
if "%%i" == "Could not connect to STK500 V2 on USB" (echo %%i) & goto menu
) & (
if "%%i" == "Could not connect to AVRISP mkII on USB" (echo %%i) & goto MENU
)

Oh dang, that's ugly. In Python, I first sent the output to a text file with this command:

language:python
#erase and then write FUSE bits
sudo avrdude -p $DEVICE -C /home/pi/avrdude_gpio.conf -c linuxspi -P /dev/spidev0.0 -b 125000 -D -v -e -u -U hfuse:w:$HIGH_FUSE:m -u -U lfuse:w:$LOW_FUSE:m -u -U efuse:w:$EXT_FUSE:m 2>/home/pi/fuse_results.txt

Notice that little trick using the "2>":

language:python
2>/home/pi/fuse_results.txt

This is actually where all of the output debug from avrdude is getting saved to a text file.

Finally, we can do the parsing of the text file in Python like so:

language:python
f = open('/home/pi/fuse_results.txt', 'r')
    for line in f:
            if 'avrdude: 1 bytes of hfuse verified' in line:
                    print line
                    hfuse = True
            elif 'avrdude: 1 bytes of lfuse verified' in line:
                    print line
                    lfuse = True
            elif 'avrdude: 1 bytes of efuse verified' in line:
                    print line
                    efuse = True
            elif 'avrdude: AVR device not responding' in line:
                    print line
f.close()

So much cleaner! Thank you Python!

To learn more about file handling, here's a great tutorial that got us up and running:

The truly beautiful thing about Python is that anything you want to do is usually a google search away. It's remarkable how much support there is for python tools. Paired with a headless pi and the sky is the limit!