uart8051.h:
#ifndef __UART_H__
#define __UART_H__
#define XTAL 12000000
#define baudrate 9600
char UART_putchar(char ch);
char UART_getkey(void);
void InitCom(void);
#endif
uart8051.c:
#include <reg51.h>
#include "uart8051.h"
char UART_putchar(char ch)
{
if(ch=='\n')
{
SBUF = 0x0d;
while(TI == 0);
TI=0;
SBUF = 0x0a;
}
else
SBUF = ch;
while(TI == 0);
TI = 0;
return ch;
}
char UART_getkey(void)
{
char c;
while(!RI);
c = SBUF;
RI = 0;
return(c);
}
void InitCom(void)
{
SCON=0X50;
TMOD=0X20;
PCON=0X80;
TH1=0XF3;
TL1=0XF3;
ES=0;
EA=1;
TR1=1;
}
main.c:
#include <reg51.h>
#include <stdio.h>
#include "uart8051.h"
char putchar(char ch)
{
return UART_putchar(ch);
}
char _getkey(void)
{
return UART_getkey();
}
void main(void)
{
unsigned int tem;
InitCom();
printf("´®¿Ú²âÊÔ£¬³£¹æʹÓÃ:\n");
UART_putchar('A');UART_putchar(' ');
UART_putchar('B');UART_putchar(' ');
UART_putchar('C');UART_putchar(' ');
UART_putchar('D');UART_putchar(' ');
UART_putchar('\n');
printf("Ç¿´óµÄ¸ñʽ»¯Á÷Êä³ö£º\n");
printf("Êä³öÒ»¸öÕûÐΣº%d\n",(int)6886);
printf("Êä³öÒ»¸öʵÐÍ£º%d\n",(float)68.86);
while(1)
{
printf("\nÊäÈëÒ»¸öÕûÐÍ£¬ËÍP2¿Ú×¢Òâ¹Û²ìP2¿ÚµÄµÆ:\n");
scanf("%d",&tem);
P2=tem;
}
}
编译之后,打开烧录软件烧录,然后打开串口通信助手进行调试:
如上图,分别输入1+空格,2+空格,3+空格,效果图如下:
1+空格:
2+空格:
3+空格: