Some tips to prevent issues.
===
If you intend to use the board as a HID, build in a failsafe. It's very easy to get the board in a state where
- it spams the PC with data.
- keys presses get stuck in the PC.
As a result you can have a hard time to e.g. upload a new sketch.
The failsafe will be a pin that you can connect to GND. If that pin is HIGH it will prevent the board from spamming the PC. In the below example I use A0 as the failsafe pin.
const uint8_t safetyPin = A0;
void setup()
{
pinMode(safetyPin, INPUT_PULLUP);
while(digitalRead(safetyPin) == HIGH)
{
// do nothing
}
}
void loop()
{
// your HID functionality here
}
This code will get stuck in setup() till you ground the safety pin; that way you can prevent the spamming.
This will not prevent a key (e.g. <CTRL>) getting stuck in the PC; as a result when you press a
on the normal keyboard it will become <CTRL>A and usually it will e.g. select all code in the IDE. Therefore you must make sure that you always release keys. The basics for the loop() function to achieve that is below.
void loop()
{
if(digitalRead(safetyPin) == HIGH)
{
keyboard.releaseAll();
return;
}
// your HID functionality here
}
If the safetyPin is not connected to GND the loop() will release all keys and prevent further HID functionality.
===
You will often see code like below when using the Serial interface.
void setup()
{
Serial.begin(115200);
while(!Serial) {}
}
This is used if you want to make sure that you will not miss the first data that is send to e.g. serial monitor. The code will wait till the a communication channel with the PC is opened (e.g. opening the serial monitor).
This however has the disadvantage in stand-alone use of the board as it will simply hang on the while(!Serial) {}
. You can either remove the while(!Serial) {}
line or use a workaround can be to add a timeout as shown below
void setup()
{
Serial.begin(115200);
while(!Serial)
{
if (millis() > 3000)
{
break;
}
}
}
This will wait for the communication channel to be opened or till 3 seconds (3000 milliseconds) have passed.
===
When using the board with external power on the RAW / Vin pin and using USB to print data over the Serial interface you can bring your board to a near grinding halt. The scenario is that your board is connected to external power (e.g 9V) and you're happily debugging using serial monitor; now you disconnect the USB (and keep the external power connected; the result is that the processor can no longer get id of the data and your board will eventually come to a near grinding halt.
To prevent that you can check if there is still space in the underlaying software Serial buffer; you need to do this for every print/println/write
void loop()
{
if(Serial.availableForWrite() > X)
{
Serial.print(something);
}
}
where X is basically the number of bytes that you want to send. If you want to play it safe you can use e.g. 60.
Note:
Codes not tested as I'm currently using my boards for something else.