string - 以字符串形式接收数字(uart)

标签 string serial-port stm32 uart

我正在尝试通过 uart 接收一个打包为字符串的数字。我发送数字 1000,所以我得到 4 个字节 + 空字符。但是,当我使用 atoi() 将数组转换为数字并将整数与 1000 进行比较时,我并不总是得到正确的数字。这是我用于接收号码的中断处理函数。可能出了什么问题?

void USART1_IRQHandler(void)
{
    if( USART_GetITStatus(USART1, USART_IT_RXNE) )
    {
        char t = USART1->RDR;
        if( (t != '\n' && t!='\0') && (cnt < 4) )
        {
            received_string[cnt] = t;
            cnt++;
        }
        else
        {
            cnt = 0;
        }

        t = 0;
        received_string[4] = 0;
    }

    if(cnt==4)
    {
        data = atoi(received_string);
    }
}

最佳答案

请尝试使用此代码。在这里,我检查接收的最大字节数,以避免缓冲区溢出(以及可能的硬件故障)。我创建了一个特定的函数来清除接收缓冲区。您还可以找到字符串长度的定义,因为代码更灵活。我还建议检查接收错误(读取传入字节后),因为如果出现错误,接收将被阻止。

//Define the max lenght for the string
#define MAX_LEN 5

//Received byte counter
unsigned char cnt=0;

//Clear reception buffer (you can use also memset)
void clearRXBuffer(void);

//Define the string with the max lenght
char received_string[MAX_LEN];

void USART1_IRQHandler(void)
{
    if( USART_GetITStatus(USART1, USART_IT_RXNE) )
    {
        //Read incoming data. This clear USART_IT_RXNE
        char t = USART1->RDR;

        //Normally here you should check serial error!
        //[...]

        //Put the received char in the buffer
        received_string[cnt++] = t;     

        //Check for buffer overflow : this is important to avoid
        //possible hardware fault!!!
        if(cnt > MAX_LEN)
        {
            //Clear received buffer and counter
            clearRXBuffer();                
            return;
        }

        //Check for string length (4 char + '\0')
        if(cnt == MAX_LEN)
        {
            //Check if the received string has the terminator in the correct position
            if(received_string[4]== '\0'){

                //Do something with your buffer
                int data = atoi(received_string);
            }

            //Clear received buffer and counter
            clearRXBuffer();                
        }
    }
}

//Clear reception buffer (you can use also memset)
void clearRXBuffer(void){
    int i;
    for(i=0;i<MAX_LEN;i++) received_string[i]=0;
    cnt=0;
}

关于string - 以字符串形式接收数字(uart),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679035/

相关文章:

java - 运行程序时抛出NullPointerException,但 Debug模式下不抛出NullPointerException Java jssc 串口通信

c - 将数据从串行端口传输到文本文件

embedded - Cortex-M3 STM32F103 内核在闪存页删除期间是否会因为 FPEC 繁忙且无法从闪存中获取更多指令而停止?

gcc - STM32 ADC 连续转换模式不会自动启动转换

c - 寻找一个好的 C 哈希表实现

python - 如何在不考虑空格并知道字符串的原始索引的情况下在字符串中查找子字符串

Python 漂亮的矩阵打印

c - 如何从文件读取两个字符串并将它们存储在两个单独的数组中

c++ - 根据多个终止字符从 UART 收集数据

STM32F4 : EEPROM 25LC256 management through SPI