标题: 51单片机串口通信-握手协议 [打印本页]

作者: 远征之路    时间: 2018-11-19 10:54
标题: 51单片机串口通信-握手协议
  1. #include "reg52.h"
  2. #define uchar unsigned char
  3. #define uint unsigned int
  4. uchar code askconfig[]= {0xcc,0x99,0x01,0x02,0x03,0xdd};
  5. uchar code Ackconfig[]= {0xaa,0x66,0x99,0x16,0x91,0x12,0xd8,0x56,0xbb};
  6. uchar chuli[29];
  7. void System_Init()
  8. {                    
  9.     TMOD = 0x20;
  10.     SCON = 0x50;
  11.     TH1 = 0xfc;
  12.     TL1 = 0xfc;
  13.     PCON = 0x00;
  14.     TR1 = 1;
  15. }

  16. void Delay (uint Milliseconds)//延时
  17. {
  18.     uchar a,b;
  19.         for(a=3;a>0;a--)
  20.         {
  21.         for(b=245;b>0;b--)
  22.     for (; Milliseconds > 0; Milliseconds--);
  23.         }
  24. }

  25. void SendChar (uchar chr)//发送一个字符
  26. {
  27.                    SBUF = chr;
  28.                 while(!TI);
  29.           TI=0;                                                
  30. }

  31. char Handshake (void)
  32. {
  33.              uchar i,j,k;
  34.                    Delay(50000);
  35.                   Delay(50000);
  36.                 for(i=0;i<6;i++)
  37.                         {
  38.                         SendChar(askconfig[ i]);[ i]
  39.                         }
  40.                         while(RI)
  41.                         {
  42.                                 chuli[j]=SBUF;
  43.                                 RI=0;
  44.                                 j++;
  45.                         
  46.                                 if(j==9)
  47.                                 {
  48.                                 for(k=0;k<10;k++)
  49.                                           {
  50.                                         if(chuli[k]!=Ackconfig[k])
  51.                                              break;
  52.                                         }
  53.                                 if(k!=10)
  54.                                           return 0;
  55.                                 else
  56.                                           return -1;         
  57.                                 }
  58.                     }
  59. }


  60. void main()
  61. {
  62.    
  63.    System_Init();
  64.    Delay(200);
  65.    while(1)
  66.      {
  67.                if(Handshake ())
  68.                  {
  69.                   Delay(2000);
  70.                   Delay(2000);
  71.                   SendChar(0xff);
  72.                  }
  73.          }
  74. }
复制代码



作者: renshanwu    时间: 2020-8-15 12:57
41行运行有错误啊
作者: lzj23642008    时间: 2022-6-20 15:24
renshanwu 发表于 2020-8-15 12:57
41行运行有错误啊

41可能运行不了




欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1