如何比较 Serial.read() 中的字符串? [英] How to compare string from Serial.read()?
问题描述
我在下面有这个代码,我是从 这个论坛那里得到的我跟了过去.它对我不起作用,但他们声称代码很好.我已经尝试了几种字符串比较方法,例如 string.equals(string)
和标准的 ==
运算符,但仍然没有运气.
I have this code below where I got from this forum that I followed through. It did not work for me but they claim that the code is fine. I already tried several string comparison methods such as string.equals(string)
and the standard ==
operator, still with no luck.
int ledPin = 13;
String readString;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("serial on/off test 0021"); // so I can keep track
}
void loop() {
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
if (readString.length() >0) {
if (readString == "on") {
Serial.println("switching on");
digitalWrite(ledPin, HIGH);
}
if (readString == "off") {
digitalWrite(ledPin, LOW);
}
readString="";
}
}
推荐答案
我可以通过在字符串比较之前简单地添加 readString.trim();
来解决昨晚的问题.这是因为在arduino控制台中id没有打印任何东西的地方会有换行符.
I am able to solve last night problem by simply adding readString.trim();
before string comparison. This is because there will be newline character where id did not print anything in the arduino console.
我将函数放在下面的代码中:
I place the function as in my code below:
int ledPin = 13;
String readString;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("serial on/off test 0021"); // so I can keep track
}
void loop() {
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
readString.trim();
if (readString.length() >0) {
if (readString == "on"){
Serial.println("switching on");
digitalWrite(ledPin, HIGH);
}
if (readString == "off")
{
Serial.println("switching off");
digitalWrite(ledPin, LOW);
}
readString="";
}
}
这篇关于如何比较 Serial.read() 中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!