Arduino Wait for Input

  1. Set the Arduino to Wait for the Input Using the Serial.avaiable() Function
  2. Set the Arduino to Wait for the Input Using the digitalRead() Function

This tutorial will discuss two methods to set your Arduino to wait for the input. One method is for serial ports or analog pins, and the other is for digital pins.

Set the Arduino to Wait for the Input Using the Serial.avaiable() Function

If you want to read input from a serial port, then you can use the Serial.available() function to wait for the input. This function gets the number of bytes present at the serial port. If there is no input present, it will return zero.

void setup() {
    Serial.begin(9600);
}

void loop() {
    while(Serial.available() == 0) {
    }
    int mydata = Serial.read();
}

In the above code, if there is no input present at the serial port, then the Arduino will be stuck in a loop and will remain there. If an input arrives at the serial port, the loop will break, and the serial will read data using Serial.read() and will store it in the variable mydata.

Set the Arduino to Wait for the Input Using the digitalRead() Function

If you want to read input from a digital pin then, you can use the digitalRead() function to wait for the input. This function reads the digital value of a digital pin which is either LOW or HIGH.

int valPin = 0;
int inputPin = 7;

void setup() {
    pinMode(inputPin, INPUT);
}

void loop() {
    while(digitalRead(inputPin) != LOW);{      
  }
    valPin = digitalRead(inputPin);
}

In the above code, if there is no input present at the digital pin, then the Arduino will be stuck in a loop and will remain there. If an input arrives at the digital pin, the loop will break, and the serial will read data using digitalRead() and store it in the variable valPin.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.