51單片機(jī)與PC通信要注意的地方
第一、波特率要設(shè)置相同。
本文引用地址:http://m.butianyuan.cn/article/201611/318594.htm第二、要在PC機(jī)上的設(shè)備管理器里把USB轉(zhuǎn)232串口設(shè)置為COM2,并且波特率要設(shè)置的和軟件里寫的一樣。
如下是寫的測試程序,精簡了通信部分。
51單片機(jī)上的通信程序
#include
#define uchar unsigned char
#define uint unsigned int
uchar code cgf1[10] = {"CHINA"};
uchar code cgf2[10] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
main()
{
uchar i,j;
TMOD = 0x20;
TH1 = 0x0e6;TL1 = 0x0e6;
TR1 = 1;
SCON = 0x50;
P1 = 0x3f;
lcd_reset();
while(1)
{
RI = 0;
while(!RI);
i = SBUF;
i = i&0x0f;
lcd_display(0,0,15,13);
delay(3000);
//P1 = cgf2[i];
RI = 0;
for(j = 0;j<200;j++);
TI = 0;
SBUF =cgf1[i];
while(!TI);
TI = 0;
}
}
PC機(jī)上通信程序(用Turboc2.0編譯就行)
#include
#include
#include
#include
#include
void port(void)
{
outportb(0x2fb,0x80);
outportb(0x2f8,0x60);
outportb(0x2f9,0);
outportb(0x2fb,0x03);
}
void send(unsigned char s)
{
unsigned char x;
outportb(0x2f8,s);
begin:
x = inportb(0x2fd);
x = x&0x20;
if(x == 0)goto begin;
}
unsigned char data()
{
unsigned char a;
bgin:
a = inportb(0x2fd);
a = a&0x01;
if(a != 1)goto bgin;
else
{
a = inportb(0x2f8);
return(a);
}
}
void main(void)
{
int i;
unsigned char c,b;
b = ;
system("cls");
port();
puts("PC USE COM1 1200b/s,press A to exit");
puts("89c51 fosc = 12MHz");
puts("input(0-9)");
while(1)
{
c = getchar();
if(c == 97)
exit(0);
else
{if(c >= 0x30 && c <= 0x39)
{
send(c);
b = data();
puts("STC89c51 send
printf(" %cn",b);
for(i = 0;i<2000;i++);
}
}
}
}
補(bǔ)充:如果用vc些outportb、inputb可以用_inp、_outp。可以閱覽msdn
評(píng)論