Search code examples
cembeddedstm32interruptuart

Uart receive interrupt serial port terminal for stm32


I've been trying to implement a kind of emulator for my code from serial port terminal. I am sending the data from the terminal with uart receive interrupts and saving the data to an array but I have to enter a few data and save it.

I want my uart function to wait for enter key and then proceed to the next function for next data. I couldn't figure out how to implement it and I don't want to use putchar or fscanf. How can I develop my code to work this way? I can't use while loop or if statements because I am using interrupts.


Solution

  • Code implementation can be very different depending on your hardware/software settings(e.g. UART peripheral setting, interrupt setting ...). Therefore, if you share your current settings and code implementation, I can give you a more accurate answer.

    If you are using HAL_UART_Receive_IT for UART RX Interrupt, that's usually not a good idea. Becuase the CPU has to copy each character from the UART peripheral to memory one by one.

    In general, using RX DMA is a way to reduce CPU load and make code implementation easier.

    After enabling the RX DMA of your UART, refer to the code template below and try to implement it.

    #define RxBuffSize    256
    
    uint8_t RxBuff[RxBuffSize];
    
    void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
    {
        if (huart == &huart1)
        {   
            int i;
            for(i = 0; i < Size; i++){
                if(RxBuff[i] == '\n'){
                    // TODO something...
                }
            }
            HAL_UARTEx_ReceiveToIdle_DMA(&huart1, RxBuff, RxBuffSize);
            __HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
        }
    }
    
    
    int main(void){
    
        //
        //
        //
    
        HAL_UARTEx_ReceiveToIdle_DMA(&huart1, RxBuff, RxBuffSize);
        __HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
    
        //
        //
        //
    
    }