机器人与人工智能爱好者论坛

标题: 物联网协议MQTT Arduino代码例子 [打印本页]

作者: irobot    时间: 2015-12-7 22:23
标题: 物联网协议MQTT Arduino代码例子
物联网协议MQTT Arduino代码例子

时间:2015-12-06 20:08

  MQTT Arduino        开始之前

        需要的东西有:

        假设我们已经满足了上面的条件。

        Arduino Pubsubclient 示例

        引用官方的示例

  1. #include <SPI.h>
  2. #include <Ethernet.h>
  3. #include <PubSubClient.h>

  4. byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
  5. byte server[] = { 192, 168, 168, 78 }; // MQTT服务地址
  6. byte ip[]     = { 192, 168, 168, 250 }; // 设备IP

  7. void callback(char* topic, byte* payload, unsigned int length) {
  8.   // handle message arrived
  9. }

  10. EthernetClient ethClient;
  11. PubSubClient client(server, 1883, callback, ethClient);

  12. void setup()
  13. {
  14.   Ethernet.begin(mac, ip);
  15.   if (client.connect("arduinoClient")) {
  16.     client.publish("outTopic","hello world");
  17.     client.subscribe("inTopic");
  18.   }
  19. }

  20. void loop()
  21. {
  22.   client.loop();
  23. }
复制代码

运行,接着报了各种服务错误。。。

  1. { [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
  2. { [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
复制代码

  打开一看,发现是限定了传进来的格式要是JSON的。


        于是:

  1. client.publish("outTopic","{'hello': 'true'}");
复制代码

  It Works。

        其他

        这里的测试环境是在本地,不知何原因无法使用服务器,是否是因为DNS缓存?









欢迎光临 机器人与人工智能爱好者论坛 (http://www.robot-ai.org/) Powered by Discuz! X3.2