0

I used multiple of Serial.read() and Serial.parseInt() to get characters and a number ( like "xy123" ) on an Arduino UNO. Then I checked the result on Serial monitor.

Unfortunately I couldn't get the character with second Serial.read().

Here's the code:

void setup(){
    Serial.begin(9600);
}

void loop(){  
  if (Serial.available() >0) {

    // I want to reacive the characters like "xy123"
    char input1 = Serial.read();
    char input2 = Serial.read();
    int value = Serial.parseInt();

    Serial.println(input1); // ok
    Serial.println(input2); // * no good * (-1)
    Serial.println(value);  // ok

    // Writing some codes with input1 ,input2 and value ...        
  }
// I don't want to use delay(). 
}

How do I get the second character?

Thanks.

3
  if (Serial.available() >0) {

This is like saying "I won't go into that room until there is at least one dog in there". Someone tells you there is a dog there. You go into the room and say "Hey, why aren't there two dogs there?".

If you want to read two bytes one approach is to wait until they are available:

  if (Serial.available() >= 2) {
| improve this answer | |
  • 1
    but you did send two dogs into the tunnel leading to that room :-) – Juraj Jul 9 '18 at 12:51
  • 1
    Exactly! But one hasn't arrived yet. :) Dogs move at a finite speed, the same way that serial communications does. In fact I think everything moves at a finite speed. – Nick Gammon Jul 9 '18 at 22:46
2

You did not read the second character, because the character did not arrive yet. Wait until it is available. read doesn't wait. parseInt has the waiting build-in.

You can wait for the second character by reading the two characters with the waiting function readBytes. It will wait a second for the next character.

char buff[2];
if (Serial.readBytes(buff, 2) == 2) {
  char input1 = buff[0];
  char input2 = buff[1];
...

If you send only one character, readBytes will wait one second for the next and the returns that one char was read.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.