USBKeyboard.h occasionally hangs

RandallR:
What is lost and what is left when the watch dog bites? I would assume globals and statics would not loose their values, anything else? Is there some why for your code to know that the watch dog had to wake it up?

I worked out a way of knowing you had been reset:

#include <avr/wdt.h>

// some stuff that shouldn't be there randomly
const char wantedSig [5] = { 'f', 'o', 'b', 'a', 'r' };

// compiler not to initialize these two variables
char __attribute__ ((section (".noinit"))) magicSig [5];
long __attribute__ ((section (".noinit"))) resetCount;

void setup ()
{
  
  // if signature there, we have restarted
  if (memcmp (wantedSig, magicSig, sizeof magicSig) == 0)
    resetCount++;
  else 
    {
    resetCount = 0;
    // put signature there
    memcpy (magicSig, wantedSig, sizeof magicSig);
    }
    
  Serial.begin (115200);
  Serial.print ("Reset count = ");
  Serial.println (resetCount);
  
  wdt_enable(WDTO_1S);  // reset after one second, if no "pat the dog" received
 }  // end of setup

void loop ()
{
  
Serial.println ("Entered loop ...");

Serial.println ("Point A");
delay (500);
Serial.println ("Point B");
delay (400);

wdt_reset();  // give me another second to do stuff (pat the dog)

Serial.println ("Point C");
delay (500);
Serial.println ("Point D");
delay (400);

while (true) ;   // oops, went into a loop
    
}  // end of loop

The code marked:

 __attribute__ ((section (".noinit")))

... does not get reinitialized by the compiler. So by using a field as a "signature" we can work out if we have been reset or not, fairly reliably.