I'm using a ESP32 DevKitC with Wroom32 on PlatformIO with Arduino framework.
I used the Uart0 at the beginning of my project, but wanted to separate now USB and RS232.
So I moved my serial protocol handling to Serial2 and was faced with some problems.
After trying and searching for some days, I found the reason for the problem.
The serial2.available() is returning values>0, but directly afterwards (same CPU cycle), the Serial2.read() function fails and retuns -1.
I really do not understand this behaviour, because the read() functions internally also does a call to available() and returns -1 if it is 0. So how can it be different?
The following function is called in every loop() cycle (~1ms):
Code: Select all
void RS232_RECEIVE()
{
int ReceivedByte;
int bytesToReceive = Serial2.available();
int TempAvailable;
if (bytesToReceive > 0)
{
while (Serial2.available() > 0)
{
TempAvailable = Serial2.available();
ReceivedByte = Serial2.read();
if (ReceivedByte > -1) //-1 if nothing to read
{
switch ( ReceivedByte )
{
// find <CR><LF>
case 0x0D: // <CR>
//Ignore
break;
case 0x0A: // <LF>
pSerialStream = &ucRxData[0];
ucSerialSize = ucRxDataIdx;
ParseReceivedString();
// reset Index
ucRxDataIdx = 0;
break;
default:
ucRxData[ucRxDataIdx] = (uint8_t) ReceivedByte;
ucRxDataIdx++;
break;
}
}
else
{
Serial.printf("Serial2.available() == %d\n", TempAvailable);
Serial.println("Serial2.read() == -1");
}
}
}
}
Serial2.available() == 1
Serial2.read() == -1
Serial2.available() == 2
Serial2.read() == -1
Serial2.available() == 2
Serial2.read() == -1
Serial2.available() == 2
Serial2.read() == -1
Serial2.available() == 3
Serial2.read() == -1
Serial2.available() == 2
Serial2.read() == -1
Serial2.available() == 3
Serial2.read() == -1
Does anyone have an idea, how this is possible?
Why is Serial2.read() returning -1 while Serial2.available is not 0?