Hello,I am trying to understand the logic of this code for EFM32 USART.I have a putty on my PC where i can send a letter each minute or each hour.
How exactly this loop will work? in each iteration it expects some data to be recieved,what will happen if in a certain itteration no data will be recieved but on the next itteration it will get "G" for example?
Thanks.
Code:
while (1)
{
// Read a line from the UART
for (i = 0; i < BUFFER_SIZE - 1 ; i++ )
{
buffer[i] = USART_Rx(USART1);
if (buffer[i] == '\r')
{
break; // Breaking on CR prevents it from being counted in the number of bytes
}
}
// Echo the line back, adding CRLF
for (j = 0; j < i ; j ++ )
{
USART_Tx(USART1, buffer[j]);
}
USART_Tx(USART1, '\r');
USART_Tx(USART1, '\f');
}
}
The code has no protection against bad data. It assumes 'buffer[]' is clear before any data is received and that '\r' appears before BUFFER_SIZE is exceeded. So the answer to your question is 'anything could happen'. It really needs either some kind of timeout before it is called to ensure fresh data is about to start -or- some special start character to reset 'i' to zero when it is received.
The code operation is simple. If you don't understand it, you should probably work through some C language tutorial.
A simple prerequisite you should know is that USART_Rx() is waiting endlessly until a new character is received. Hence the only way to advance to the output loop is either typing <CR> or typing > BUFSIZE characters.
The code looks more like a simple excercise or test function than a useful application. It's nevertheless safe. Initial buffer[] content is ignored.