参考资料:
https://www.cnblogs.com/mr-raptor/archive/2011/06/20/2347677.htmlhttps://www.cnblogs.com/mr-raptor/archive/2011/06/20/2347677.html
http://wiki.100ask.org/
1、串口电路,MAX232与2440的GPH2、GPH3相连接
2、程序结构
uart0_init()用于初始化串口
putchar()用于发送一个字符
getchar()用于接收一个字符
puts()用于发送一串字符
<1>uart0_init()函数
设置引脚用于串口:根据原理图和参考手册设置GPH2,3用于TxD0, RxD0,并且为了将其保持为高电平,先设置其为上拉;
#define GPHCON *(volatile ulong *)0x56000070 #define GPHUP *(volatile ulong *)0x56000078
GPHCON &= ~((3<<4)|(3<<6))
GPHCON |= ((2<<4)|(2<<6))
GPHUP &= ~((1<<2)|(1<<3))
相关的寄存器:
/* UART registers*/ #define ULCON0 (*(volatile unsigned long *)0x50000000) #define UCON0 (*(volatile unsigned long *)0x50000004) #define UFCON0 (*(volatile unsigned long *)0x50000008) #define UMCON0 (*(volatile unsigned long *)0x5000000c) #define UTRSTAT0 (*(volatile unsigned long *)0x50000010) #define UTXH0 (*(volatile unsigned char *)0x50000020) #define URXH0 (*(volatile unsigned char *)0x50000024) #define UBRDIV0 (*(volatile unsigned long *)0x50000028)
ULCON0寄存器:// 查询方式,UART时钟源为PCLK
UCON0=0x05(0101)
ULCON0寄存器:8N1(8个数据位,无较验,1个停止位)
ULCON0 = 0x03/* 8n1: 8个数据位, 无较验位, 1个停止位 */
UBRDIV0寄存器:
uart clock=50M(PCLK),波特率假设是115200,
UBRDIVn = (int)( 50000000 / ( 115200 x 16) ) –1 = 26
UBRDIV0 = 26;
UFCON0寄存器:
UFCON0 = 0x00; // 不使用FIFO
UFCON0寄存器:
UMCON0 = 0x00; // 不使用流控
uart0_init()函数
/* * 初始化UART0 * 115200,8N1,无流控 */ void uart0_init(void) { GPHCON |= 0xa0; // GPH2,GPH3用作TXD0,RXD0 GPHUP = 0x0c; // GPH2,GPH3内部上拉 ULCON0 = 0x03; // 8N1(8个数据位,无较验,1个停止位) UCON0 = 0x05; // 查询方式,UART时钟源为PCLK UFCON0 = 0x00; // 不使用FIFO UMCON0 = 0x00; // 不使用流控 UBRDIV0 = UART_BRD; // 波特率为115200 }
发送字符函数
#define TXD0READY (1<<2)
void putc(unsigned char c) { /* 等待,直到发送缓冲区中的数据已经全部发送出去 */ while (!(UTRSTAT0 & TXD0READY)); /* 向UTXH0寄存器中写入数据,UART即自动将它发送出去 */ UTXH0 = c; }
发送字符串函数
void puts(char *str) { int i = 0; while (str[i]) { putc(str[i]); i++; } }