目录
简介
这个例子示范了怎么用SerialEvent()函数。这个函数是从loop()里调用。如果缓冲器有串口数据,每个被找到的字符都加入到一个字符串里,直到发现新行。在这种情况下,由收到的字符组成的字符串打印并且重置变回null。
硬件要求
- Arduino or Genuino 开发板
电路
什么都不要,只需要开发板连接到电脑。用Arduino IDE串口监视器发送单个或者多个字符并且返回字符串。
样例代码
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}