ESP32 使用MQTT协议上传数据

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个周期才能收到自己发布的消息。很奇怪。


  • 2
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值