如何使用ESP32cam在bme680传感器的mqtt上发布数据

时间:2019-11-24 18:54:49

标签: json wifi mqtt arduino-ide esp32

我正在使用Windows 10,并正在使用esp32cam从BME680获取气体读数。我尝试添加此内容:

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
//#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <Arduino_JSON.h>

//uint64_t mac;  
//uint32_t high;
//uint32_t low;

// Replace the next variables with your SSID/Password combination
const char* ssid = "";
const char* password = "";

// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "";
const char* mqtt_server = "";
const char* mqtt_port = "";
const char* mqtt_user = "";
const char* mqtt_password = "";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

//uncomment the following lines if you're using SPI
#include <SPI.h>
#define BME_SCK 14
#define BME_MISO 12
#define BME_MOSI 13
#define BME_CS 15

//Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
float temperature = 0;
float humidity = 0;
float pressure = 0;
float gas = 0;

//Device ID  
//uint64_t chip_id;  
//chip_id=ESP.getEfuseMac();//The chip ID is essentially its MAC address(length: 6 bytes).

// LED Pin
const int ledPin = 4;

void setup() {
  Serial.begin(115200);
  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  //status = bme.begin();  
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
        WiFi.begin();  
  }
  setup_wifi();
  client.setServer(mqtt_server,...);
  client.setCallback(callback);

  pinMode(ledPin, OUTPUT);
  // Set up oversampling and filter initialization
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_2X);
  bme.setPressureOversampling(BME680_OS_4X);
  bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
  bme.setGasHeater(320, 150); // 320*C for 150 ms
}

void setup_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* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 
  // Changes the output state according to the message
  if (String(topic) == "esp32/output") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin, LOW);
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(20000);
    }
  }
}

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

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;

    // Temperature in Celsius
    temperature = bme.readTemperature();   
    // Uncomment the next line to set temperature in Fahrenheit 
    // (and comment the previous temperature line)
    //temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit

    // Convert the value to a char array
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);
    //Serial.print("Temperature: ");
    //Serial.println(tempString);
    //client.publish("esp32/temperature", tempString);

    humidity = bme.readHumidity();

    // Convert the value to a char array
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    //Serial.print("Humidity: ");
    //Serial.println(humString);
    //client.publish("esp32/humidity", humString);

    pressure = bme.readPressure();

    //Convert the value to a char array
    char preString[16];
    dtostrf(pressure, 1, 2, preString);
    //Serial.print("Pressure: ");
    //Serial.println(preString);
    //client.publish("esp32/pressure", preString);

    gas = bme.readGas();

    //Serial.print(bme.gas_resistance / 1000.0);
    char gasString[8];
    dtostrf(gas, 1, 2, gasString);
    //Serial.println(" KOhms");

    char macValue[13]; // Don't forget one byte for the terminating NULL...
    uint64_t mac = ESP.getEfuseMac();
    sprintf(macValue, "%012x", mac);
    //Serial.print("ChipID: ");
    //Serial.println(chipId);
    //client.publish("esp32/chipid", chipId);

    JSONVar data;
    data["temperature"] = temperature;
    data["humidity"] = humidity;
    data["pressure"] = pressure;
    data["macValue"] = macValue;
    data["gas"] = gas;

    //Serial.print("data.keys() = ");
    //Serial.println(data.keys());

    //Serial.print("Data = ");
    //Serial.println(data);

    String jsonString = JSON.stringify(data);
    //Serial.print("JSON.stringify(data) = ");
    //Serial.println(jsonString);
    client.publish("esp32/data", jsonString.c_str());

  }
}

一切都完美地编译了。但是当我尝试上传代码时,出现了此错误:

  Arduino: 1.8.9 (Windows 10), Board: "ESP32 Wrover Module, Huge APP 
 (3MB No OTA), QIO, 80MHz, 115200, Verbose"

  Sketch uses 789282 bytes (25%) of program storage space. Maximum 
  is 3145728 bytes.
  Global variables use 40652 bytes (12%) of dynamic memory, leaving 
  287028 bytes for local variables. Maximum is 327680 bytes.
  esptool.py v2.6
  Serial port COM7
  Connecting.....
  Chip is .....(revision 1)
  Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, 
  Coding Scheme None
  MAC: .....
  Uploading stub...
  Running stub...
  Stub running...
  Configuring flash size...
  Warning: Could not auto-detect Flash size (FlashID=0xffffff, 
  SizeID=0xff), defaulting to 4MB
  Compressed 8192 bytes to 47...

  A fatal error occurred: Timed out waiting for packet content
  A fatal error occurred: Timed out waiting for packet content

  This report would have more information with
  "Show verbose output during compilation"
  option enabled in File -> Preferences.

我不知道为什么会出现这种情况,因为以前我尝试合并BME280并在MQTT上发布可用数据时一切正常。现在,我切换到了bme680。

编辑: 我尝试从ESP32断开BME,然后上传代码,然后重新连接BME。该错误没有显示,但是仍然没有显示数据,而是连续这样:

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371 
ets Jun  8 2016 00:22:57

1 个答案:

答案 0 :(得分:0)

在我看来,当您尝试上传代码时,ESP32-CAM不在引导加载程序模式下。

您是否连接了IO0和GND引脚并按了复位按钮?

您应该在终端窗口中看到一条消息,说明ESP32已准备好上载。

对不起,我的答复很晚...:)