C51語言編程:單片機與 PC 串口通信程序
單片機接收PC機發(fā)來的指令信號,然后單片機又向PC機發(fā)送字符串。具體要求如下:
當接收指令信號為:'go',單片機向PC機發(fā)送字符串:WELCOME TO CHINA!;
當接收指令信號為:'who',單片機向PC機發(fā)送字符串:MY NAME IS LIMING;
當接收指令信號為:'home',單片機向PC機發(fā)送字符串:YINGYONGKEXUEXUEYUAN。
PC機上的串口調(diào)試軟件,會在窗口顯示出單片機送回來相應字符串;
如果接送的字符串不正確,單片機不響應。
采用C語言。
題目鏈接: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 定時方式2
TH1 = 0xfd; //波特率 9600bps @ fosc = 11.0592MHz
TL1 = 0xfd;
TR1 = 1; //啟動T1
ES = 1; //開串口中斷.
EA = 1; //開總中斷.
}
//---------------------------------------------------
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; //啟動發(fā)送中斷.
} }
}
//---------------------------------------------------
void Uart_INT(void) interrupt 4 //串口中斷函數(shù)
{
uchar Tcv = 0;
if(RI) { //接收?.
RI = 0; //標志位清零.
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]; //取來待發(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 最后修改時間:2018-05-18