# Serial.read incorrect byte output

**URL:** <https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678>\
**Category:** Programming\
**Created:** [June 11, 2024, 6:13pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678 "2024-06-11T18:13:58Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![username623](https://avatars.discourse-cdn.com/v4/letter/u/ccd318/32.png) [@username623](https://forum.arduino.cc/u/username623)\
**Post date:** [June 11, 2024, 6:13pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/1 "2024-06-11T18:13:58Z")

</div>

Data is constantly coming into the serial line, and a certain order needs to be extracted from it. It starts at '0', and has a fixed size.  
I can’t figure out what is causing the byte reading error.  
If you display the data in the place where I wrote '85', then the first byte there will actually be '85', as it should be immediately after '0'.  
But a few lines below this number becomes like '-1'  
Because of this, I cannot compare the data stream with the target string.  
I tried to redo it in different ways, but always when I call 'Serial.read()' for the second time, the first byte breaks. The rest of the bytes are fine.  
What is the reason for this and how can I fix it?

```arduino
byte dataError[] = {85, 149, 133, 237, 249, 139, 63, 159};
int errCount = 0;

if (Serial.available() > 0) {
    if (Serial.read() == 0) {

      // '85' !

      for (int i = 0; i < 8; i++) {
        if (Serial.read() == dataError[i]) {
          errCount++;
          
        } else {
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print(Serial.read()); // '-1' instead of '85' !
          break;
        }
      }
    }
    if (errCount == 8) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("error");
      delay(2000);
      errCount = 0;
    }
  } 

```

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [June 11, 2024, 6:22pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/3 "2024-06-11T18:22:21Z")

</div>

> [@username623](#):
>
> this number becomes like '-1'

If you get back a value of -1 from Serial.read() then it means that there is nothing to read

You are testing what Serial.available() returns and if at least 1 byte is available then you read 8 bytes. What if all of the required data is not yet available ?

---

<div class="post-metadata">

**Author:** ![username623](https://avatars.discourse-cdn.com/v4/letter/u/ccd318/32.png) [@username623](https://forum.arduino.cc/u/username623)\
**Post date:** [June 11, 2024, 6:33pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/4 "2024-06-11T18:33:37Z")

</div>

> -1 is that Serial.read returns when you call it but there is no byte there to be read.

> If you get back a value of -1 from Serial.read() then it means that there is nothing to read

Thanks guys, that's basically what I thought.  
But the problem is only with the first byte after '0'. The rest are output without problems. I also lengthened the output data string, and all the bytes are displayed normally. Even if I set a delay, I can see every byte on the display, but not '85' (only first Serial.read() will print this out)

---

<div class="post-metadata">

**Author:** ![b707](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/b707/32/854321_2.png) [@b707](https://forum.arduino.cc/u/b707)\
**Post date:** [June 11, 2024, 6:40pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/5 "2024-06-11T18:40:01Z")

</div>

> [@username623](#):
>
> But the problem is only with the first byte after '0'.

It doesn’t matter how the problem manifests itself - in reading only the first byte or the rest. In any case, the fact that your code is incorrect is obvious at first glance.

So fix the bug you were told about and test again.

---

<div class="post-metadata">

**Author:** ![username623](https://avatars.discourse-cdn.com/v4/letter/u/ccd318/32.png) [@username623](https://forum.arduino.cc/u/username623)\
**Post date:** [June 11, 2024, 7:32pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/7 "2024-06-11T19:32:42Z")

</div>

Are you proposing to do something similar?

```arduino
if (Serial.available() >= 8)
    if (Serial.read() == 0) {
      for (int i = 0; i < 8; i++) {
        while (!Serial.available()) {}
        if (Serial.read() == dataError[i]) {
            . . .

```

---

<div class="post-metadata">

**Author:** ![kenb4](https://avatars.discourse-cdn.com/v4/letter/k/bb73d2/32.png) [@kenb4](https://forum.arduino.cc/u/kenb4)\
**Post date:** [June 11, 2024, 8:22pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/9 "2024-06-11T20:22:01Z")

</div>

Every time you call `Serial.read`, you either get `-1` if there is nothing available, or the waiting byte. Once that happens, that byte _is gone_. If you need to use it more than once, you need to store it in a variable.

> [@](#):
>
> ```cpp
> for (int i = 0; i < 8; i++) {
> if (Serial.read() == dataError[i]) {
> 
> ```

Inside the loop, `read` is definitely called there and then sometimes also a second time here

> [@](#):
>
> ```cpp
> lcd.print(Serial.read()); // '-1' instead of '85' !
> 
> ```

for what the loop is implying should be the same byte. So you may get `-1` again.

---

<div class="post-metadata">

**Author:** ![username623](https://avatars.discourse-cdn.com/v4/letter/u/ccd318/32.png) [@username623](https://forum.arduino.cc/u/username623)\
**Post date:** [June 12, 2024, 2:53am UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/10 "2024-06-12T02:53:42Z")

</div>

> lcd.print(Serial.read()); // '-1' instead of '85' !

The reason for this output in the code is that I needed to make sure which of the incoming bytes did not match the byte from the array. I also displayed them together:

```arduino
lcd.setCursor(0, 0);
lcd.print(Serial.read());
lcd.setCursor(5, 0);
lcd.print(dataError[i]);
delay(50);
lcd.clear();

```

And I got this lcd output:

> -1 85  
> 149 149  
> 133 133  
> 237 237  
> 249 249  
> 139 139  
> 63 63  
> 159 159

---

<div class="post-metadata">

**Author:** ![kenb4](https://avatars.discourse-cdn.com/v4/letter/k/bb73d2/32.png) [@kenb4](https://forum.arduino.cc/u/kenb4)\
**Post date:** [June 12, 2024, 4:12am UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/11 "2024-06-12T04:12:00Z")

</div>

Compare these two bits of pseudo-code

```arduino
let value_read = nextValue()
if (value_read == value_expected) {
  do_something()
} else {
  // why did the comparison fail?
  print value_read
  print value_expected
}

```

versus

```arduino
if (nextValue() == value_expected) {
  do_something()
} else {
  // not what I just tested
  print nextValue()
  print value_expected
}

```

---

<div class="post-metadata">

**Author:** ![username623](https://avatars.discourse-cdn.com/v4/letter/u/ccd318/32.png) [@username623](https://forum.arduino.cc/u/username623)\
**Post date:** [June 14, 2024, 6:00pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/12 "2024-06-14T18:00:12Z")

</div>

What I was suggested above doesn't work.  
I found a simple and effective solution with saving to a buffer:

```arduino
if (Serial.available() >= bufferSize) {
    if (Serial.read() == startByte) {
		byte buffer[bufferSize];
		Serial.readBytes(buffer, bufferSize);
	
		if(memcmp(buffer, dataErr, bufferSize) == 0) {
			lcd.clear();
			lcd.setCursor(5, 0);
			lcd.print("Error");
	
		} else {
	
			lcd.clear();
			lcd.setCursor(5, 0);
			lcd.print("Ok");
		}
    }
}

```

---

<div class="post-metadata">

**Author:** ![kenb4](https://avatars.discourse-cdn.com/v4/letter/k/bb73d2/32.png) [@kenb4](https://forum.arduino.cc/u/kenb4)\
**Post date:** [June 14, 2024, 10:53pm UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/13 "2024-06-14T22:53:44Z")

</div>

> [@](#):
>
> ```arduino
> if (Serial.available() >= bufferSize) {
> if (Serial.read() == startByte) {
> byte buffer[bufferSize];
> Serial.readBytes(buffer, bufferSize);
> 
> ```

If there are exactly `bufferSize` bytes available, the `read` consumes one, and then `readBytes` will consume and return `bufferSize - 1` (which you don't check). The last byte in `buffer` will not be set/overwritten, and may coincidentally match (or not) the last byte of `dataErr`

---

<div class="post-metadata">

**Author:** ![username623](https://avatars.discourse-cdn.com/v4/letter/u/ccd318/32.png) [@username623](https://forum.arduino.cc/u/username623)\
**Post date:** [June 15, 2024, 9:18am UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/14 "2024-06-15T09:18:40Z")

</div>

Thanks, you are right, I will add to this.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [December 12, 2024, 9:19am UTC](https://forum.arduino.cc/t/serial-read-incorrect-byte-output/1270678/15 "2024-12-12T09:19:17Z")

</div>

Closed on December 12, 2024, 9:19am UTC

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
