Understanding Serial.available()

@GolamMostafa, Serial.read() returns an int, not a byte. So you should store it in an int and rerun your tests.

Serial.read() returns an int, not a byte.

Does it mean that the serial FIFO buffer is word oriented? If so, it agrees with our good old days’ knowledge of UART Port of IBMPC. The upper 8-bit of the return value contains the status bits and the lower 8-bit contains the actual character received. In Arduino IDE, execution of byte x = Serial.read(); automatically takes the lower 8-bit of the 16-bit buffer location. In old days, we had to do it in a different way. (Thanks to clever Arduino IDE.)

Old Days’ Method:

#include	<stdio.h>
#include	<bios.h>
#include	<conio.h>
#define 	COM1INI	bioscom(0x00, 0xC7, 0x0000)  /*c7=2SB, C3=1SB */
#define 	COM1WR  bioscom(0x01, ch1,   0x0000)
#define 	COM1RD  comval.z=bioscom(0x02, 0x00, 0x0000)
#define 	COM1STS comval.z = bioscom(0x03, 0x00, 0x0000) /* Status Read */
#define	TxRDY   ((comval.ch2[1])& 0x20) /*!=0x00 */   
#define	RxRDY	((comval.ch2[1])& 0x01) 
#define 	RxDATA  (comval.ch2[0])

void main(void)

{
   unsigned char ch1 ;

  union 	{
			int z;
			unsigned char ch2[2];
      		} 	comval;

  clrscr();
COM1INI; 		/* COM1 initialize at 4800Bd,NP,2-SB */ 

While ((ch1 = getche()) != ‘Q’)	/* read ASCII code of pressed down key */
{
		COM1STS ;	/* reading COM1 status after executing bioscom(0x03, , );*/


		if (TxRDY != 0x00)
	
		COM1WR ;	/* write ASCII code of the pressed down key on COM1 port */

		If (RxRDY !=00)
		{
			COM1RD ;	/* Data has arrived at COM1 port and read it */
			putchar (RxDATA) ;	/* show the received character on screen */
		}

	}
	exit(0);
}

Serial.read() returns an int, not a byte.

GolamMostafa: Does it mean that the serial FIFO buffer is word oriented?

No, it means that, when no data is available to read, Serial.read() returns a value (-1) that cannot possibly be read from the serial port. When there is data available, Serial.read() returns a value in the range 0 to 255. There are no status bits with Serial.read().

In short, Serial.read() returns 256 values (-1 to 255) which cannot possibly be contained in an 8 bit data type thus Serial.read() returns a number of signed int type.

adwsystems: In short, Serial.read() returns 256 values (-1 to 255) which cannot possibly be contained in an 8 bit data type thus Serial.read() returns a number of signed int type.

Correction: Serial.read() can return one of 257 values. 0 through 255 is 256 values (which can be stored in a byte), and -1 is a 257th value.