使用ESP8266快速开发一个物联网应用

MQTT模板

一个好的模板将极大的提高编程效率

传感器 发送数据

以超声波为例

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <string.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#include <SPI.h> // Only needed for Arduino 1.6.5 and earlier

//Wifi Configuration
#define MQTT_VERSION MQTT_VERSION_3_1_1
const char* WIFI_SSID = "wifi ssid";
const char* WIFI_PASSWORD = "wifi password";
const PROGMEM char* MQTT_PUBLISH_TOPIC = "topic";
const PROGMEM char* MQTT_CLIENT_ID = "client id";
const PROGMEM char* MQTT_SERVER_IP = "IP";
const PROGMEM uint16_t MQTT_SERVER_PORT = port;
const PROGMEM char* MQTT_USER = "user";
const PROGMEM char* MQTT_PASSWORD = "password";

unsigned int HighLen = 0;
unsigned int LowLen  = 0;
unsigned int Len_mm  = 0;

SoftwareSerial us100(D1,D2);//Rx,Tx
WiFiClient wifiClient;
PubSubClient client(wifiClient);

void callback(char* p_topic, byte* p_payload, unsigned int p_length) {

  // concat the payload into a string
  String payload;
  for (uint8_t i = 0; i < p_length; i++) {
    payload.concat((char)p_payload[i]);
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("INFO: Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASSWORD)) {
      Serial.println("INFO: connected");
      // Once connected, publish an announcement...
    } else {
      Serial.print("ERROR: failed, rc=");
      Serial.print(client.state());
      Serial.println("DEBUG: try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void publishData(float dist) {
  // create a JSON object
  // doc : https://github.com/bblanchon/ArduinoJson/wiki/API%20Reference
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  // INFO: the data must be converted into a string; a problem occurs when using floats...
  root["distance"] = (String)dist;
  root.prettyPrintTo(Serial);
  /*
     {
        "temperature": "23.20" ,
        "humidity": "43.70"
     }
  */
  char data[200];
  root.printTo(data, root.measureLength() + 1);
  client.publish(MQTT_PUBLISH_TOPIC, data, true);
}

void setup() {
  // set baudrate as 9600bps.
  us100.begin(9600);
  Serial.begin(9600);
  // init the WiFi connection
  Serial.println();
  Serial.println();
  Serial.print("INFO: Connecting to ");
  WiFi.mode(WIFI_STA);
  Serial.println(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("INFO: WiFi connected");
  Serial.print("INFO: IP address: ");
  Serial.println(WiFi.localIP());

  // init the MQTT connection
  client.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
  client.setCallback(callback);

}

void loop() {
  
  if (!client.connected()) {
    reconnect();
  }
    
  us100.flush();     // clear receive buffer of serial port
  us100.write(0X55); // trig US-100 begin to measure the distance
  delay(500);          //delay 500ms to wait result
  
  if(us100.available() >= 2) {                    //when receive 2 bytes 
    HighLen = us100.read();                   //High byte of distance
    LowLen  = us100.read();                   //Low byte of distance
    Len_mm  = HighLen*256 + LowLen;             //Calculate the distance
    
    Serial.print("Distance is: ");   //output the result to serial monitor
    Serial.print(Len_mm);             //output the result to serial monitor
    Serial.println("mm");  
    publishData((float)Len_mm);
  }

  delay(500);  
  client.loop();
}

仅需通过修改头部配置信息 publishData()函数 与 loop循环即可. esp8266将以JSON的数据格式向Broker发送数据

执行器 接收数据

以继电器为例

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#define MQTT_VERSION MQTT_VERSION_3_1_1

//Wifi Configuration
const char* WIFI_SSID = "wifi ssid";
const char* WIFI_PASSWORD = "wifi password";
const PROGMEM char* MQTT_SUBSCRIBE_TOPIC = "relay";
const PROGMEM char* MQTT_CLIENT_ID = "relay";
const PROGMEM char* MQTT_SERVER_IP = "mqtt server ip";
const PROGMEM uint16_t MQTT_SERVER_PORT = 1883;
const PROGMEM char* MQTT_USER = "mqtt user";
const PROGMEM char* MQTT_PASSWORD = "mqtt password";

//relay

int relay = D0;

WiFiClient wifiClient;
PubSubClient client(wifiClient);

void callback(char* p_topic, byte* p_payload, unsigned int p_length) {

  String payload;
  
  for (uint8_t i = 0; i < p_length; i++) {
    payload.concat((char)p_payload[i]);
  }

  StaticJsonBuffer<200> jsonBuffer;
  // doc : https://github.com/bblanchon/ArduinoJson/wiki/API%20Reference

  JsonObject& mBuffer = jsonBuffer.parseObject(payload);

  const char* state = mBuffer["state"];

  if(state == "on"){
    digitalWrite(relay, HIGH);
  }else if(state == "off"){
    digitalWrite(relay, LOW);
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("INFO: Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASSWORD)) {
      Serial.println("INFO: connected");
      client.subscribe(MQTT_SUBSCRIBE_TOPIC);
    } else {
      Serial.print("ERROR: failed, rc=");
      Serial.print(client.state());
      Serial.println("DEBUG: try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.print("INFO: Connecting to ");
  WiFi.mode(WIFI_STA);
  Serial.println(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("INFO: WiFi connected");
  Serial.print("INFO: IP address: ");
  Serial.println(WiFi.localIP());

  // init the MQTT connection
  client.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
  client.setCallback(callback);

  pinMode(relay, OUTPUT);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

仅修改callback()函数即可 通过mBuffer["键"]取值
上位机数据发送示例

{"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}

注意防转义 两边的双引号

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,743评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,296评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,285评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,485评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,581评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,821评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,960评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,719评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,186评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,516评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,650评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,329评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,936评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,757评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,991评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,370评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,527评论 2 349

推荐阅读更多精彩内容