Arduino Serial Basics: Waiting to Receive A Serial Command

Stalling Sketch Execution Until Serial Monitor is Opened

Imagine a project where you determine that you do not want to enter the Arduino loop until you receive a serial input of some sort from your serial monitor ( or other terminal program).

This skill is particularly useful if you want to create menus that allow you to use your serial monitor as an interface.

What you will essentially need to do is continually check for that input and prevent your sketch from continuing until that connection has been established.

This brief article shows to use Serial.available() you how to do just that.

What Happens If We Don’t Wait?

The sketch below is just your blink sketch that shows that shows us starting the serial port and then entering into the loop to blink the LED attached to pin 13.

void setup() {
  Serial.begin(9600);
  
  pinMode(13, OUTPUT); 

}

void loop() {  
  
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second

}

If you to upload this sketch,  you would find that your LED on thirteen starts blinking right after the upload is complete.   In other words,  you entered the sketch loop immediately.

Check For Data Input with Serial.available()

This next sketch uses Serial.available()  to check for input from your serial monitor.   Fundamentally,  we will stay in setup() until we receive an input from the Arduino serial monitor.

Go ahead and upload this sketch.

void setup() {
  
  
  Serial.begin(9600);
  
  pinMode(13, OUTPUT);
  
  while (!Serial.available()){
    //Do Absolutely Nothing until something is received over the serial port
  }
  
  

}

void loop() {
  
  
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second


}

After uploading this sketch, notice the the Pin 13 LED is not blinking.

Now do the following:

  1.  Open Your Serial Monitor
  2. Press any character
  3.  Hit enter or click the ‘Send’ button.

Now the LED on Pin 13 will blink.

With a little creativity,  you’re ready to parse input from your serial monitor and control your Arduino sketch.