无标题文章

https://github.com/knolleary/pubsubclient

https://www.jianshu.com/p/590f249ecd05

https://github.com/plapointe6/EspMQTTClient

https://github.com/Imroy/pubsubclient

esp32是乐鑫物联网芯片,带wifi。

使用arduino进行编程。MQTT的服务器代码用NODEJS完成。mqserver.js

arduino的代码如下:

/*

Basic ESP8266 MQTT example

This sketch demonstrates the capabilities of the pubsub library in combination

with the ESP8266 board/library.

It connects to an MQTT server then:

  - publishes "hello world" to the topic "outTopic" every two seconds

  - subscribes to the topic "inTopic", printing out any messages

    it receives. NB - it assumes the received payloads are strings not binary

  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,

    else switch it off

It will reconnect to the server if the connection is lost using a blocking

reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to

achieve the same result without blocking the main loop.

To install the ESP8266 board, (using Arduino 1.6.4+):

  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":

      http://arduino.esp8266.com/stable/package_esp8266com_index.json

  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"

  - Select your ESP8266 in "Tools -> Board"

*/

#include <WiFi.h>

#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "xxx";

const char* password = "xx123456";

const char* mqtt_server = "xx.xx.xx.xx";

WiFiClient espClient;

PubSubClient client(espClient);

long lastMsg = 0;

char msg[50];

int value = 0;

int dhtpin=12;

int ledpin=11;

int temp;//温度

int humi;//湿度

void setup() {

  pinMode(ledpin,OUTPUT);

  Serial.begin(115200);

  setup_wifi();

  client.setServer(mqtt_server, 1883);

  client.setCallback(callback);

}

void setup_wifi() {    //连接wifi

  delay(10);

  // We start by connecting to a WiFi network

  Serial.println();

  Serial.print("Connecting to ");

  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }

  Serial.println("");

  Serial.println("WiFi connected");

  Serial.println("IP address: ");

  Serial.println(WiFi.localIP());

}

void callback(char* topic, byte* payload, unsigned int length) {    //回调函数

  Serial.print("Message arrived [");

  Serial.print(topic);

  Serial.print("] ");

  for (int i = 0; i < length; i++) {

    Serial.print((char)payload[i]);

  }

  Serial.println();

  // Switch on the LED if an 1 was received as first character

  if (length>2){

    if ((char)payload[length-2] == '1') {

      digitalWrite(ledpin, LOW);  // Turn the LED on (Note that LOW is the voltage level

      // but actually the LED is on; this is because

      // it is acive low on the ESP-01)

    } else {

      digitalWrite(ledpin, HIGH);  // Turn the LED off by making the voltage HIGH

    }

  }

}

void reconnect() {        //每次发布mqtt信息时,需检查连接

  // Loop until we're reconnected

  while (!client.connected()) {

    Serial.print("Attempting MQTT connection...");

    // Attempt to connect

    if (client.connect("ID_ESP32Client")) {

      Serial.println("connected");

      // Once connected, publish an announcement...

      client.publish("hmdata", "{\"datetime\":\"2018-7-1 19:30\",\"temp\":25,\"humi\":100}");  //发布json格式

      // ... and resubscribe

      client.subscribe("hmdata");        //订阅

    } else {

      Serial.print("failed, rc=");

      Serial.print(client.state());

      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying

      delay(5000);

    }

  }

}

void loop() {

  if (!client.connected()) {

    reconnect();

  }

  client.loop();    //检查调用回调函数

  long now = millis();

  if (now - lastMsg > 2000) {

    lastMsg = now;

    ++value;

    wenshidu();  //读取温度

    temp=temp+random(1,5);

    humi=humi+random(1,10);

    snprintf (msg, 75, "{\"datetime\":\"2018-7-2 20:30\",\"temp\":%ld,\"humi\":%ld}", temp,humi);

    Serial.print("Publish message: ");

    Serial.println(msg);

    client.publish("hmdata", msg);

  }

}

void wenshidu()  //获取温湿度。

{

int pin=12;

int tol;//校对码

int j;

unsigned int loopCnt;

int chr[40] = {0};//创建数字数组,用来存放40个bit

unsigned long time1;

  bgn:

  delay(2000);

//设置2号接口模式为:输出

//输出低电平20ms(>18ms)

//输出高电平40μs

  pinMode(pin,OUTPUT);

  digitalWrite(pin,LOW);

  delay(20);

  digitalWrite(pin,HIGH);

  delayMicroseconds(40);

  digitalWrite(pin,LOW);

//设置2号接口模式:输入

  pinMode(pin,INPUT);

  //高电平响应信号

  loopCnt=10000;

  while(digitalRead(pin) != HIGH)

  {

    if(loopCnt-- == 0)

    {

//如果长时间不返回高电平,输出个提示,重头开始。

      Serial.println("HIGH");

      goto bgn;

    }

  }

  //低电平响应信号

  loopCnt=30000;

  while(digitalRead(pin) != LOW)

  {

    if(loopCnt-- == 0)

    {

//如果长时间不返回低电平,输出个提示,重头开始。

      Serial.println("LOW");

      goto bgn;

    }

  }

//开始读取bit1-40的数值 

    for(int i=0;i<40;i++)

  {

    while(digitalRead(pin) == LOW)

    {}

//当出现高电平时,记下时间“time”

    time1 = micros();

    while(digitalRead(pin) == HIGH)

    {}

//当出现低电平,记下时间,再减去刚才储存的time

//得出的值若大于50μs,则为‘1’,否则为‘0’

//并储存到数组里去

    if (micros() - time1  >50)

    {

      chr[i]=1;

    }else{

      chr[i]=0;

    }

  }


//湿度,8位的bit,转换为数值

humi=chr[0]*128+chr[1]*64+chr[2]*32+chr[3]*16+chr[4]*8+chr[5]*4+chr[6]*2+chr[7];


//温度,8位的bit,转换为数值

temp=chr[16]*128+chr[17]*64+chr[18]*32+chr[19]*16+chr[20]*8+chr[21]*4+chr[22]*2+chr[23];

  //校对码,8位的bit,转换为数值

//tol=chr[32]*128+chr[33]*64+chr[34]*32+chr[35]*16+chr[36]*8+chr[37]*4+chr[38]*2+chr[39];

//输出:温度、湿度、校对码

  Serial.print("temp:");

  Serial.println(temp);

  Serial.print("humi:");

  Serial.println(humi);


}

需要说明的是:

ESP32的电压是3.3v,导致带DHT11传感器时,用dht11库会出现校验错误。因此,采用自写代码形式,完成温湿度采集。还没有仔细分析二者代码有什么不同。

实际使用时,发现一个问题:发布的消息和收到的消息会不同步,发布消息后,要3个周期才能收到自己发布的消息。很奇怪。

---------------------

作者:wengduke

来源:CSDN

原文:https://blog.csdn.net/wengduke/article/details/80889364

版权声明:本文为博主原创文章,转载请附上博文链接!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • JAVA面试题 1、作用域public,private,protected,以及不写时的区别答:区别如下:作用域 ...
    JA尐白阅读 1,191评论 1 0
  • # 一度蜜v3.0协议 --- # 交互协议 [TOC] ## 协议说明 ### 请求参数 下表列出了v3.0版协...
    c5e350bc5b40阅读 679评论 0 0
  • ```java /* * Copyright (C) 2006 The Android Open Source P...
    mrganer阅读 1,167评论 0 50
  • title: Optical Character Recognition (OCR)author: Marina ...
    4a87cc38dcbc阅读 387评论 0 0
  • 第94个冬天 最后一片枯叶落了 它落下的时候 没有谁为之伤心 曾在它底下乘凉的人 面无表情 那是怎样的铁石心肠啊 ...
    开心点金石阅读 1,599评论 49 69