STC单片机串口接收一帧数据全为0的原因和解决办法
typedef unsigned char BYTE;
void UART_RX_DATA_JX(void)
{
volatile BYTE Uart_Rx_temp = SBUF;
if(state_machine == 0)
{
if(Uart_Rx_temp == 0xA5)
{
state_machine = 1;
m_ucData[0] = Uart_Rx_temp;
}
else
{
state_machine = 0;
}
}
else if(state_machine == 1)
{
if(Uart_Rx_temp == 0x5A)
{
state_machine = 2;
m_ucData[1] = Uart_Rx_temp;
}
else
{
state_machine = 0;
}
}
else if(state_machine == 2)
{
rcvcount = Uart_Rx_temp;
state_machine = 3;
lencnt = 0;
m_ucData[2] = Uart_Rx_temp;
}
else if(state_machine == 3)
{
m_ucData[lencnt+3] = Uart_Rx_temp;
if(lencnt == m_ucData[2]-1)
{
retval = 0xaa;
state_machine = 0;
}
else
{
lencnt ++;
}
}
else
{
state_machine = 0;
}
}
void Uart() interrupt 4 using 1
{
if (RI)
{
UART_RX_DATA_JX();
RI = 0;
}
if (TI)
{
TI = 0;
busy = 0;
}
}
问题的关键在于对接收数据缓存Uart_Rx_temp的定义。如果不加volatile修饰,编译器会优化处理,导致收到数据全为0。另一种解决方式是将Uart_Rx_temp定义为全局变量。
以上程序在STC单片机实测验证通过,其他51系列单片机可以借鉴。