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

while (! Serial); 
  • This is completely answered at arduino.cc/en/Serial/IfSerial, and is available on line in your Arduino IDEs Help. So it is off-topic for this forum. – gbulmer Oct 11 '14 at 18:01
  • This question appears to be off-topic because it is about the Arduino library. The question is fully answered in the Arduino IDE's Help. Maybe it should be on the Arduino stackexchange. – gbulmer Oct 11 '14 at 18:03

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

  • 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 Oct 11 '14 at 17:55
  • 1
    Actually, it is both OS and driver dependant, not just down to the software that does the port opening. – Majenko Oct 11 '14 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. – BrettAM Oct 11 '14 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 Oct 11 '14 at 18:39
  • I believe it is possible to open an FTDI SUB/Serial without asserting DTR on Windows, OS X, and Linux, because I've done it. It is optional. So please update the answer, either say that when the IDE opens the serial port the board is reset, or that opening the serial monitor resets it, or that opening the serial port usually resets the board. I don't mind which is chosen. However the current answer is not accurate. – gbulmer Oct 11 '14 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy