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)) {