|
我想寫個(gè)程序完成從PC發(fā)0-F字符到單片機(jī)。單片機(jī)的2位LED顯示出接受到的數(shù)據(jù)。同時(shí)把接收到的數(shù)據(jù)發(fā)回PC去檢查數(shù)據(jù)的正確性。
下面的程序能接收和發(fā)送數(shù)據(jù)。但是不正確。請(qǐng)懂的朋友指點(diǎn)。謝謝
#include <reg52.h>//單片機(jī)51頭文件,存放著單片機(jī)的寄存器
unsigned char dat; //用于存儲(chǔ)單片機(jī)接收發(fā)送緩沖寄存器SBUF里面的內(nèi)容
sbit gewei=P1^0; //個(gè)位選通定義
sbit shiwei=P1^1; //十位選通定義
sbit alarm=P3^6; //聲音報(bào)警 alarm=0不發(fā)出聲音,alarm=1; 發(fā)聲音報(bào)警
unsigned char code table[]={ 0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71}; //定義0到F 16個(gè)數(shù)碼管顯示代碼;
void Delay(unsigned int tc) //延時(shí)程序
{
while( tc != 0 )
{unsigned int i;
for(i=0; i<100; i++);
tc--;}
}
void LED() //LED顯示接收到的數(shù)據(jù)
{
shiwei=0;
P2= table[dat/16];
Delay(8);
shiwei=1;
gewei=0;
P2= table[dat%16];
Delay(5);
gewei=1;
}
void Init_Com(void)//功能:串口初始化,波特率9600,方式1
{
TMOD = 0x20;
PCON = 0x00;
SCON = 0x50;
TH1 = 0xFd;
TL1 = 0xFd;
TR1 = 1;
}
void main()//主程序功能:實(shí)現(xiàn)接收數(shù)據(jù)并把接收到的數(shù)據(jù)原樣發(fā)送回去///////
{
Init_Com();//串口初始化
P1=0;
alarm=0;
while(1)
{
if ( RI ) //掃描判斷是否接收到數(shù)據(jù),
{
dat = SBUF-0x30; //接收數(shù)據(jù)SBUF賦與dat
RI=0; //RI清零。
SBUF = dat; //在原樣把數(shù)據(jù)發(fā)送回去
}
LED(); //顯示接收到的數(shù)據(jù)
}
}
|
|