Electronic – arduino – Need explanation on how to flash HEX files on ATmega32u4 via AVR109 protocol

arduinoatmegaatmelavrflash

I am not an electronic expert, so forgive me if I am misusing the terms in my question or if my question contains imprecisions and/or misinterpretation on how a Leonardo Board works. Corrections are of course welcome.

I am trying to write a very simple chip flasher that, given an HEX file, will be able to flash it on a Leonardo board, via its bootloader. I understand that the Arduino Leonardo uses an ATmega32u4 and that the bootlaoder uses the AVR109 protocol.

Based on this information, I have been able to write some code that flashes bytes on the board, but once flashed, the code does not work.

My code roughly looks like this:

  1. Parse the (intel) HEX file into a representation of how the memory should look like on the chip (i.e. for each record I extract the memory address to write to, and the data in the record).
  2. For each couple of bytes in this representation, I issue a set memory address instruction, followed by a write low byte, followed by a write high byte.
  3. Every 256 bytes flashed this way, I issue a write page instruction.

I have an hard time finding what I do wrong, because I am not sure about any of these steps. Step #1 produce data that looks OK (as one can see some familiar strings here and there):

enter image description here

however, if I compare my data with the same HEX file flashed by AVRdude and loaded again from the chip, the two are widely different.

Step #2 works (the bootloader responds with a 0xD byte at each command, but I don't know if I am doing the right thing by flashing the low byte before the high one.

Step #3 also seem to work fine, but I am uncertain on whether memory pages are effectively 256 bytes large (I derived this figure from the chip's datasheet, table 28-11).

I will be extremely grateful to anybody who could review my "algorithm" and provide feedback on what I do right or wrong, and where are common source of errors in this kind of application.

Best Answer

I have been using dfu-programmer successfully on Linux (using a "bare-bone" atmega32u2/atmega32u4) from the command line. So it's very easy to integrate it in a Makefile.

A quote from that web site:

dfu-programmer-0.6.2.tar.gz contains the source tree for this project. Download this to build and install on a Linux/Unix/Mac system.

So you should be able to build it on a Mac. Or you can have a look in the source code.