int UARTAutoBaud(unsigned long *pulRatio){
long lPulse, lValidPulses,LTEmp, lTotal;
volatile long lDelay;
// 配置systICk,将其值设定为最大值;
HWREG(NVIC_ST_RELOAD) = 0xffffffff;
HWREG(NVIC_ST_CTRL) = NVIC_ST_CTRL_CLK_SRC| NVIC_ST_CTRL_ENABLE;
// 打开引脚的边沿触发中断
HWREG(GPIO_PORTA_BASE + GPIO_O_IBE) = UART_RX;
// 使能UART RXD引脚边沿触发中断
HWREG(NVIC_EN0) = 1;
// 采集引脚边沿中断,两个字节的边沿
while(g_ulTickIndex < MIN_EDGE_COUNT)
{}
// 计算systick采样下来的值,对溢出进行处理
for(lPulse = 0; lPulse < (MIN_EDGE_COUNT - 1); lPulse++){
lTemp = (((long)g_pulDataBuffer[lPulse] - (long)g_pulDataBuffer[lPulse + 1]) & 0x00ffffff);
g_pulDataBuffer[lPulse] = lTemp;
}
// 此循环计算两个连续脉冲之间的宽度
for(lPulse = 0; lPulse < (MIN_EDGE_COUNT - 1); lPulse++){
// 精确计算两个连续脉冲之间的宽度
lTemp = (long)g_pulDataBuffer[lPulse];
lTemp -= (long)g_pulDataBuffer[lPulse + 1];
if(lTemp < 0) {
lTemp *= -1;
}
// 验证两个边沿的脉宽是否正确,其算法如下:
// abs(Pulse[n] - Pulse[n + 1]) < Pulse[n + 1] / PULSE_DETECTION_MULT
// 或者
// PULSE_DETECTION_MULT * abs(Pulse[n] - Pulse[n + 1]) < Pulse[n + 1]
if((lTemp * PULSE_DETECTION_MULT) < (long)g_pulDataBuffer[lPulse + 1]) {
lTotal += (long)g_pulDataBuffer[lPulse];
lValidPulses++;
}
else{
lValidPulses = 0;
lTotal = 0;
}
// 7个有效脉冲,就可以计算UART串口速率
if(lValidPulses == 7) {
// 将最后一个脉冲加入计数器,并计算波特率
lTotal += (long)g_pulDataBuffer[lPulse];
*pulRatio = lTotal >> 1;
// 返回成功标识
return(0);
}
}
// 检测失败
return(-1);
}
自定义串口波特率
最新推荐文章于 2024-06-11 21:50:31 发布