NicoHood / HoodLoader2

16u2 Bootloader to reprogram 16u2 + 328/2560 with Arduino IDE
http://www.nicohood.de
734 stars 186 forks source link

atmega16u2 unexpectedly starts running bootloader #134

Open hraftery opened 9 months ago

hraftery commented 9 months ago

I've deployed HoodLoader2 on a PCB design based on the Arduino UNO. I'm running a small sketch on the 16u2 based on HID-Bridge, and a larger project on the 328p. The device delivers HID reports to an Android device over USB.

I'm now experiencing very odd occurrences of the 16u2 ending up in the bootloader, despite being constantly powered and nothing influencing the RESET pin. Without my sketch running, the device is not effective and needs to be power cycled to return to normal.

What are the ways a 16u2 running a sketch can end up back in the bootloader? Anything other than the 1200 baud trick?

Are there options for ensuring the device doesn't stay this way? Say, a timeout in the bootloader, so if it ever does find itself running, will default back to the application after a dormant period?

hraftery commented 9 months ago

Figured it out. The bootloader will also run if the atmega16u2 reboots due to brown-out detection. I can't think of a desirable use case for that, and it's certainly a problem for an embedded device.

In my case the BOD is being triggered due to some weird impulse on the ground plane, injected by a peripheral. The BOD is doing what it should, but running the bootloader as a consequence brings everything to a halt.

Here's the diff of my fix:

--- a/avr/bootloaders/HoodLoader2/HoodLoader2.c
+++ b/avr/bootloaders/HoodLoader2/HoodLoader2.c
@@ -203,7 +203,7 @@ void Application_Jump_Check(void)
                }

                // On a power-on reset, we ALWAYS want to go to the sketch. If there is one.
-               else if ((mcusr_state & (1 << PORF))){
+               else if ((mcusr_state & (1 << PORF)) || (mcusr_state & (1 << BORF))){
                        if(!POWER_ON_TO_BOOTLOADER){
                                StartSketch();
                        }

Alas, it's been 8 years since avr-gcc 5.1 was a thing, and I ran into flash space issues re-compiling with 9.4.0. I then found USE_RAM_DESCRIPTORS is buggy, so ended up ripping out some chars from the descriptor strings to get it over the line! So my pull request would be a bit ugly at the moment. I can tidy it up and submit it if of use.