Reputation: 247
I'm trying to read a string from the serial line and compare it to a list of commands. If the string is a valid command the Arduino should go ahead and do something, and return some info on the serial line. However, my comaprison always fails (give me the "not a valid command response"). I have tried sending the word "temp" both from the Arduino serial monitor and from a Python script.
My arduino code:
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;
}
}
Upvotes: 2
Views: 3108
Reputation: 2880
First of all I'd avoid using the String
object. It's better, in my opinion, to just use char arrays. They are lighter and avoid memory allocation and deallocation.
By the way, why are you reserving the space if, later, you are assigning it a new empty string?
Anyway, I think that the problem is that you are appending also the new line to the string. Moreover, in a windows environment a new line is a '\r'
followed by a '\n'
, so you get different behaviour in Win and Linux.
I'd just replace
inputString += inChar;
if (inChar == '\n'){
stringComplete = true;
}
with
if ((inChar == '\r') || (inChar == '\n')){
stringComplete = (inputString.length() > 0);
} else {
inputString += inChar;
}
EDIT: I'd also add a break in the stringComplete case, since otherwise multple commands can't be detected. So:
if ((inChar == '\r') || (inChar == '\n')){
if(inputString.length() > 0) {
stringComplete = true;
break;
}
} else {
inputString += inChar;
}
Upvotes: 1