物联网协议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();
}运行,接着报了各种服务错误。。。{ code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
{ code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }打开一看,发现是限定了传进来的格式要是JSON的。
于是:client.publish("outTopic","{'hello': 'true'}");It Works。 其他
这里的测试环境是在本地,不知何原因无法使用服务器,是否是因为DNS缓存?
页:
[1]