Upload code on Arduino Leonardo using command line

The problem with the Leonardo is it doesn't automatically reset when you open the serial port like boards such as the Uno do.

The Arduino IDE contains code to manually reset the board (by opening the serial port at 1200 baud and closing it again) which avrdude doesn't have.

Basically you need a different way to reset the board so it enters the bootloader. That may be as simple as just pressing the reset button at the right time (the LED fades in and out when it's in bootloader mode) or using some command line utility to open the serial port at 1200 baud and close it again just before running avrdude.

I don't have my Leonardo to hand right now, but you might have some luck running:

stty -F /dev/ttyACM0 ispeed 1200 ospeed 1200 && avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

After try some trial and error I have built a simple binary to upload into the Leonardo bootloader. This binary opens serial at 1200 baud then closes it, and wraps the avrdude binary to write .hex into flash.

In Arduino core CDC.cpp we can see that CDC not only waiting baudrate 1200, but CDC checking DTR value. If DTR goes high, CDC cancels to jump into the bootloader. That's why I cleared DTR value. I tried this in Ubuntu 16.04.

https://github.com/vanbwodonk/leonardoUploader

Only use this simple command:

leonardoUploader /dev/ttyACM0 Blink.ino.hex

I hope it helps other people searching for this.