我正在尝试通过 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)