Serial reading problem in ESP8266 (must use available)

Hi guys

I have made some project using arduino and esp8266 .

While i made this, i knew some new tip (I can't sure that it can be called tip)

My arduino and esp8266 communicate by UART serial.
Arduino uses softwareserial / esp8266 uses hardware serial and ESP01.

When ESP8266 read some characters that is sent by arduino , it must need Serial.available() function.
in loop .

ex)

if(Serial.available()>0) // it works.
{
ch=Serial.read(); //arduino sent number 0
if(ch==0) count++;
}

if(Serial.read()==0) count++ //it doesn't work. when i program like this, Serial.read() is -1
always. even though arduino sent 0 certainly.

so, in esp8266, available() must be before read() function.
I don't know Why this situation is happened.....

Are there anyone who do know about this situation?

That's because the loop() is fast, very very very fast. And it will not wait. And reading something while there is nothing to read will not magically give you you an answer. So indeed, you HAVE to check if there is something to read before you actually read, always!

wogkr3654:
if(Serial.read()==0) count++ //it doesn't work. when i program like this, Serial.read() is -1
always. even though arduino sent 0 certainly.

Serial.read() is non blocking. i.e. it does not wait for data to be present.
It immediately returns with a status code of an int NOT a char or a uint8_t
If there is no character/byte available in the rx buffer, then read() returns a -1
If there is a character there, it returns the value of the character/byte in the lower 8 bits of the return code.

This is true for all cores.
Here is the code from the AVR core:

int HardwareSerial::read(void)
{
  // if the head isn't ahead of the tail, we don't have any characters
  if (_rx_buffer_head == _rx_buffer_tail) {
    return -1;
  } else {
    unsigned char c = _rx_buffer[_rx_buffer_tail];
    _rx_buffer_tail = (rx_buffer_index_t)(_rx_buffer_tail + 1) % SERIAL_RX_BUFFER_SIZE;
    return c;
  }
}

--- bill

Thank you for your kind answer~!