AnsweredAssumed Answered

USART communication (code problem)

Question asked by p.klemen on Dec 13, 2013
Latest reply on Dec 14, 2013 by p.klemen
Dear Sir/Madam,

I have been trying to understand what I am doing wrong with my serial communication. I am using STM32L Discovery board and have successfully sent and received bytes on my board/PC.

I would like to send bytes from my PC to the board until a NEWLINE constant is received and then continue with the main loop.

My code works to some extent:

while(1) {     
        // Check if receive data flag is set (byte received)
        if(USART_GetFlagStatus(USART2,USART_FLAG_RXNE) == SET) {
            // Incoming byte over serial
            char incomingByte;                     
            while(1) {             
                // Wait until receive data register is empty (the flag is automatically cleared after read)
                while(USART_GetFlagStatus(USART2,USART_FLAG_RXNE) == RESET);               
                // Read the byte
                incomingByte = (char) USART_ReceiveData(USART2);               
                // If end command is received, break
                if(incomingByte == '\n')
                // Check the data
                // Wait until transmit data register is empty
                while(USART_GetFlagStatus(USART2,USART_FLAG_TXE) == RESET);                            
        while(USART_GetFlagStatus(USART2,USART_FLAG_TXE) == RESET);

The problem is, when I send the data for the first time, the program is stuck in the inner loop (as it though did not receive the newline). When I send the data the second time, it works as I expect. Please see the image below for more clear explanation.


Thank you for your help and best regards,