Hi,
for one of my projects i need to read from Serial. So for example if X is received via serialEvent it should do something.
So used this example code:
And put a if-statement in there. But it never triggers. Here the code:
String inputString = ""; // a String to hold incoming data
bool 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:
if (inputString == "x") {
Serial.print("You typed a x");
}
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 and check if its a new line so the main loop can do simething with it:
char inChar = (char)Serial.read();
if (inChar == '\n') {
stringComplete = true;
}
else {
// add it to the inputString:
inputString += inChar;
}
}
}
And that's my serial output after pressing some keys (including the x) and enter afterwords:
d
x
x
x
a
d
x
f
I ask my friends who normally know better than me. And they don't know. So i hope i find a the solution here.
Thanks
ED