Blog

Blog

PHODAL

物联网协议MQTT Arduino示例

在试着给http://mqtt.phodal.com/做一个简单的Arduino示例,找到了这个库https://github.com/knolleary/pubsubclient,果断试了试。

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缓存?

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签