Arduino Serial
Description#
Communicating with an Arduino using Serial is a common way to interact with your Arduino. It can also be a very helpful debugging tool.
This is a very short example demonstrating how you can send a message to your Arduino using the Serial Monitor and have it respond back (hence Ping Pong!).
The code will first check if there is any data available to read (Serial.available()) from the Serial Monitor. If there is, it will read the data and store it in a String variable. It will then check if the input is equal to “Ping” (case-sensitive) and if it is, it will respond with “Pong”.
Code#
void setup() {
Serial.begin(9600);
}
void loop() {
/*
Check if there is any data available to read from the Serial Monitor.
If there is, read the data and store it in a String variable.
*/
if (Serial.available() > 0) {
String input = Serial.readString();
/*
Why trim?
trim() is used to remove any whitespace characters that may be in the string.
In this case, when you provide input through the serial monitor, a line feed / new line (\n)
character is added which should be removed. Although not necessary, it'll make comparison ops
on strings easier (input == "Ping" vs. input == "Ping\n").
*/
input.trim();
if (input == "Ping") {
Serial.println("Pong");
}
}
}
FAQs#
- What if I want to send a number to the Arduino?
- You can use
Serial.parseInt()to read an integer from the Serial Monitor. - Check the official documentation for serial for all the functions available.
- You can use
Read other posts