Arduino从串行线读取字符串并进行比较

时间:2015-10-08 09:45:55

标签: arduino serial-port string-comparison

我正在尝试从串行线读取一个字符串,并将其与命令列表进行比较。如果字符串是一个有效的命令,Arduino应该继续做某事,并在串行线上返回一些信息。 但是,我的comaprison总是失败(给我“不是一个有效的命令响应”)。我试过从Arduino串口监视器和Python脚本中发送“temp”一词。

我的arduino代码:

int sensorPin = 0; // Sensor connected to A0
int ledPin = 13; // Led connected to 13
int reading = 0; // Value read from A0

float voltage = 0; // Voltage we read
float temperatureC = 0; // Temperature we measure

String inputString= ""; // Set string empty
String Temperature = "temp"; // The command we are looking for

boolean stringComplete = false; // See if we are done reading from serial line



void setup() {
  Serial.begin(9600);  
  pinMode(ledPin, OUTPUT);
  inputString.reserve(200); // Reserve space for inputString in memory
}

void serialEvent() {
  // Read data from serial line until we get a \n.
  // Store data in inputString
  while (Serial.available()){
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == '\n'){
      stringComplete = true;
    }
  }
}

void loop() {
  serialEvent(); // See if there are data on serial line and get it
  if (stringComplete){ // If we are done reading on serial line
    if (inputString == Temperature){ //WHY YOU FAIL ME?
      digitalWrite(ledPin, HIGH);
      voltage = (analogRead(sensorPin) * 5.0)/1024.0;
      temperatureC = (voltage - 0.5) * 100;
      Serial.print(voltage); Serial.println(" volts");
      Serial.print(temperatureC); Serial.println(" degrees C");
      delay(5000);
      digitalWrite(ledPin, LOW);
  }
  else{
    Serial.print("Not a valid command:");
    Serial.print(' '+inputString);
  }
  // Reset so we can wait for a new command
  inputString = "";
  stringComplete = false;
  }
}

2 个答案:

答案 0 :(得分:1)

首先,我要避免使用String对象。在我看来,最好只使用char数组。它们更轻,避免内存分配和释放。

顺便说一下,如果以后要为它分配一个新的空字符串,为什么还要保留这个空格呢?

无论如何,我认为问题在于你还要将新行追加到字符串中。此外,在Windows环境中,新行是'\r'后跟'\n',因此您在Win和Linux中会遇到不同的行为。

我只是替换

inputString += inChar;
if (inChar == '\n'){
  stringComplete = true;
}

if ((inChar == '\r') || (inChar == '\n')){
  stringComplete = (inputString.length() > 0);
} else {
  inputString += inChar;
}

编辑:我还在stringComplete案例中添加了一个中断,因为否则无法检测到多个命令。所以:

if ((inChar == '\r') || (inChar == '\n')){
  if(inputString.length() > 0) {
    stringComplete = true;
    break;
  }
} else {
  inputString += inChar;
}

答案 1 :(得分:1)

尝试

inputString += inChar.trim(); 
而不是。

inputString += inChar;