机器人与人工智能爱好者论坛
标题: 物联网协议MQTT Arduino代码例子 [打印本页]
作者: irobot 时间: 2015-12-7 22:23
标题: 物联网协议MQTT Arduino代码例子
物联网协议MQTT Arduino代码例子
时间:2015-12-06 20:08
MQTT Arduino 开始之前 需要的东西有:
- Arduino
- Arduino Ethernet
- MQTT服务
假设我们已经满足了上面的条件。
Arduino Pubsubclient 示例 引用官方的示例
- #include <SPI.h>
- #include <Ethernet.h>
- #include <PubSubClient.h>
- byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
- byte server[] = { 192, 168, 168, 78 }; // MQTT服务地址
- byte ip[] = { 192, 168, 168, 250 }; // 设备IP
- void callback(char* topic, byte* payload, unsigned int length) {
- // handle message arrived
- }
- EthernetClient ethClient;
- PubSubClient client(server, 1883, callback, ethClient);
- void setup()
- {
- Ethernet.begin(mac, ip);
- if (client.connect("arduinoClient")) {
- client.publish("outTopic","hello world");
- client.subscribe("inTopic");
- }
- }
- void loop()
- {
- client.loop();
- }
复制代码运行,接着报了各种服务错误。。。
- { [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
- { [Error: read ECONNRESET] code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
复制代码 打开一看,发现是限定了传进来的格式要是JSON的。
于是:
- client.publish("outTopic","{'hello': 'true'}");
复制代码 It Works。
其他
这里的测试环境是在本地,不知何原因无法使用服务器,是否是因为DNS缓存?
欢迎光临 机器人与人工智能爱好者论坛 (http://robot-ai.org/) |
Powered by Discuz! X3.2 |