Question:以16进制发送一个0-255之间的任一数,当单片机收到后在数码管上动态显示出来,波特率自定。
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit duan =P2^6;
sbit wei =P2^7;
uchar code table[]={
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};
uchar flag;
uchar bai,shi,ge;
uint num;
void init();
void display(uchar bai,char shi,uchar ge);
void delay(uint xms)
{
uint i,j;
for(i=0;i<xms;i++)
for(j=0;j<10;j++);
}
void main()
{
init();
while(1)
{
if(flag==1)
{
ES=0;
flag=0;
bai=num/100;
shi=num%100/10;
ge=num%10;
/*SBUF=bai;
while(!TI);
TI=0;
SBUF=shi;
while(!TI);
TI=0;
SBUF=ge;
while(!TI);
TI=0;*/
ES=1;
}
display(bai,shi,ge);//如果这个函数写在了上一个循环里面显示会出错,只会显示个位数字!!!!
}
}
void display(uchar bai,uchar shi,uchar ge)
{
wei=1;
P0=0xfe;
wei=0;
P0=0xff;
duan=1;
P0=table[bai];
duan=0;
P0=0xff;
delay(2);
wei=1;
P0=0xfd;
wei=0;
P0=0xff;
duan=1;
P0=table[shi];
duan=0;
P0=0xff;
delay(2);
wei=1;
P0=0xfb;
wei=0;
P0=0xff;
duan=1;
P0=table[ge];
duan=0;
P0=0xff;
delay(2);
}
void init()
{
TMOD=0x20;
TH1=0xfd;
TL1=0xfd;
SM0=0;
SM1=1;
TR1=1;
REN=1;
EA=1;
ES=1;
}
void ser() interrupt 4
{
num=SBUF;
flag=1;
RI=0;
}
Question:以9600bps从计算机发送任一字节数据,当单片机收到该数据后,在此数据前加上一序号然后连同此数据一起发送至计算机,当序号超过255时归零。
#include
#define uchar unsigned char
#define uint unsigned int
uchar aa;
uchar num;
uchar flag;
void init();
void main()
{
init();
while(1)
{
if(flag==1)
{
flag=0;
ES=0;
if(num==255)
num=0;
SBUF=num;
while(!TI);
TI=0;
SBUF=aa;
while(!TI);
TI=0;
ES=1;
}
}
}
void init()
{
TMOD=0x20;
TH1=0xfd;
TL1=0xfd;
SM0=0;
SM1=1;
TR1=1;
EA=1;
ES=1;
REN=1;
num=0;
}
void ser() interrupt 4
{
flag=1;
RI=0;
aa=SBUF;
num++;
}