user1494994
user1494994

Reputation:

Arduino serial event not returning

I'm working on an Arduino project and would like to receive some commands from the Serial port with the arduino Serial event. However it always won't fulfill a condition, making the code not knowing the serial event has been finished. Here is my code.

void serialEvent() {
    while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read(); 
    if (inChar == '`')
    {
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
        if (inChar == '|') {
            settingsReceived = true; // <----- This will never be called
            Serial.println("true"); // <------ Nor this will too
        }  
    }
  }
}

I've tried passing the string `Hello| from the serial monitor yet it won't respond. Additionally, I've tried the Line ending with No Line Ending and Newline yet it won't work, Can anyone please help? Thanks!

Upvotes: 2

Views: 7243

Answers (2)

user1494994
user1494994

Reputation:

I have figured the problem, Serial.read() will only read a byte per time, for example, `Hello| will be split into

` H e l l o |  

So for the first time, the if (inChar == '`') is true, therefore entering the actions inside, however from the second char, (H, e, l, l, o, |) are not the char "`", meaning if (inChar == '`') is not true, not letting it to enter the condition after that.

Here should be the propoer way of doing it:

void serialEvent() {
    if (Serial.available())
    {
       char inChar = (char)Serial.read();
       if (inChar != '`')
       {
         return;    // <----- Rejecting the char if not starting with `
       } 
    }

    while (Serial.available()) {
    // get the new byte:
      char inChar = (char)Serial.read(); 
    // add it to the inputString:
      inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
      if (inChar == '|') {
        settingsReceived = true;
        Serial.println("true");
      }

    }
}

Upvotes: 2

JackCColeman
JackCColeman

Reputation: 3807

Is inputstring being defined in the sketch? Also, loop() and setup() have some tasks to complete. See: http://arduino.cc/en/Tutorial/SerialEvent this page has a good starting example, get it to work first and then modify it for your specific code.

When you type "Hello|" and press enter, what is the '|' for? Is there a reason why you are NOT testing for '\n' as the line termination character?

Also, you are testing for inChar == '`' and then adding it to string, but you are typing in "Hello"? Serial I/O passes one character at a time, so you need to allow the inChars that are typed in.

Upvotes: 1

Related Questions