標(biāo)題: 單片機(jī)多機(jī)通訊從機(jī)程序 [打印本頁]

作者: 12366666    時(shí)間: 2017-6-6 19:32
標(biāo)題: 單片機(jī)多機(jī)通訊從機(jī)程序
從機(jī)程序:http://www.torrancerestoration.com/bbs/dpj-87068-1.html
主機(jī)程序:http://www.torrancerestoration.com/bbs/dpj-87067-1.html

  1. #include<reg51.h>
  2. #include<string.h>
  3. #define addr     0x01//從機(jī)1的地址
  4. #define _SUCC_   0x0f//數(shù)據(jù)傳送成功
  5. #define _ERR_    0xf0//數(shù)據(jù)傳送失敗
  6. unsigned char aa=0xff;//主機(jī)與從機(jī)之間通信標(biāo)志
  7. unsigned char Buff[20];//數(shù)據(jù)緩沖區(qū)
  8. //串口初始化函數(shù)
  9. void serial_init()
  10. {
  11. TMOD=0x20; //定時(shí)器1工作于方式2
  12. TH1=0xfd;  
  13. TL1=0xfd; //波特率為9600
  14. PCON=0;
  15. SCON=0xd0;  //串口工作于方式3
  16. TR1=1;  //開啟定時(shí)器
  17. TI=0;
  18. RI=0;
  19. }
  20. //接收數(shù)據(jù)函數(shù)
  21. unsigned char RECE_data(unsigned char *Buff)
  22. {
  23. unsigned char i,temp;
  24. unsigned char lenth;
  25. unsigned char check;
  26. RI=0;     //接收數(shù)據(jù)長度
  27. while(!RI);
  28. if(RB8==1)    //若接收到地址幀,則返回0xfe
  29.   return 0xfe;
  30. lenth=SBUF;
  31. RI=0;     

  32. check=lenth;
  33. for(i=0;i<lenth;i++) //接收數(shù)據(jù)
  34. {
  35.   while(!RI);
  36.   if(RB8==1)   //若接收到地址幀,則返回0xfe
  37.    return 0xfe;
  38.   Buff[i]=SBUF;   
  39.   check=check^(Buff[i]);
  40.   RI=0;
  41. }
  42. while(!RI);    //接收校驗(yàn)字節(jié)
  43. if(RB8==1)    //若接收到地址幀,則返回0xfe
  44.   return 0xfe;
  45. temp=SBUF;
  46. RI=0;

  47. check=temp^check;  //將從主機(jī)接收到的校驗(yàn)碼與自己計(jì)算的校驗(yàn)碼比對
  48. if(check!=0)   //校驗(yàn)碼不一致,表明數(shù)據(jù)接收錯(cuò)誤,向主機(jī)發(fā)送錯(cuò)誤信號,函數(shù)返回0xff
  49. {
  50.   TI=0;
  51.   TB8=0;
  52.   SBUF=_ERR_;
  53.   while(!TI);
  54.   TI=0;
  55.   return 0xff;
  56. }
  57. TI=0;           //校驗(yàn)碼一致,表明數(shù)據(jù)接收正確,向主機(jī)發(fā)送成功信號,函數(shù)返回0x00
  58. TB8=0;
  59. SBUF=_SUCC_;
  60. while(!TI);
  61. TI=0;
  62. return 0;
  63. }
  64. void main()
  65. {
  66. serial_init();
  67. while(1)
  68. {
  69.   SM2=1;              //接收地址幀
  70.   while(aa!=addr)  //從機(jī)等待主機(jī)請求自己的地址
  71.   {
  72.    RI=0;
  73.    while(!RI);
  74.    aa=SBUF;
  75.    RI=0;
  76.   }
  77.   TI=0;     //一旦被請求,從機(jī)返回自己的地址作為應(yīng)答,等待接收數(shù)據(jù)
  78.   TB8=0;
  79.   SBUF=addr;
  80.   while(!TI);
  81.   TI=0;
  82.   SM2=0;                  //接收數(shù)據(jù)幀
  83.   aa=0xff;    //從機(jī)接收數(shù)據(jù),并將數(shù)據(jù)保存到數(shù)據(jù)緩沖區(qū)
  84.   while(aa==0xff)
  85.   {
  86.    aa=RECE_data(Buff);
  87.   }
  88.   if(aa==0xfe)
  89.    continue;
  90.   P1=Buff[1];      //查看接收到的數(shù)據(jù)
  91. }
  92. }

復(fù)制代碼





歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1