Arduino unr r4 mini doesn't reconnect to serial port after manual reset

I found a solution thanks to @KurtE in this post.
The line
while (!Serial && (millis() < 5000));
let's the R4 reconnect correctly after reset. For explanation, see the original post.