stk500
stk500 copied to clipboard
Enough of the STK500 protocol in Erlang to control the Arduino boot loader
stk500 is an Erlang implementation of enough of the STK500 protocol to talk to an Arduino.
Example
% Open the serial device attached to the Arduino
% The Diecimila uses 19200
{ok,FD} = stk500:open("/dev/ttyUSB0", [{speed, 19200}]),
% Read a hex file generated by the Arduino IDE
%
% hex_file/1 returns a list of binaries as read from the
% file (16 bytes). It's faster to use 128 bytes chunks.
Hex = stk500:hex_file("test/counter.cpp.hex"),
Bytes = stk500:chunk(Hex, 128),
ok = stk500:load(FD, Bytes),
stk500:close(FD).
test/counter.cpp.hex
is a compiled hex file for testing, generated
from the example in examples/counter/counter.pde. To call the example
code from Erlang:
1> counter:run(). % loops adding 1 to a counter
2> {ok, FD} = counter:start("/dev/ttyUSB0").
3> counter:read(FD).
{ok, 0}
4> counter:incr(FD).
ok
5> counter:incr(FD, 5).
6> counter:read(FD).
{ok, 6}
7> counter:set(FD, 3).
ok
8> counter:read(FD).
{ok, 3}
Build
$ rebar3 compile
# running tests
# arduino is attached to /dev/ttyUSB2
STK500_SERIAL_PORT=/dev/ttyUSB2 rebar3 ct
Note on Protocol Dumping
The simplest way to dump the serial communications is by using strace. For example, on an Ubuntu system, to see how the Arduino IDE is calling avrdude:
# as root
cd /usr/share/arduino/hardware/tools
mv avrdude avrdude.dist
cat<<EOF>avrdude
#!/bin/sh
set -e
mkdir /tmp/arduino-$$
strace -e read=3 -e write=3 -v -o /tmp/arduino-$$/dump \
-e trace=open,close,read,write,ioctl \
/usr/share/arduino/hardware/tools/avrdude.dist $@
EOF
An example protocol dump is doc/protocol_trace.txt.
Resources
The STK500 protocol documentation can be found here:
http://www.atmel.com/Images/doc2525.pdf