Skip to content
Browse files

Sort of like calling avrdude but with VM segfaults

Put an arduino into programmer mode and upload code using the STK500
protocol using pure Erlang. Well, the C is in another library.

Sort of like calling avrdude but with less features, no error checking
and more likelihood of crashing the Erlang VM.
  • Loading branch information...
0 parents commit f902ece6db0fa28c18bf4feacc503a89b57bd29a @msantos committed
Showing with 509 additions and 0 deletions.
  1. +3 −0 .gitignore
  2. +18 −0 Makefile
  3. +26 −0 README.md
  4. +131 −0 include/stk500.hrl
  5. +4 −0 rebar.config
  6. +3 −0 src/stk500.app.src
  7. +321 −0 src/stk500.erl
  8. +3 −0 start.sh
3 .gitignore
@@ -0,0 +1,3 @@
+*.[oa]
+*.beam
+*.swp
18 Makefile
@@ -0,0 +1,18 @@
+REBAR=$(shell which rebar || echo ./rebar)
+
+all: compile
+
+./rebar:
+ erl -noshell -s inets start -s ssl start \
+ -eval 'httpc:request(get, {"https://github.com/downloads/basho/rebar/rebar", []}, [], [{stream, "./rebar"}])' \
+ -s inets stop -s init stop
+ chmod +x ./rebar
+
+compile: $(REBAR)
+ @$(REBAR) compile
+
+clean: $(REBAR)
+ @$(REBAR) clean
+
+deps: $(REBAR)
+ @$(REBAR) get-deps
26 README.md
@@ -0,0 +1,26 @@
+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("doc/counter.cpp.hex"),
+ Bytes = stk500:chunk(Hex, 128),
+
+ stk500:load(FD, Bytes).
+
+
+## Resources
+
+The STK500 protocol documentation can be found here:
+
+ http://www.atmel.com/Images/doc2525.pdf
131 include/stk500.hrl
@@ -0,0 +1,131 @@
+%% Copyright (c) 2012, Michael Santos <michael.santos@gmail.com>
+%% All rights reserved.
+%%
+%% Redistribution and use in source and binary forms, with or without
+%% modification, are permitted provided that the following conditions
+%% are met:
+%%
+%% Redistributions of source code must retain the above copyright
+%% notice, this list of conditions and the following disclaimer.
+%%
+%% Redistributions in binary form must reproduce the above copyright
+%% notice, this list of conditions and the following disclaimer in the
+%% documentation and/or other materials provided with the distribution.
+%%
+%% Neither the name of the author nor the names of its contributors
+%% may be used to endorse or promote products derived from this software
+%% without specific prior written permission.
+%%
+%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+%% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+%% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+%% COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+%% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+%% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+%% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+%% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+%% POSSIBILITY OF SUCH DAMAGE.
+
+% %**** ATMEL AVR - A P P L I C A T I O N N O T E ************************
+% %*
+% %* Title: AVR061 - STK500 Communication Protocol
+% %* Filename: command.h
+% %* Version: 1.0
+% %* Last updated: 09.09.2002
+% %*
+% %* Support E-mail: avr@atmel.com
+% %*
+% %**************************************************************************
+
+% % *****************[ STK Message constants ]***************************
+
+-define(STK_SIGN_ON_MESSAGE, "AVR STK" ). % Sign on string for Cmnd_STK_GET_SIGN_ON
+
+% % *****************[ STK Response constants ]***************************
+
+-define(Resp_STK_OK , 16#10 ).
+-define(Resp_STK_FAILED , 16#11 ).
+-define(Resp_STK_UNKNOWN , 16#12 ).
+-define(Resp_STK_NODEVICE , 16#13 ).
+-define(Resp_STK_INSYNC , 16#14 ).
+-define(Resp_STK_NOSYNC , 16#15 ).
+
+-define(Resp_ADC_CHANNEL_ERROR , 16#16 ).
+-define(Resp_ADC_MEASURE_OK , 16#17 ).
+-define(Resp_PWM_CHANNEL_ERROR , 16#18 ).
+-define(Resp_PWM_ADJUST_OK , 16#19 ).
+
+% % *****************[ STK Special constants ]***************************
+
+-define(Sync_CRC_EOP , 16#20 ). % 'SPACE'
+
+% *****************[ STK Command constants ]***************************
+
+-define(Cmnd_STK_GET_SYNC , 16#30 ).
+-define(Cmnd_STK_GET_SIGN_ON , 16#31 ).
+
+-define(Cmnd_STK_SET_PARAMETER , 16#40 ).
+-define(Cmnd_STK_GET_PARAMETER , 16#41 ).
+-define(Cmnd_STK_SET_DEVICE , 16#42 ).
+-define(Cmnd_STK_SET_DEVICE_EXT , 16#45 ).
+
+-define(Cmnd_STK_ENTER_PROGMODE , 16#50 ).
+-define(Cmnd_STK_LEAVE_PROGMODE , 16#51 ).
+-define(Cmnd_STK_CHIP_ERASE , 16#52 ).
+-define(Cmnd_STK_CHECK_AUTOINC , 16#53 ).
+-define(Cmnd_STK_LOAD_ADDRESS , 16#55 ).
+-define(Cmnd_STK_UNIVERSAL , 16#56 ).
+-define(Cmnd_STK_UNIVERSAL_MULTI , 16#57 ).
+
+-define(Cmnd_STK_PROG_FLASH , 16#60 ).
+-define(Cmnd_STK_PROG_DATA , 16#61 ).
+-define(Cmnd_STK_PROG_FUSE , 16#62 ).
+-define(Cmnd_STK_PROG_LOCK , 16#63 ).
+-define(Cmnd_STK_PROG_PAGE , 16#64 ).
+-define(Cmnd_STK_PROG_FUSE_EXT , 16#65 ).
+
+-define(Cmnd_STK_READ_FLASH , 16#70 ).
+-define(Cmnd_STK_READ_DATA , 16#71 ).
+-define(Cmnd_STK_READ_FUSE , 16#72 ).
+-define(Cmnd_STK_READ_LOCK , 16#73 ).
+-define(Cmnd_STK_READ_PAGE , 16#74 ).
+-define(Cmnd_STK_READ_SIGN , 16#75 ).
+-define(Cmnd_STK_READ_OSCCAL , 16#76 ).
+-define(Cmnd_STK_READ_FUSE_EXT , 16#77 ).
+-define(Cmnd_STK_READ_OSCCAL_EXT , 16#78 ).
+
+% *****************[ STK Parameter constants ]***************************
+
+-define(Parm_STK_HW_VER , 16#80 ). % R
+-define(Parm_STK_SW_MAJOR , 16#81 ). % R
+-define(Parm_STK_SW_MINOR , 16#82 ). % R
+-define(Parm_STK_LEDS , 16#83 ). % R/W
+-define(Parm_STK_VTARGET , 16#84 ). % R/W
+-define(Parm_STK_VADJUST , 16#85 ). % R/W
+-define(Parm_STK_OSC_PSCALE , 16#86 ). % R/W
+-define(Parm_STK_OSC_CMATCH , 16#87 ). % R/W
+-define(Parm_STK_RESET_DURATION , 16#88 ). % R/W
+-define(Parm_STK_SCK_DURATION , 16#89 ). % R/W
+
+-define(Parm_STK_BUFSIZEL , 16#90 ). % R/W, Range {0..255}
+-define(Parm_STK_BUFSIZEH , 16#91 ). % R/W, Range {0..255}
+-define(Parm_STK_DEVICE , 16#92 ). % R/W, Range {0..255}
+-define(Parm_STK_PROGMODE , 16#93 ). % 'P' or 'S'
+-define(Parm_STK_PARAMODE , 16#94 ). % TRUE or FALSE
+-define(Parm_STK_POLLING , 16#95 ). % TRUE or FALSE
+-define(Parm_STK_SELFTIMED , 16#96 ). % TRUE or FALSE
+
+
+% *****************[ STK status bit definitions ]***************************
+
+-define(Stat_STK_INSYNC , 16#01 ). % INSYNC status bit, '1' - INSYNC
+-define(Stat_STK_PROGMODE , 16#02 ). % Programming mode, '1' - PROGMODE
+-define(Stat_STK_STANDALONE , 16#04 ). % Standalone mode, '1' - SM mode
+-define(Stat_STK_RESET , 16#08 ). % RESET button, '1' - Pushed
+-define(Stat_STK_PROGRAM , 16#10 ). % Program button, ' 1' - Pushed
+-define(Stat_STK_LEDG , 16#20 ). % Green LED status, '1' - Lit
+-define(Stat_STK_LEDR , 16#40 ). % Red LED status, '1' - Lit
+-define(Stat_STK_LEDBLINK , 16#80 ). % LED blink ON/OFF, '1' - Blink
4 rebar.config
@@ -0,0 +1,4 @@
+{deps, [
+ {srly, ".*", {git, "git://github.com/msantos/srly.git", "master"}}
+ ]}.
+{erl_opts, [{i, "include"}, {i, "deps/srly/include"}]}.
3 src/stk500.app.src
@@ -0,0 +1,3 @@
+{application, stk500,
+ [{description, "stk500 protocol for the Arduino"},
+ {vsn, "0.01"}]}.
321 src/stk500.erl
@@ -0,0 +1,321 @@
+%% Copyright (c) 2012, Michael Santos <michael.santos@gmail.com>
+%% All rights reserved.
+%%
+%% Redistribution and use in source and binary forms, with or without
+%% modification, are permitted provided that the following conditions
+%% are met:
+%%
+%% Redistributions of source code must retain the above copyright
+%% notice, this list of conditions and the following disclaimer.
+%%
+%% Redistributions in binary form must reproduce the above copyright
+%% notice, this list of conditions and the following disclaimer in the
+%% documentation and/or other materials provided with the distribution.
+%%
+%% Neither the name of the author nor the names of its contributors
+%% may be used to endorse or promote products derived from this software
+%% without specific prior written permission.
+%%
+%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+%% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+%% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+%% COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+%% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+%% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+%% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+%% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+%% POSSIBILITY OF SUCH DAMAGE.
+-module(stk500).
+-include("serctl.hrl").
+-include("stk500.hrl").
+
+-export([
+ open/0, open/1, open/2,
+
+ reset/1,
+ dtrrts/2,
+ version/1,
+
+ sync/1,
+ read/1, read/2,
+
+ hex_file/1, hex_file/2,
+ chunk/2,
+ load/2
+ ]).
+
+-define(DEV, "/dev/ttyUSB0").
+
+-define(TIOCMGET, 16#5415).
+-define(TIOCMSET, 16#5418).
+
+-define(TIOCM_DTR, 16#002).
+-define(TIOCM_RTS, 16#004).
+
+
+open() ->
+ open(?DEV, [{speed, b19200}]).
+
+open(Dev) ->
+ open(Dev, [{speed, b19200}]).
+
+open(Dev, Opt) ->
+
+ Speed = proplists:get_value(speed, Opt, b19200),
+
+ % 19200, 8 data bits, 1 stop bit, no parity
+ Mode = #termios{
+ iflag = serctl:constant(ignbrk),
+ oflag = 0,
+ lflag = 0,
+ cflag = serctl:constant(cs8)
+ bor serctl:constant(clocal)
+ bor serctl:constant(cread),
+
+ cc = lists:foldl(
+ fun({Offset, Val}, Bin) ->
+ serctl:offset(Bin, {Offset, Val})
+ end,
+ <<0:(serctl:constant(nccs)*8)>>, % zero'ed bytes
+ [
+ {serctl:constant(vmin), 1}, % Minimum number of characters
+ {serctl:constant(vtime), 0} % Timeout in deciseconds
+ ])
+ },
+
+ Termios = lists:foldl(
+ fun(Fun, Acc) -> Fun(Acc) end,
+ Mode,
+ [
+ fun(N) -> serctl:ispeed(N, Speed) end,
+ fun(N) -> serctl:ospeed(N, Speed) end,
+
+ fun(N) -> serctl:flow(N, false) end
+ ]),
+
+ {ok, FD} = serctl:open(Dev),
+ ok = serctl:tcsetattr(FD, tcsanow, Termios),
+
+ {ok, FD}.
+
+
+reset(FD) ->
+ ok = dtrrts(FD, off),
+ timer:sleep(50),
+ ok = dtrrts(FD, on),
+ timer:sleep(50),
+
+ [ begin read(FD), sync(FD) end
+ || _ <- lists:seq(1,3) ],
+
+ read(FD),
+
+ ok.
+
+
+version(FD) ->
+ reset(FD),
+
+ ok = serctl:write(FD, <<?Cmnd_STK_GET_PARAMETER, ?Parm_STK_SW_MAJOR, ?Sync_CRC_EOP>>),
+ {ok, <<?Resp_STK_INSYNC, Major, ?Resp_STK_OK>>} = read(FD, 3),
+
+ ok = serctl:write(FD, <<?Cmnd_STK_GET_PARAMETER, ?Parm_STK_SW_MINOR, ?Sync_CRC_EOP>>),
+ {ok, <<?Resp_STK_INSYNC, Minor, ?Resp_STK_OK>>} = read(FD, 3),
+
+ {Major, Minor}.
+
+
+dtrrts(FD, Status) when is_integer(Status) ->
+ dtrrts(FD, bool(Status));
+dtrrts(FD, Status) when is_atom(Status) ->
+ {ok, <<Ctl:4/native-unsigned-integer-unit:8>>} = serctl:ioctl(
+ FD,
+ ?TIOCMGET,
+ <<0:32>>
+ ),
+
+ Ctl1 = case Status of
+ on -> Ctl bor ( ?TIOCM_DTR bor ?TIOCM_RTS );
+ off -> Ctl band bnot ( ?TIOCM_DTR bor ?TIOCM_RTS )
+ end,
+
+ {ok, <<_Ctl2:4/native-unsigned-integer-unit:8>>} = serctl:ioctl(
+ FD,
+ ?TIOCMSET,
+ <<Ctl1:4/native-unsigned-integer-unit:8>>
+ ),
+
+ ok.
+
+
+% <<16#30, 16#20>>
+sync(FD) ->
+ serctl:write(FD, <<?Cmnd_STK_GET_SYNC, ?Sync_CRC_EOP>>).
+
+
+read(FD) ->
+ read(FD, 2).
+read(FD, N) ->
+ poll(FD, N, 10).
+
+
+hex_file(File) ->
+ hex_file(intel, File).
+
+hex_file(intel, File) ->
+ {ok, Bin} = file:read_file(File),
+ Hex = binary:split(Bin, <<"\r\n">>, [global, trim]),
+ rec(Hex).
+
+
+load(FD, Bytes) ->
+ reset(FD),
+
+ ok = serctl:write(FD, <<?Cmnd_STK_ENTER_PROGMODE, ?Sync_CRC_EOP>>),
+ case read(FD, 2) of
+ {ok, <<?Resp_STK_INSYNC, ?Resp_STK_OK>>} ->
+ load_1(FD, 0, Bytes);
+ {ok, Resp} ->
+ {protocol_error, {response, Resp}};
+ {error, Error} ->
+ {error, enter_progmode, Error}
+ end.
+
+load_1(FD, _Address, []) ->
+ ok = serctl:write(FD, <<
+ ?Cmnd_STK_LEAVE_PROGMODE,
+ ?Sync_CRC_EOP
+ >>),
+
+ case read(FD, 2) of
+ {ok, <<?Resp_STK_INSYNC, ?Resp_STK_OK>>} ->
+ ok;
+ {ok, Resp} ->
+ {protocol_error, {response, Resp}};
+ {error, Error} ->
+ {error, leave_progmode, Error}
+ end;
+
+load_1(FD, Address, Bytes) ->
+ Cmd = <<?Cmnd_STK_LOAD_ADDRESS,
+ Address:2/little-unsigned-integer-unit:8,
+ ?Sync_CRC_EOP
+ >>,
+
+ ok = serctl:write(FD, Cmd),
+
+ error_logger:info_report([
+ {address, Address},
+ {cmd, Cmd}
+ ]),
+
+ case read(FD, 2) of
+ {ok, <<?Resp_STK_INSYNC, ?Resp_STK_OK>>} ->
+ load_2(FD, Address, Bytes);
+ {ok, Resp} ->
+ {protocol_error, {response, Resp}};
+ {error, Error} ->
+ {error, {load_address, Address}, Error}
+ end.
+
+load_2(FD, Address, [H|T]) ->
+ Cmd = <<?Cmnd_STK_PROG_PAGE,
+ (byte_size(H)):2/big-unsigned-integer-unit:8,
+ $F,
+ H/bytes,
+ ?Sync_CRC_EOP>>,
+
+ error_logger:info_report([
+ {address, Address},
+ {cmd, Cmd},
+ {data, H}
+ ]),
+
+ ok = serctl:write(FD, Cmd),
+
+ case read(FD, 2) of
+ {ok, <<?Resp_STK_INSYNC, ?Resp_STK_OK>>} ->
+ load_1(FD, Address+byte_size(H) div 2, T);
+ {ok, <<?Resp_STK_INSYNC>>} ->
+ read(FD,1),
+ load_1(FD, Address+byte_size(H) div 2, T);
+ {ok, Resp} ->
+ {protocol_error, {response, Resp}};
+ {error, Error} ->
+ {error, {prog_page, Address, H}, Error}
+ end.
+
+
+chunk(Bytes, Size) when is_list(Bytes) ->
+ chunk(list_to_binary(Bytes), Size);
+chunk(Bytes, Size) when is_binary(Bytes) ->
+ chunk(Bytes, Size, []).
+
+chunk(Bytes, Size, Acc) ->
+ case Bytes of
+ <<Chunk:Size/bytes, Rest/binary>> ->
+ chunk(Rest, Size, [Chunk|Acc]);
+ _ ->
+ lists:reverse([Bytes|Acc])
+ end.
+
+
+%%--------------------------------------------------------------------
+%%% Internal functions
+%%--------------------------------------------------------------------
+bin_to_int(N, Base) ->
+ list_to_integer(binary_to_list(N), Base).
+
+
+poll(_FD, _Num, 0) ->
+ {error, eagain};
+poll(FD, NumBytes, Retry) ->
+ case serctl:read(FD, NumBytes) of
+ {error, eagain} ->
+ timer:sleep(25),
+ poll(FD, NumBytes, Retry-1);
+ {ok, Buf} ->
+ {ok, Buf};
+ Error ->
+ Error
+ end.
+
+
+bool(0) -> off;
+bool(1) -> on.
+
+
+rec(Hex) ->
+ rec(Hex, []).
+
+rec([], Acc) ->
+ lists:reverse(Acc);
+
+% Type 0
+% XXX Should compute and verify checksum
+rec([<<":", LenX:2/bytes, _LoadX:4/bytes, "00", DataSum/binary>>|T], Acc) ->
+ Len = bin_to_int(LenX, 16),
+
+ % Each byte is encoded as 2 bytes hex
+ HexLen = Len * 2,
+ <<Data:HexLen/bytes, _Sum:2/bytes>> = DataSum,
+
+ Bytes = rec_data(Data),
+
+ rec(T, [list_to_binary(Bytes)|Acc]);
+
+% Ignore other types
+rec([_|T], Acc) ->
+ rec(T, Acc).
+
+
+rec_data(Data) ->
+ rec_data(Data, []).
+
+rec_data(<<>>, Acc) ->
+ lists:reverse(Acc);
+rec_data(<<Byte:2/bytes, Rest/binary>>, Acc) ->
+ rec_data(Rest, [bin_to_int(Byte, 16)|Acc]).
3 start.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+erl $@ -boot start_sasl -pa $PWD/ebin $PWD/deps/*/ebin

0 comments on commit f902ece

Please sign in to comment.
Something went wrong with that request. Please try again.