简体   繁体   English

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

[英]how do i publish the data on mqtt of the bme680 sensor using ESP32cam

I am using windows 10 and working on getting the gas readings from BME680 using esp32cam.我正在使用 Windows 10 并使用 esp32cam 从 BME680 获取气体读数。 I tried to add this:我试图添加这个:

#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());

  }
}

everything got compiled perfectly.一切都得到了完美的编译。 But when i tried to upload the code, this error came up:但是当我尝试上传代码时,出现了这个错误:

  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.

I don't know why is this thing coming up because previously everything was working fine when I tried to incorporate BME280 and publish the available data on MQTT.我不知道为什么会出现这个问题,因为以前当我尝试合并 BME280 并在 MQTT 上发布可用数据时,一切正常。 Now, I have switched to bme680.现在,我已经切换到 bme680。

EDIT: I tried to disconnect BME from ESP32, then uploaded the code, then connected BME back.编辑:我尝试断开 BME 与 ESP32 的连接,然后上传代码,然后重新连接 BME。 The error did not show up, but still, the data is not being shown this time, rather something like this, continually:错误没有出现,但这次仍然没有显示数据,而是像这样,不断地显示:

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

It looks to me that ESP32-CAM is not in the bootloader mode when you try to upload the code.在我看来,当您尝试上传代码时,ESP32-CAM 未处于引导加载程序模式。

Did you connect IO0 and GND pins and push the reset button?您是否连接了 IO0 和 GND 引脚并按下了复位按钮?

You should see the message that ESP32 is ready for upload in the terminal window.您应该会在终端窗口中看到 ESP32 已准备好上传的消息。

Sorry for the late reply ... :)这么晚才回复很抱歉 ... :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM