Is it possible to flash a
.hex file on an AVR MCU, which already contains the Arduino bootloader, using an AVRISP mkII, without overwriting the bootloader?
In my concrete situation, I have an Arduino Uno that I would like to program sometimes over an AVRISP mkII, and sometimes using the built-in programmer (i.e. by just connecting the Uno via USB to a computer).
For reference, given a compiled
.hex file, this is what I use to upload it using the built-in programmer:
avrdude -c arduino -p atmega328p -P/dev/ttyACM0 -b115200 -D -Uflash:w:_build/image.hex:i
By default, this works as expected. I can also use
avrdude to upload it using the AVRISP:
avrdude -c avrisp2 -p atmega328p -U flash:w:_build/image.hex:i
This gets my image on the board as well; however, it also seems to overwrite the bootloader, i.e. after this, I can only use the AVRISP, and not the built-in one, to upload images. The only way back, at this point, is to re-flash the bootloader (via the AVRISP) on the Uno.
If I try to instruct
avrdude to upload via the AVRISP without overwriting the bootloader:
avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex:i
then it fails in the verification phase:
avrdude: verification error; content mismatch
Based on @ChrisStratton's answer, I understand this means my problem actually starts before I even try to upload it, by the compiler emitting code which has addresses that should belong to the bootloader.
Here is the command I use to compile and link (I am not using the Arduino IDE at all)
avr-g++ -c -g -O3 -w -std=c++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -I.. -mmcu=atmega328p -DF_CPU=16000000L blinkPB5.cpp -o _build/blinkPB5.cpp.o -MMD -MF _build/blinkPB5.cpp.m avr-g++ -Os -Wl,--gc-sections -mmcu=atmega328p -o _build/image.elf _build/blinkPB5.cpp.o avr-objdump -S _build/image.elf avr-objcopy -Oihex -R.eeprom _build/image.elf _build/image.hex
As explained above, I can use the same resulting
.hex file both via the bootloader (by just uploading it via serial) and the AVRISP (by overwriting the bootloader).