C51语言编程:单片机与 PC 串口通信程序
单片机接收PC机发来的指令信号,然后单片机又向PC机发送字符串。具体要求如下:
当接收指令信号为:'go',单片机向PC机发送字符串:WELCOME TO CHINA!;
当接收指令信号为:'who',单片机向PC机发送字符串:MY NAME IS LIMING;
当接收指令信号为:'home',单片机向PC机发送字符串:YINGYONGKEXUEXUEYUAN。
PC机上的串口调试软件,会在窗口显示出单片机送回来相应字符串;
如果接送的字符串不正确,单片机不响应。
采用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; //启动发送中断.
} }
}
//---------------------------------------------------
void Uart_INT(void) interrupt 4 //串口中断函数
{
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]; //取来待发字符.
if (TX_p == 2) Tcv = trdata2[Tx_i];
if (TX_p == 3) Tcv = trdata3[Tx_i];
if (Tcv != 0) {SBUF = Tcv; Tx_i++;} //不是0就发送.
}
}
编辑:admin 最后修改时间:2018-05-18