GoatFood
GoatFood

Reputation: 25

Trouble with null characters in Arduino

I am trying to write an Arduino program that will translate a text string transmitted through the Serial Monitor to Morse code. This is the offending function:

void serialEvent() {
  while (Serial.available()){
    char inChar = Serial.read();
    input += inChar;
    if (inChar == '\0'){  
      Serial.print("END!");
      stringComplete = true;
    }
  }
}

It should take characters from the serial input one by one, adding them to the input string until it reaches the end of the serial input (ie a null character). For some reason the 'if' statement won't execute for

inChar == '\0'

But if I replace '\0' with an arbitrary character as in

inChar == 'g'

It executes just fine. Am I somehow calling the null character '\0' wrong?

Upvotes: 0

Views: 5282

Answers (1)

rendon
rendon

Reputation: 2363

What I think is that you think that you read all characters in the while loop, Am I right? The truth is that only a character is read by each call to the loop() method, so, you can set stringComplete = true when Serial.available() == 0.

Upvotes: 4

Related Questions