在线时间7 小时
UID3107528
注册时间2015-3-16
NXP金币0
该用户从未签到
注册会员

- 积分
- 61
- 最后登录
- 2015-6-19
|
本帖最后由 gaow11 于 2015-6-3 21:50 编辑
各位大侠:
我用KL16的UART0串口每隔1ms给电脑发送一帧数据,格式是61 XX XX XX XX 共五个字节这样的,115200波特率,但是在串口猎人上接收到的数据会有丢数据或者数据不对的,看了一下寄存器,实际波特率算下来是117647,我用的是网上的例程,串口初始化函数是uart0_init(UART0_BASE_PTR,2000,115200);
void uart0_init (UART0_MemMapPtr uartch, int sysclk, int baud)
{
uint8 i;
uint32 calculated_baud = 0;
uint32 baud_diff = 0;
uint32 osr_val = 0;
uint32 sbr_val, uart0clk;
uint32 baud_rate;
uint32 reg_temp = 0;
uint32 temp = 0;
SIM_SCGC4 |= SIM_SCGC4_UART0_MASK;
// Disable UART0 before changing registers
UART0_C2 &= ~(UART0_C2_TE_MASK | UART0_C2_RE_MASK);
// Verify that a valid clock value has been passed to the function
if ((sysclk > 50000) || (sysclk < 32))
{
sysclk = 0;
reg_temp = SIM_SOPT2;
reg_temp &= ~SIM_SOPT2_UART0SRC_MASK;
reg_temp |= SIM_SOPT2_UART0SRC(0);
SIM_SOPT2 = reg_temp;
}
// Verify that a valid value has been passed to TERM_PORT_NUM and update
// uart0_clk_hz accordingly. Write 0 to TERM_PORT_NUM if an invalid
// value has been passed.
if (TERM_PORT_NUM != 0)
{
reg_temp = SIM_SOPT2;
reg_temp &= ~SIM_SOPT2_UART0SRC_MASK;
reg_temp |= SIM_SOPT2_UART0SRC(0);
SIM_SOPT2 = reg_temp;
// Enter inifinite loop because the
// the desired terminal port number
// invalid!!
while(1)
{}
}
// Initialize baud rate
baud_rate = baud;
// Change units to Hz
uart0clk = sysclk * 1000;
// Calculate the first baud rate using the lowest OSR value possible.
i = 4;
sbr_val = (uint32)(uart0clk/(baud_rate * i));
calculated_baud = (uart0clk / (i * sbr_val));
if (calculated_baud > baud_rate)
baud_diff = calculated_baud - baud_rate;
else
baud_diff = baud_rate - calculated_baud;
osr_val = i;
// Select the best OSR value
for (i = 5; i <= 32; i++)
{
sbr_val = (uint32)(uart0clk/(baud_rate * i));
calculated_baud = (uart0clk / (i * sbr_val));
if (calculated_baud > baud_rate)
temp = calculated_baud - baud_rate;
else
temp = baud_rate - calculated_baud;
if (temp <= baud_diff)
{
baud_diff = temp;
osr_val = i;
}
}
if (baud_diff < ((baud_rate / 100) * 3))
{
// If the OSR is between 4x and 8x then both
// edge sampling MUST be turned on.
if ((osr_val >3) && (osr_val < 9))
UART0_C5|= UART0_C5_BOTHEDGE_MASK;
// Setup OSR value
reg_temp = UART0_C4;
reg_temp &= ~UART0_C4_OSR_MASK;
reg_temp |= UART0_C4_OSR(osr_val-1);
// Write reg_temp to C4 register
UART0_C4 = reg_temp;
reg_temp = (reg_temp & UART0_C4_OSR_MASK) + 1;
sbr_val = (uint32)((uart0clk)/(baud_rate * (reg_temp)));
/* Save off the current value of the uartx_BDH except for the SBR field */
reg_temp = UART0_BDH & ~(UART0_BDH_SBR(0x1F));
UART0_BDH = reg_temp | UART0_BDH_SBR(((sbr_val & 0x1F00) >> 8));
UART0_BDL = (uint8)(sbr_val & UART0_BDL_SBR_MASK);
/* Enable receiver and transmitter */
UART0_C2 |= (UART0_C2_TE_MASK
| UART0_C2_RE_MASK );
}
else
{
{}
}
}
请各位大侠指正,谢谢!
|
|