AnsweredAssumed Answered

USART send/receive interference

Question asked by p.klemen on Sep 27, 2014
Dear programmers,

I would like to ask for an opinion regarding the USART data send/receive. The USART receive data is handled by the IRQ service:

void USART1_IRQHandler(void){
    if(USART_GetITStatus(USART1,USART_IT_RXNE)) {  
         
        static uint8_t bcount = 0;
        static uint8_t CRCcount = 0;
        static bool CRC_flag = false;
                 
        incomingByte = (char) USART1->DR;
 
        if(CRC_flag == false) {
            if(incomingByte == '\n') {      
                incomingBuffer[bcount] = '\n';
                bcount++;
                incomingBuffer[bcount] = '\0';
                bcount = 0;
                CRC_flag = true;
            }          
            else {
                incomingBuffer[bcount] = incomingByte;
                bcount++;          
            }
        }      
        else if(CRC_flag == true) {
            CRCBuffer[CRCcount] = (uint8_t) incomingByte;          
            CRCcount++;        
            if(CRCcount >= 2) {
                CRCcount = 0;
                CRC_flag = false;
                bCommandReceived = true;
            }
        }      
    }
}

In general, my main program code looks like this:

// Global var
bool bCommandReceived = false;

int main() {
  // INITIALIZATION HERE
   
  while(1) {
    if(bCommandReceived == true) {
     bCommandReceived = false;
     // PROCESS THE COMMAND
    }
   // EVERY ITERATION WRITE DATA TO THE USART (TX) - ~20 bytes,basically USART1->DR
 }
}

So every time, the data is received over the RX line, the interrupt is triggered. I need to receive the data continuously, since the computer (PC) is "pinging" the micro-controller every ~250 ms to see if the communication is OK. Also, some other commands are being sent from PC manually.

My question is what can happen if the interrupt is triggered (RX) at the same time the data is being sent to the TX in the while loop? Could this cause an error by mixing up the bytes that need to be sent and the bytes that are being received? How could I avoid this?

I hope I am being clear.

Thank you very much for your answer and best regards,
K

Outcomes