UART编程
1.初始化
我们的2440支持3个UART串口,以uart0为例讲解。 那么我们需要实现以下这几个函数完成串口的最基本功能:
(1)uart0_init()用于初始化串口 (2)putchar()用于发送一个字符 (3)getchar()用于接收一个字符 (4)puts()用于发送一串字符
1.uart0_init()
1.配置uart0引脚 (1)根据原理图GPH2,3用于TxD0, RxD0。
(2)查看dataset,配置GPH控制寄存器,让GPH2,3配成uart模式;为了将其保持为高电平,先设置其为上拉。
GPHCON &= ~((3<<4) | (3<<6));
GPHCON |= ((2<<4) | (2<<6));
GPHUP &= ~((1<<2) | (1<<3)); /* 使能内部上拉 */
UCON0 = 0x00000005; /* 时钟源选择PCLK,中断/查询模式 */
2.设置波特率 /* uart clock=50M,假设我们想要波特率=115200, ** 根据公式UBRDIVn = (int)(UART clock/( buad rate x 16) ) –1 ** 得到UBRDIVn = (int)( 50000000 / ( 115200 x 16) ) –1 = 26 */ UBRDIV0 = 26;
3. 设置数据格式
数据格式设置为常用的8n1,表示8个数据位, 无较验位, 1个停止位
ULCON0 = 0x00000003; /* 8n1: 8个数据位(数据+校验), 无较验位, 1个停止位 */
2.putchar(),getchar()
putchar就是向发送寄存器(UTXH0)写入值进去。
getchar就是从接受寄存器(URXH0)取出值。
无论是getchar还是putchar都可以通过读取状态寄存器(UTRSTAT0)来作为传输结束判断标志。
查询其第2位判断发送buff是否为空,即上一次发送是否完成,如果完成即向UTXH0写入要发送的新数据;
查询其第0位判断接收buff是否有数据接受到,如果有数据接收到,返回接收buffer的值。
int putchar(int c)
{
while (!(UTRSTAT0 & (1<<2)));
UTXH0 = (unsigned char)c;
}
int getchar(void)
{
while (!(UTRSTAT0 & (1<<0)));
return URXH0;
}
3.puts()
int puts(const char *s)
{
while (*s)
{
putchar(*s);
s++;
}
}
相关文章









