| 
 
| 大侠好,小弟在写51串口通信下位机程序的时候碰到了写麻烦。我在用串口工具像下位机发送单字节的时候没有问题,数据能正常接收并返回给上位机。但是在字符串发送的时候就老有问题。我的思路是这样的:上位机发送字符串的时候下位机对第一个字节进行判断,并点亮P0口上的二极管。然后返回接收到的字符给上位机,以此判断下位机的程序问题。但是现在总是不对,希望各位路过的大侠能指点一二,万分感谢!!!下面上下位机c程序源码。 #include <reg51.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 //数据接收缓冲区
 unsigned char strRecvBuf[32]="\0";
 //指向缓冲区的指针
 unsigned char *pRecvBuf=strRecvBuf;
 //接收数据标记. 0=未完成,1=接收完成
 unsigned char nIsRecvOver=0;
 int main(void)
 {
 void InitSeralPort(void);
 int SendData(void);
 int GetX(void);
 int GetY(void);
 int nX=0, nY=0;
 InitSeralPort();
 P0=0xFF;
 
 //主循环
 while(1)
 {
 if(1 == nIsRecvOver)
 {
 nX=GetX();
 nY=GetY();
 SendData();
 switch(nX)
 {
 case 0:
 P0=0x00;
 break;
 case 1:
 P0=0xfe;
 break;
 case 2:
 P0=0xfd;
 break;
 case 3:
 P0=0xfb;
 break;
 case 4:
 P0=0xf7;
 break;
 case 5:
 P0=0xef;
 break;
 case 6:
 P0=0xdf;
 break;
 case 7:
 P0=0xbf;
 break;
 case 8:
 P0=0x7f;
 break;
 case 9:
 P0=0xff;
 break;
 default:
 P0=0xff;
 break;
 }//End switch
 nIsRecvOver=0;
 }//End if
 }//End whlie
 }
 
 //串口中断服务子程序
 void UART_SER(void) interrupt 4
 {
 if(1 == RI)
 {//当产生数据接收中断时
 RI=0;
 
 *pRecvBuf=SBUF;
 if('|' == *pRecvBuf)
 {
 nIsRecvOver=1;
 
 //数据接收完成后重置pRecvBuf指针
 pRecvBuf=strRecvBuf;
 }//End if
 pRecvBuf++;
 }//End if
 
 if(1 == TI)
 {//当产生数据发送中断时
 TI=0;
 }//End if
 }
 
 void InitSeralPort(void)
 {
 PCON=0x00; /*SMOD=0,波特率不翻倍*/
 SCON=0x50;
 TMOD=0x20;
 TH1=0xfd;
 TL1=0xfd;
 TR1=1;
 ES=1;
 EA=1;
 }
 
 int GetX(void)
 {
 unsigned char strX[5]="\0";
 int n=0;
 
 while(*pRecvBuf != ':')
 {
 strX[n++] = *pRecvBuf++;
 }//End while
 
 return atoi(strX);
 }
 
 int GetY(void)
 {
 unsigned char strY[5]="\0";
 int n=0;
 
 while(*pRecvBuf != '|')
 {
 strY[n++] = *pRecvBuf++;
 }//End while
 
 return atoi(strY);
 }
 
 void SendByte(unsigned char cByte)
 {
 SBUF=cByte;
 while(TI == 0)
 ;
 TI=0;
 }
 
 int SendData(void)
 {
 pRecvBuf=strRecvBuf;
 while(*pRecvBuf != '|')
 {
 SendByte(*pRecvBuf++);
 }
 
 return 0;
 }
 | 
 |