Serial.peek always returns 255

Hi, I am pulling my hair out over this Serial.peek not behaving as I expect.

Calling

if( Serial.available() ) {
    char peek = Serial.peek();
    Serial.print("Skip[dec]: ");
    Serial.println(peek, DEC);
    peek = Serial.peek();
    Serial.println(peek, DEC);
    peek = Serial.read();
    Serial.println(peek, DEC);
}

prints

Skip[dec]: 255
255
104

Serial.peek is always returning 255 for me. As the calls are bounded with if Serial.available(), there is data available..... Also, I am sending the character 'h', so the 104 is correct.

Huh???

@OrangeOctober, the problem is not with Serial.peek() but with the definition of “char” in the firmware. In Arduino land, “char” is really a signed byte value but in Spark Core land, it is defined as an unsigned byte.

So, if you use “int8_t” instead of “char”, you will see that the returned value of 255 (unsigned) is really -1 (signed). Serial.peek() will return -1 when nothing is available in the Serial buffer. :smile:

@peekay123 that -1 here == 255 is clear to me. He problem is that bytes are available - notice the guard check for .available - and peek returns the wrong thing. Read returns the correct character which is available.

@OrangeOctober, you are correct! Looking at the Serial code in the main firmware repo, I see that peek() ONLY returns -1 whereas for Serial1 and Serial2, it will return what is expected.

@zachary, any reason for peek() not being implemented in USBSerial?

Nope, that should absolutely be fixed. Thanks for the heads up @OrangeOctober & @peekay123! I just added it as a new issue here:

Pull requests are of course welcome — seems simple and small, but as you might expect we’re extremely focused on the Photon right now. I’ve got a community status update partially drafted that I’ll be posting soon. Cheers!

@OrangeOctober, if you compile locally, the code in the “feature/HAL” branch of the firmware has the code updates. :smile: