This section is actually sorting out and summarizing some of the operations involved in the previous article (not necessarily in the order of the previous article).
Table of contents
3. Summary: UART initialization
1. UART IO initialization
IO initialization is actually setting a pin to be multiplexed as UART and setting the electrical properties of the pin.
void uart1_io_init()
{
// 设置引脚复用为 uart1
IOMUXC_SW_MUX_CTL_PAD_UART1_TX_DATA &= ~(0xF);
IOMUXC_SW_MUX_CTL_PAD_UART1_RX_DATA &= ~(0xF);
// 配置电气属性
IOMUXC_SW_MUX_CTL_PAD_UART1_TX_DATA = 0x10B0;
IOMUXC_SW_PAD_CTL_PAD_UART1_RX_DATA = 0x10B0;
}
2. UART initialization
1. Open/close the serial port
/* 关闭uart1串口 */
void close_uart1()
{
UART1_UCR1 &= ~(1 << 0);
}
/* 打开uart1串口 */
void open_uart1()
{
UART1_UCR1 |= (1 << 0);
}
2. Software reset
/* 软件复位 */
void uart1_software_reset()
{
UART1_UCR2 &= ~(1 << 0);
while((UART1_UCR2 & 0x01) == 0); // 等待软复位结束
}
3. Summary: UART initialization
void uart1_init()
{
// UART IO 初始化
uart1_io_init();
// 关闭uart1串口
close_uart1();
// uart1 软复位
uart1_software_reset();
UART1_UCR1 = 0;
/*
* bit 14: 0 禁止自动检测波特率
*/
UART1_UCR1 &= ~(1 << 14);
/*
* bit 1: 1 接收使能
* bit 2: 1 发送使能
* bit 5: 1 数据位为 8 bit
* bit 6: 0 停止位占 1 bit
* bit 8: 0 关闭奇偶校验
*/
UART1_UCR2 |= ((1 << 1) | (1 << 2) | (1 << 5) | (1 << 14));
UART1_UCR2 &= ~((1 << 6) | (1 << 8));
// 复位选择
UART1_UCR3 |= (1 << 2);
// 波特率配置
/*
* bit 9-7: 101 分频数为1
*/
UART1_UFCR &= ~(7 << 7);
UART1_UFCR |= (5 << 7);
UART1_UBIR = 71;
UART1_UBMR = 3124;
// 打开uart1串口
open_uart1();
}
3. Receive data
Bit 0 of UART1_USR2 can be used to judge whether the data is ready, if there is no data ready, it will always be set to 0; when the data is ready, it will be automatically set to 1.
/* 接收数据 */
unsigned char readData()
{
while ((UART1_USR2 & 0x01) == 0); // 尚未有数据就绪
return UART1_URXD & 0xFF;
}
4. Send data
Bit 3 of UART1_USR2 can be used to judge whether the last data is sent successfully. If it is not sent successfully, it will always be set to 0. First, the previous data is sent out; after the data is sent successfully, it will be automatically set to 1.
/* 发送字符 */
void sendCharacter(unsigned char data)
{
while (((UART1_USR2 >> 3) & 0x01) == 0); // 上一次的发送还没有完成
UART1_UTXD &= ~0xFF; // 低 8 位清零
UART1_UTXD |= (data & 0xFF);
}
/* 发送字符串 */
void sendString(unsigned char* data)
{
unsigned char* cur = data;
while (*cur != '\0') // 字符串以 \0 结尾
{
sendCharacter(*(cur++));
}
}