简体   繁体   中英

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. 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. Now, I have switched to bme680.

EDIT: I tried to disconnect BME from ESP32, then uploaded the code, then connected BME back. 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.

Did you connect IO0 and GND pins and push the reset button?

You should see the message that ESP32 is ready for upload in the terminal window.

Sorry for the late reply ... :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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