Angelo 发表于 2014-4-9 14:33:19

无线通讯通用库(PlainProtocol 简介 Ver 1.1)

本帖最后由 Angelo 于 2014-11-3 10:15 编辑

做项目的时候,一旦牵涉到通信,就需要建立一套自己的协议,这不仅会花很长时间,而且在协议的解析过程中也很容易出现各种各样的问题。如果其他人需要使用这个协议,必须用很长的时间来看懂协议。这个过程也会非常痛苦。
为什么这种协议不能变得简单而易于使用呢?通过借鉴JavaScript Object Notation(JSON),我们完成这个基于明文协议的Arduino库。
它使用起来非常方便,继承了Arduino的函数调用习惯,更加方便,易懂。
并且可以在基于串口的任何一种通信设备上使用,比如Zigbee,Wi-Fi, 蓝牙等等。

下载PlainProtocol库

如何安装Arduino库

发送端的样例代码:
#include <PlainProtocol.h>

PlainProtocol mytest(Serial);

void setup() {
mytest.begin(57600);
}

void loop() {
mytest.write("speed",100);          //set the speed to 100
mytest.write("destination", 23, 56); //set the destination to (23,56)
mytest.write("display","Hello World!",10,35);//show the string on display at (10,35)
delay(2000);
}
上传完这个代码以后,你就可以打开Arduino的串口监视器中看到如下的字符串,这个字符串就是编码过之后的数据。
<speed>100;

<destination>23,56;

<displayHello World!>10,35;


接收端的样例代码:


这是一个接收端的DEMO,你可以打开串口监视器,发送以下几条数据。然后就可以看到,PlainProtocol正确解析了发送出来的数据并且打印了出来。


<speed>100;

<destination>23,56;

<displayHello World!>10,35;



#include <PlainProtocol.h>

PlainProtocol mytest(Serial);

int motorSpeed;
int motorDestination;

String displayString="";
int displayPosition;

void setup() {
mytest.begin(57600);
}
/*
This is the receiving demo code for plainprotocol.

You can send the following frame in Serial monitor to test whether the PlainProtocol can phrase the frame correctly:

<speed>100;
<destination>23,56;
<displayHello World!>10,35;

*/

void loop() {

if (mytest.available()) {
    if (mytest.equals("speed")) {    //send "<speed>100;" in Serial monitor
      //the "speed" process
      motorSpeed=mytest.read();

      Serial.print("speed:");
      Serial.println(motorSpeed);
    }
    else if (mytest.equals("destination")){   //send "<destination>23,56;" in Serial monitor
      //the "destination" process
      motorDestination=mytest.read();
      motorDestination=mytest.read();

      Serial.println("destination:");
      Serial.print(" X:");
      Serial.print(motorDestination);
      Serial.print(" Y:");
      Serial.println(motorDestination);

    }
    else if (mytest.equals("display")){    //send "<displayHello World!>10,35;" in Serial monitor
      //the "destination" process
      displayString=mytest.readString();
      displayPosition=mytest.read();
      displayPosition=mytest.read();

      Serial.println("display:");
      Serial.print("displayString:");
      Serial.println(displayString);
      Serial.print(" X:");
      Serial.print(displayPosition);
      Serial.print(" Y:");
      Serial.println(displayPosition);
    }
    else{
      //no matching command
    }
}
}



英文版参考链接





tutorials

Grey 发表于 2014-4-16 14:39:17

这个太赞了,通信协议实在是太头痛了

齐天大妖孽 发表于 2014-4-16 16:06:41

终于不用自己去解析了,这个确实不错,很容易与高级设备通信。

wanglei830205 发表于 2014-10-5 18:17:05

这个很值得借鉴使用,下载一个先

wanglei830205 发表于 2014-11-2 20:13:58

这个协议目前都是基于串口的,比如现在两个UNO之间通过其它的硬件(如射频硬件)发生无线通讯,如何利用这个协议来进行解析传输的数据呢?
页: [1]
查看完整版本: 无线通讯通用库(PlainProtocol 简介 Ver 1.1)