我試圖從串行線讀取一個字符串並將其與命令列表進行比較。如果字符串是一個有效的命令,Arduino應該繼續並執行一些操作,並在串行線路上返回一些信息。 但是,我的comaprison總是失敗(給我「不是一個有效的命令響應」)。我曾嘗試從Arduino串行監視器和Python腳本發送「temp」一詞。Arduino從串行線讀取字符串並比較
我的Arduino代碼:
所有我會避免使用String
對象的
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;
}
}