一、准备工作
1、KEIL C51编译环境
2、CodeGen8 代码生成器
3、MC96F6332D 开发板
4、USB-OCD II仿真器
二、生成串口代码
1、在CodeGen8 代码生成器的外设窗口中选择内部RC时钟作为时钟源,设置时钟源的频率为8MHz,配置UART的引脚P40(Pin8)-->RXD0引脚, P41(Pin9)-->TXD0引脚;配置UART0的参数为ASync. 9600bps N 8 1;具体配置如下图①所示,代码生成部分如下图②所示;
2、点击 C 图标,自动打开KEIL C51软件;针对串口部分的代码进行重新修改;
①:添加stdio头文件:因为Printf函数是标准的I/O函数,所以在工程中需要添加头文件 #include "stdio.h"
②:重定义putchar和getchar函数:关于Printf函数底层调用的putchar和getchar函数属于C语言基础知识,这里不再赘述;重定义的示例代码如下所示:
/**
* @brief Retargets the C library printf function to the UART.
* @param[in] c Character to send
* @retval char Character sent
* @par Required preconditions:
* - None
*/
char putchar(char c)
{
/* Write a character to the UART */
UART_write(0,c);
return (c);
}
/**
* @brief Retargets the C library scanf function to the UART.
* @param[in] None
* @retval char Character to Read
* @par Required preconditions:
* - None
*/
char getchar (void)
{
int c = 0;
c = UART_read(0);
return (c);
}
③:UART_write(0,c);和UART_read(0);直接使用CodeGen8 代码生成器生成的代码,这样可以增加代码的可移植性;因为这里用到的是串口0,所以串口读取和写入函数中关于串口编号的参数固定为0;read/write的示例代码如下:
//串口读取函数
unsigned char UART_read(unsigned char ch)
{
unsigned char dat;
if (ch == (unsigned char)0) { // UART0
while(!(USI0ST1 & 0x20)); // wait
dat = USI0DR; // read
}
return dat;
}
//串口写入函数
void UART_write(unsigned char ch, unsigned char dat)
{
if (ch == (unsigned char)0) { // UART0
while(!(USI0ST1 & 0x80)); // wait
USI0DR = dat; // write
}
}
这样修改后的工程就可以方便的调用Printf函数进行MCU的调试了。
④:在主函数的循环体中增加函数:printf("%c",getchar());可以实现串口数据的透传功能;
3、编译该工程并下载程序到MCU。
三、实验现象(具体内容可以参考工程中的Readme.txt文件)
1、循环体中增加printf("%c",getchar());可以实现串口数据的透传功能,即PC发送数据到MCU,MCU会返回相同的数据到PC端。
2、具体的代码可以访问链接:https://share.weiyun.com/5Ivphmm;进行免费下载
因为小编自己能力水平有限,文中难免有错误或表达失误的信息,还望广大阅读者留言批评指正,谢谢。