×
单片机 > 单片机程序设计 > 详情

51单片机与PC通信要注意的地方

发布时间:2020-08-25 发布时间:
|
做了两天终于把232通信做通了,写下总结。

第一、波特率要设置相同。

第二、要在PC机上的设备管理器里把USB转232串口设置为COM2,并且波特率要设置的和软件里写的一样。

如下是写的测试程序,精简了通信部分。

51单片机上的通信程序

#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机上通信程序(用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(" %c ",b);
for(i = 0;i<2000;i++);
}
}
}
}

 

补充:如果用vc些outportb、inputb可以用_inp、_outp。可以阅览msdn



『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
ARM 汇编的必知必会