Home > OS >  STM32 Uart reading issue
STM32 Uart reading issue

Time:08-06

The following code only reads up the first iteration. I don't seem to see the problem.

void USART2_IRQHandler(void){

    if (USART_GetITStatus(USART_MODULE, USART_IT_RXNE) != RESET)
    {
        Rx_Buff[counter  ] = (uint8_t)USART_ReceiveData(USART_MODULE);

        USART_ClearITPendingBit(USART_MODULE, USART_IT_RXNE);
    }
}

uint16_t uart_read(void *load, uint16_t size){

    uint8_t *u = (uint8_t *)load;
    uint8_t p = 0;
    if ((size <= counter))
    {

        for (uint16_t i = 0; i < size; i  )
        {
            u[i] = Rx_Buff[i];
        }
        return size;
    }
}

CodePudding user response:

Two potential issues here.

Firstly, you don't show how counter is defined. It will need to be volatile in order for the compiler to know that the interrupt can change it. Otherwise the compiler will assume it never changes, because the interrupt routine is not called as far as it can see.

Secondly, you don't need to clear the RXNE bit. It is cleared when you access the data register via USART_ReceiveData(). You can actually just read it directly out of the data register, you don't really need to call a function to do it.

CodePudding user response:

You need to re-activate the uart interrupt after receiving each byte. Probably that's why only the first byte is read.

Somewhere in your main() you have activated uart receive interrupt. Repeat the same line in your ISR after reading the byte.

The HAL library function for activating uart receive interrupt is HAL_UART_Receive_IT (I guess you have not used HAL libraries in your code) which generates a interrupt after receiving each byte and needs to be re-activated in the interrupt callback.

CodePudding user response:

There are some points to check here:

  • Check the value of counter to make sure that your code could receive sufficient data that you expected.

  • Value of counter and size at the time you calling API uart_read because at following line you check the condition:

     if ((size <= counter))
    

If you haven't received enough data, it will not able to perform further copy. Actually, function uart_read will return undefined value if size > counter.

  • Assuming that you perform clear counter value and wait until received size bytes then perform further process. In this case, you might need to loop uart_read multiple time until it return to your expected size value.

Additionally, you should consider again the usage of counter, Rx_Buff to avoid the case counter grow so big.

  • Related