C51 语言编程:单片机与 PC 串口通信程序
2019-04-15 15:37发布
生成海报
单片机接收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就发送. }}//---------------------------------------------------提问者评价:谢谢了!//---------------------------------------------------评论:深蓝剑 2013-2-3 16:01 你的回答帮我大忙了!skhui08021 2012-8-23 12:55 这位老师答得真好:)POWERPOWERONE 2011-7-18 18:59 好//---------------------------------------------------
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮