Arduino MKRZERO dissapears from port selection after code upload

Hello,
I’m trying to get my Arduino MKRZERO to send CAN messages using this library and a standard mcp2515 CAN transiever.

When I use the library and run code, after I upload it the arduino disappears from the ports selection and I cannot view anything from the serial monitor to see print statements. The only way I can get the board to show up is by double clicking the reset button which resets the board into a state where no code is running.

I was wondering if my board may have been corrupted somehow or what the problem could be? I’m using the most recent version of the Arduino IDE.

If anyone could help I’d really appreciate it!

Best,
Arya

The tricky thing about the boards with native USB functionality like your board is that the USB code that creates the CDC serial port is running on the same microcontroller as your sketch. This means your sketch code can break the USB code, or stop it from running. When that happens, it no longer presents a port.

That makes it so you can't upload normally any more. However, the situation is really not so bad because there is an independent program called the bootloader in a separate section of memory from your sketch, and that program has its own USB CDC code. So even if the sketch is completely broken, you only need to activate the bootloader via the double reset technique and you will get a port back and be able to upload again, as you discovered.

It's far more likely that the problem is with the code in the specific sketch you are using rather than that your board was "corrupted". You can verify this by uploading a simple sketch like File > Examples > 01.Basics > BareMinimum. If the problem no longer occurs when you use a sketch like that, you will know that your previous sketch code is the cause. At that point, your task is to identify exactly which part of the sketch code is breaking the USB and fix it.

You should note that this behavior is normal and expected in some cases. For example, a sketch that puts the microcontroller to sleep will inevitably cause the port to disappear because if the microcontroller is asleep then it can't also be running the USB stack.

Thanks for the help!

This explanation makes a lot of sense!

Is there a way to view the serial monitor or observe the print statements of the board even when it does not show up on the port selection of my computer?

You could connect a USB to serial adapter (AKA "FTDI") to pins 13 and 14 on the MKR Zero and print to Serial1 instead of Serial.

A more advanced approach would be to connect a CMSIS-DAP compliant debug probe to the SWD breakout pads on the bottom of the board and then use the beta Arduino IDE 2.x's integrated debugger. This allows you to control the execution of your code, stepping through it line by line if you like.