UART轮询模式比中断模式要简单得多,UART初始化代码如下:
void UARTInit(void)
{
// 配置 UART1 参数
// 波特率 115200 数据位 8 停止位 1 无校验位
UARTConfigSetExpClk(SOC_UART_1_REGS, UART_1_FREQ, BAUD_115200, UART_WORDL_8BITS, UART_OVER_SAMP_RATE_16);
// 使能 UART1
UARTEnable(SOC_UART_1_REGS);
}
因为选择的是non-fifo模式,所以UART初始化代码里只需要设置UART的参数就行了,不需要再配置FIFO并使能FIFO。同时,因为采用轮询模式,所以不需要进行UART中断初始化,所以,对UART初始化之后,就完成了所有的初始化步骤了。主函数如下:
int main(void)
{
// 外设使能配置
PSCInit();
// GPIO 管脚复用配置
GPIOBankPinMuxSet();
// UART 初始化
UARTInit();
// 发送字符串
unsignedchar i;
for(i = 0; i < 34; i++)
UARTCharPut(SOC_UART_1_REGS, Send[i]);
// 接收缓存
unsignedchar Receive;
// 主循环
for(;;)
{
Receive=UARTCharGet(SOC_UART_1_REGS);
UARTCharPut(SOC_UART_1_REGS, Receive);
}
}
主函数也非常简单,先是UARTCharPut(SOC_UART_1_REGS, Send[i]);把已定义好的一串字符串发送到串口,UARTCharPut函数如下:
void UARTCharPut(unsigned int baseAdd, unsigned char byteTx)
{
unsigned int txEmpty;
txEmpty = (UART_THR_TSR_EMPTY | UART_THR_EMPTY);
/*
** Here we check for the emptiness of both the Trasnsmitter Holding
** Register(THR) and Transmitter Shift Register(TSR) before writing
** data into the Transmitter FIFO(THR for non-FIFO mode).
*/
while (txEmpty != (HWREG(baseAdd + UART_LSR) & txEmpty));
/*
** Transmitter FIFO(THR register in non-FIFO mode) is empty.
** Write the byte onto the THR register.
*/
HWREG(baseAdd + UART_THR) = byteTx;
}
在该函数中,程序先是不停地查询LSR寄存器的TEMT和THRE两位,确定THR寄存器(transmitter holding register,THR)和TSR寄存器(transmitter shift register,TSR)是否为空,如果为空,则往THR里写一字节的数,否则继续查询,直到为空。
(指南P1440)
然后程序开始进入主循环中,在主循环中,程序先是等待接收数据Receive=UARTCharGet(SOC_UART_1_REGS); UARTCharGet函数如下:
int UARTCharGet(unsigned int baseAdd)
{
int data = 0;
/*
** Busy check if data is available in receiver FIFO(RBR regsiter in non-FIFO
** mode) so that data could be read from the RBR register.
*/
while ((HWREG(baseAdd + UART_LSR) & UART_DATA_READY) == 0);
data = (int)HWREG(baseAdd + UART_RBR);
return data;
}
当LSR寄存器的DR位为0时,说明数据已准备好,接收缓冲寄存器RBR(receiver buffer register (RBR))中收到了数据,然后就开始将RBR中的数据读出来,因为是non-fifo模式,所以读出一个字节的数据。
(指南P1442)
然后,程序将读到的数据原封不动地发到UART,返还回去,UARTCharPut(SOC_UART_1_REGS, Receive);。