C51語(yǔ)言編程:單片機(jī)與 PC 串口通信程序
單片機(jī)接收PC機(jī)發(fā)來(lái)的指令信號(hào),然后單片機(jī)又向PC機(jī)發(fā)送字符串。具體要求如下:
當(dāng)接收指令信號(hào)為:'go',單片機(jī)向PC機(jī)發(fā)送字符串:WELCOME TO CHINA!;
當(dāng)接收指令信號(hào)為:'who',單片機(jī)向PC機(jī)發(fā)送字符串:MY NAME IS LIMING;
當(dāng)接收指令信號(hào)為:'home',單片機(jī)向PC機(jī)發(fā)送字符串:YINGYONGKEXUEXUEYUAN。
PC機(jī)上的串口調(diào)試軟件,會(huì)在窗口顯示出單片機(jī)送回來(lái)相應(yīng)字符串;
如果接送的字符串不正確,單片機(jī)不響應(yīng)。
采用C語(yǔ)言。
題目鏈接:http://zhidao.baidu.com/question/282477940.html
//---------------------------------------------------------
做而論道回答如下:
看看下面的。
//---------------------------------------------------------
#include
#include
#define uchar unsigned char
#define uint unsigned int
//---------------------------------------------------
uchar idata trdata1[] = {
'W','E','L','C','O','M','E',' ','T','O',' ','C','H','I','N','A','!',0x0d,0x0a,0x00};
uchar idata trdata2[] = {
'M','Y',' ','N','A','M','E',' ','I','S',' ','L','I','M','I','N','G',0x0d,0x0a,0x00};
uchar idata trdata3[] = {
'Y','I','N','G','Y','O','N','G','K','E','X','U','E','X','U','E','Y','U','A','N',0x0d,0x0a,0x00};
uchar RxBuf[5], Rx_p, Rx_i, TX_p, Tx_i;
//---------------------------------------------------
void UART_Init(void) //串口初始化
{
PCON = 0x00;
SCON = 0x50; //串口工作方式為1,允許接收.
TMOD = 0x20; // T1 定時(shí)方式2
TH1 = 0xfd; //波特率 9600bps @ fosc = 11.0592MHz
TL1 = 0xfd;
TR1 = 1; //啟動(dòng)T1
ES = 1; //開(kāi)串口中斷.
EA = 1; //開(kāi)總中斷.
}
//---------------------------------------------------
void main()
{
UART_Init();
Rx_p = 0;
Rx_p = 2;
while(1) {
if (Rx_p != 0) {
TX_p = Rx_p;//字符串1 2 3
Tx_i = 0; //字符指針.
Rx_p = 0; //清零.
Rx_i = 0;
TI = 1; //啟動(dòng)發(fā)送中斷.
} }
}
//---------------------------------------------------
void Uart_INT(void) interrupt 4 //串口中斷函數(shù)
{
uchar Tcv = 0;
if(RI) { //接收?.
RI = 0; //標(biāo)志位清零.
RxBuf[Rx_i] = SBUF;
if((RxBuf[Rx_i - 1] == 'g') && (RxBuf[Rx_i] == 'o')) Rx_p = 1;
if((RxBuf[Rx_i - 2] == 'w') && (RxBuf[Rx_i - 1] == 'h') && (RxBuf[Rx_i] == 'o')) Rx_p = 2;
if((RxBuf[Rx_i - 3] == 'h') && (RxBuf[Rx_i - 2] == 'o') && (RxBuf[Rx_i - 1] == 'm') && (RxBuf[Rx_i] == 'e')) Rx_p = 3;
P1 = Rx_p; //在P1顯示收到的信息.
Rx_i++;
Rx_i %= 5;
}
else {
TI = 0;
if (TX_p == 1) Tcv = trdata1[Tx_i]; //取來(lái)待發(fā)字符.
if (TX_p == 2) Tcv = trdata2[Tx_i];
if (TX_p == 3) Tcv = trdata3[Tx_i];
if (Tcv != 0) {SBUF = Tcv; Tx_i++;} //不是0就發(fā)送.
}
}
編輯:admin 最后修改時(shí)間:2018-05-18