12

I'm new to Arduino, and I am trying a couple of tutorials. What does this line do in a program?

while (! Serial); 
0

1 Answer 1

15

On boards with an FT232 chip or other USB->Serial bridge chip (Uno, Mega, etc) it does absolutely nothing.

On boards with a direct USB connection, such as the Leonardo or the Yùn it waits for an active serial connection to be established by the PC (i.e., for the serial port to be opened by a piece of software).

When you open the serial port of a board like the Uno or Mega the whole board usually resets*, so opening the serial port allows you to see the first bits of the serial data. On the Leonardo etc it doesn't reset when you open the serial, so any serial output during the setup() function would be missed. Adding that line makes the board pause until you open the serial port, so you get to see that initial bit of data.

*) Unless you specifically write some software that doesn't assert DTR when you open the port

8
  • Strictly "When you open the serial port of a board like the Uno or Mega the whole board resets," is not correct. The Arduino's IDE does that by default. However, simply opening the serial port from the USB host PC does not reset the ATmega. I've written code that opens a serial connection over USB from the host, and it doesn't reset the ATmega.
    – gbulmer
    Commented Oct 11, 2014 at 17:55
  • 1
    Actually, it is both OS and driver dependant, not just down to the software that does the port opening.
    – Majenko
    Commented Oct 11, 2014 at 18:34
  • 1
    The arduino resets when it gets the DTR signal. It is transmitted by default whenever I open a connection from anywhere, not just arduino's IDE. Commented Oct 11, 2014 at 18:37
  • In some OSses it's possible to open the serial without asserting DTR. In others it's possible to configure a port to not assert DTR when opened, but only after it's been opened once. By default, as mentioned, the IDE always explicitly asserts DTR.
    – Majenko
    Commented Oct 11, 2014 at 18:39
  • 1
    On Linux you have to open the port first in order to set the port to not assert DTR. That first opening will always reset the board regardless.
    – Majenko
    Commented Oct 11, 2014 at 19:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.