warning about Serial.read()

Hi,
Any ideas what this warning means!

"narrowing conversion of 'Serial.HardwareSerial::read()' from 'int' to 'byte {aka unsigned char}'"

Below is the full warning.

C:\Users\in4si\Desktop\iFlag_WS2812B_v1\iFlag_WS2812B_v1.ino: In function 'void serialEvent()':

C:\Users\in4si\Desktop\iFlag_WS2812B_v1\iFlag_WS2812B_v1.ino:166:20: warning: narrowing conversion of 'Serial.HardwareSerial::read()' from 'int' to 'byte {aka unsigned char}' inside { } [-Wnarrowing]

         Serial.read(),      // (FF) Command trigger byte

         ~~~~~~~~~~~^~

Thanks

Don't know. It might be obvious from your code, so please post it, don't forget the code tags.

Serial.read returns an int. You are assigning the return value to a byte. The warning use telling you that you may lose bit. This is not a problem if you are simply trying to get the character value returned. It is a warning, not an error.

Yes, you are right.
Thanks a million... :slight_smile:

Below is my code...

 byte command[ 4 ] =
      {
        Serial.read(),      // (FF) Command trigger byte
        Serial.read(),      // (00-FE) Command id
        Serial.read(),      // (00-FE) Command value
        Serial.read()       // (00-FE) Command extra value
      };

If you know the conversion is safe (e.g., the code checks that there are 4 bytes to read in the buffer), you can silence the warning by casting to byte:

byte command[4] =
{
  (byte)Serial.read(),      // (FF) Command trigger byte
  (byte)Serial.read(),      // (00-FE) Command id
  (byte)Serial.read(),      // (00-FE) Command value
  (byte)Serial.read()       // (00-FE) Command extra value
};

Yes, no more warnings.
Thank you.

Are you making sure there are 4 bytes in the buffer before you read it?

Presumably the reason the return value is an int, the return value will be -1 when the buffer is empty:

Returns
The first byte of incoming serial data available (or -1 if no data is available). Data type: int.

Best to make sure Serial.available() >= 4 before reading four bytes. Serial.available() returns the number of bytes available for reading.

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