MH-z19 giving -1 value after some time - arduino-esp8266

I'm trying make an mqtt co2 sensor for home assistant. And I got it to work, but only for a couple of hours. At some point it starts giving me -1 values instead of the proper co2 value. What could this be?
Below my code:
#include <Arduino.h>
#include <Mhz19.h>
#include <SoftwareSerial.h>
SoftwareSerial softwareSerial(D3, D4);
Mhz19 sensor;
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ID";
const char* password = "pw";
const char* MQTT_BROKER = "192.168.1.25";//"test.mosquitto.org";
int mqttPort = 1883;
const char* mqttUser ="mqtt-user";
const char* mqttPassword ="pw";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
// Connect to Wi-Fi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("Connected to Wi-Fi");
}
void reconnect() {
// Loop until connected
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("Test1", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT");
} else {
Serial.print("Failed MQTT connection with state: ");
Serial.println(client.state());
// Re-try in 3 seconds
delay(3000);
}
}
// Once connected, publish an announcement, and subscribe
client.publish("sensor/test", "Hello from ...");
client.subscribe("sensor/test");
}
void setup() {
Serial.begin(115200);
setup_wifi(); // Connect to Wi-Fi network
client.setServer(MQTT_BROKER, mqttPort);
//client.setCallback(callback);
reconnect(); // Connect to MQTT broker
softwareSerial.begin(9600);
sensor.begin(&softwareSerial);
sensor.setMeasuringRange(Mhz19MeasuringRange::Ppm_5000);
sensor.enableAutoBaseCalibration();
Serial.println("Preheating..."); // Preheating, 3 minutes
while (!sensor.isReady()) {
delay(50);
}
Serial.println("Sensor Ready...");
}
void loop() {
if (!client.connected()) { reconnect(); }
//client.publish("Time", ctime(&now));
auto carbonDioxide = sensor.getCarbonDioxide();
if (carbonDioxide >= 0) {
Serial.println(String(carbonDioxide) + " ppm");
}
char co2String[8];
dtostrf(carbonDioxide, 1,0, co2String);
//Serial.println(co2String);
client.publish("Floating/climate/CO2", co2String);
delay(2000);
}
I also tried flashing it via ESPHome, but then I run into issues from UART. The chip doesn't work propperly as long as the sensor is connected to it.

The sensor may not be receiving enough current. Try connecting the sensor directly to a separate breadboard power supply. The sensor seems to have a warm up time. Try waiting for longer with the independent power supply connected. I hope this will solve your issue.
Thank You,
Naveen PS

Related

ESP8266 not connected in Azure Iot Hub, return state -2

I'm trying to connect my ESP8266 to Azure Hub IoT, but I'm not getting it. I've already followed examples and I get the return rc = -2.
I use https://github.com/knolleary/pubsubclient libary.
I used the library example and other examples and nothing being able to connect to Azure Hub IoT.
Error this line
client.connect(dispositivo, usuario_mqtt, senha_mqtt)
My code
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
const char* nome_wifi = "M11";
const char* senha_wifi = "035954159";
const char* broker = "tiedt-tech-iot-hub.azure-devices.net";
const char* dispositivo = "esp-quarto";
const char* usuario_mqtt = "tiedt-tech-iot-hub.azure-devices.net/esp-quarto";
const char* senha_mqtt = "SharedAccessSignature sr=tiedt-tech-iot-hub.azure-devices.net%2Fdevices%2Fesp-quarto&sig=uM6iZTBylAcNHa4%2F4GYxPcAwMUfMAljCx5zvHyx3m%2BE%3D&se=1647197049";
const char* topico = "devices/esp-quarto/messages/events/";
WiFiClientSecure espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
conectarWifi();
}
void conectarWifi(){
Serial.print("Conectando na rede");
WiFi.begin(nome_wifi, senha_wifi);
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi Conectado");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void conectarMQTT() {
Serial.println("Conectando no broker");
client.setServer(broker, 8883);
while(!client.connected()) {
if (client.connect(dispositivo, usuario_mqtt, senha_mqtt)){
Serial.println("Conectado no broker");
}
else {
Serial.print("Falha na conexão com o broker, rc= ");
Serial.print(client.state());
Serial.println("");
delay(5000);
}
}
}
void loop(){
if (!client.connected()){
conectarMQTT();
}
}
Since late last year, there is an official Arduino SDK for ESP8266 boards. You can find it here, it comes with an example that I can confirm works.
It takes care of some of the heavy lifting, and uses the same WifiClientSecure and PubSubClient classes of your implementation.

ESP8266 is not getting connected to my deployed websocket on heroku

I have deployed a nodejs websocket on heroku. But my ESP8266 cannot get connected to that websocket. Before deploying that websocket on heroku, i tried it out locally and it worked pretty well. ESP8266 also got connected to it without any error. Then I made some changes in nodejs socket (before deploying) in order to run it on heroku. i just don't understand what's wrong with this esp8266 code
ESP8266's Code
#include <ESP8266WiFi.h>
#include <WebSocketClient.h>
boolean handshakeFailed = 0;
String data = "";
char path[] = "/"; //identifier of this device
const char *ssid = ""; //<-------------------this was entered correctly. Wifi connection was successful. websocket connection got failed
const char *password = ""; // <-------------------this was entered correctly. Wifi connection was successful. websocket connection got failed
char *host = "example.herokuapp.com"; //replace this ip address with the ip address of your Node.Js server
const int espport = 3000;
WebSocketClient webSocketClient;
unsigned long previousMillis = 0;
unsigned long currentMillis;
unsigned long interval = 300; //interval for sending data to the websocket server in ms
// Use WiFiClient class to create TCP connections
WiFiClient client;
void setup()
{
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
delay(10);
// We start by connecting to a WiFi network
Serial.println();
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());
delay(1000);
wsconnect();
// wifi_set_sleep_type(LIGHT_SLEEP_T);
}
void loop()
{
if (client.connected())
{
currentMillis = millis();
webSocketClient.getData(data);
if (data.length() > 0)
{
Serial.println(data);
//*************send log data to server in certain interval************************************
//currentMillis=millis();
if (abs(currentMillis - previousMillis) >= interval)
{
previousMillis = currentMillis;
data = (String)analogRead(A0); //read adc values, this will give random value, since no sensor is connected.
//For this project we are pretending that these random values are sensor values
webSocketClient.sendData(data); //send sensor data to websocket server
}
}
else
{
}
delay(5);
}
}
void wsconnect()
{
// Connect to the websocket server
if (client.connect(host, espport))
{
Serial.println("WebSocket Connected");
}
else
{
Serial.println("Connection failed.");
delay(1000);
if (handshakeFailed)
{
handshakeFailed = 0;
ESP.restart();
}
handshakeFailed = 1;
}
// Handshake with the server
webSocketClient.path = path;
webSocketClient.host = host;
if (webSocketClient.handshake(client))
{
Serial.println("Handshake successful");
}
else
{
Serial.println("Handshake failed.");
delay(4000);
if (handshakeFailed)
{
handshakeFailed = 0;
ESP.restart();
}
handshakeFailed = 1;
}
}

can't connect esp8266 device to azure IoT hub

I am trying to connect a esp8266(esp-12e node mcu 1.0) to azure iot hub with code written in arduino. I've created a iot hub and a device using symmetric key authentication. Using the PubSubClient along with WifiClientSecure library to provide a secure mqtt connection(port 8883). generated a SAS token for the device. can't seem to connect to azure and keep getting mqtt disconnected error (-1). Oh and have the azure Baltimore CyberTrust Root CA downloaded and added
#define AZURE
//#define AWS
#ifdef AZURE
#include "secretsAzure.h"
#elif defined(AWS)
#include "secretsAws.h"
#endif
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
BearSSL::WiFiClientSecure net;
BearSSL::X509List cert(cacert);
PubSubClient client(net);
void connectToWiFi()
{
Serial.print("connecting to wifi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(1000);
}
Serial.println("ok!");
}
void connectToMqtt()
{
Serial.print("MQTT connecting ");
while (!client.connected())
{
if (client.connect(THINGNAME, USER, SAS_TOKEN))
{
Serial.println("connected!");
if (!client.subscribe(MQTT_SUB_TOPIC))
Serial.println(client.state());
}
else
{
Serial.print("failed ");
Serial.println(client.state());
delay(5000);
}
}
}
void setup()
{
pinMode(MYPIN, OUTPUT);
Serial.begin(115200);
WiFi.hostname(THINGNAME);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
connectToWiFi();
net.setTrustAnchors(&cert);
client.setServer(MQTT_HOST, MQTT_PORT);
delay(5000);
connectToMqtt();
}
unsigned long lastMillis = 0;
void loop()
{
if (!client.connected())
connectToMqtt();
else
{
client.loop();
if (millis() - lastMillis > 5000)
{
lastMillis = millis();
//sendData();
}
}
}

Measuring bluetooth connection force with ESP32

How can I measure the bluetooth connection force with ESP32? I'm using the available example of BLE to detect the possibility of connection, but I need to measure its strength. Thank you.
I'm using:
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
int scanTime = 30; //In seconds
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
}
};
void setup() {
Serial.begin(115200);
Serial.println("Scanning...");
BLEDevice::init("");
BLEScan* pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
BLEScanResults foundDevices = pBLEScan->start(scanTime);
Serial.print("Devices found: ");
Serial.println(foundDevices.getCount());
Serial.println("Scan done!");
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000);
}`
Just a few lines added to your MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks :
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str
int rssi = advertisedDevice.getRSSI();
Serial.print("Rssi: ");
Serial.println(rssi);
}
};
in wifi i am using this function:
// Take a number of measurements of the WiFi strength and return the average result.
int getStrength(int points){
long rssi = 0;
long averageRSSI=0;
for (int i=0;i < points;i++){
rssi += WiFi.RSSI(); // put your BLE function here
delay(20);
}
averageRSSI=rssi/points;
return averageRSSI;
}
and you have the same function for BLE than WiFi.RSSI(): (see in github source code)
int BLEAdvertisedDevice::getRSSI() {
return m_rssi;
} // getRSSI

Cannot set hostname for ESP8266

I am facing a problem, as setting host name for my ESP8266 is not working. Even though when I'm trying to connect through default host name "ESP_xxxx", it's not working.
Actually when I upload my code with my mobile hotspot SSID and password then it's working fine, but as soon as I gave the SSID and password of my router then it's not working.
Here's my code (setup part):
#include <ESP8266WiFi.h>
const char* ssid = "xxxxxx";
const char* password = "xxxxxx";
int ledPin = 13; // GPIO13
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.hostname("xyz");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
Serial.println(WiFi.hostname());
}
Try this:
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h" //https://github.com/tzapu/WiFiManager
void configModeCallback (WiFiManager *myWiFiManager)
{
Serial.println("Entered config mode");
Serial.println(WiFi.softAPIP());
Serial.println(myWiFiManager->getConfigPortalSSID());
}
//
void setup()
{
Serial.begin(115200);
//
WiFiManager wifiManager;
WiFi.hostname("myhostname");
//
//wifiManager.resetSettings();
//
//
wifiManager.setAPCallback(configModeCallback);
if (!wifiManager.autoConnect("myhostname"))
{
Serial.println("failed to connect and hit timeout");
// reset
ESP.reset();
delay(1000);
}
//
Serial.println("connected...yeey :)");
}
void loop()
{
//
}
Stumbled upon this issue and below is the code which works for me.
WiFi.disconnect(true);
WiFi.begin(ssid, password);
WiFi.setHostname(device);`
Also came across below code, with this line the module is not receiving any IP. Hence deleted it.
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
Running on Arduino 1.8.15 and esp8266 board version 3.0.1
Try using mDNS instead.
Include the mDNS library
#include <ESP8266mDNS.h>
Then in the setup after you connected to WiFi, start mDNS like this.
if (!MDNS.begin("your-desired-hostname")) {
Serial.println("Error setting up MDNS responder!");
}

Resources