Code Monkey home page Code Monkey logo

sds011's Introduction

SDS011

SDS011 particle matter sensor library for the Arduino framework for ESP8266 and ESP32.

This is yet another SDS011 library, this time completely non blocking. It does come with a loop()-method to poll the serial port.

Installation

Usage

ESP8266 only has one full UART port so you may want to use SoftwareSerial on this platform.

To do something useful you can combine this lib with MQTT (like espMqttClient) as in the example below.

#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <espMqttClient.h>
#include <SDS011.h>

const char SSID[] = "My_WiFi";
const char PASS[] = "My_Pass";
const IPAddress BROKER = {192, 168, 1, 10};

SDS011 sds011;
espMqttClient mqttClient;
Ticker mqttReconnectTimer;

WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker wifiReconnectTimer;

bool connected = false;

void connectToWifi() {
  WiFi.begin(SSID, PASS);
}

void onWifiConnect(const WiFiEventStationModeGotIP& event) {
  connectToMqtt();
}

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  wifiReconnectTimer.once(2, connectToWifi);
}

void connectToMqtt() {
  if (!mqttClient.connect()) {
    mqttReconnectTimer.once(2, connectToMqtt);
}

void onMqttConnected(bool sessionPresent) {
  connected = true;
}

void onMqttDisconnect(espMqttClientTypes::DisconnectReason reason) {
  connected = false;
  if (WiFi.isConnected()) {
    mqttReconnectTimer.once(2, connectToMqtt);
  }
}

void onSensorData(float pm25Value, float pm10Value) {
  if (connected) {
    mqttClient.publish("/SENSOR/PM2_5", 1, false, String(pm25Value, 1).c_str());
    mqttClient.publish("/SENSOR/PM10", 1, false, String(pm10Value, 1).c_str());
  }
}

void onSensorResponse(uint8_t command, uint8_t set, uint8_t result) {
  // log to MQTT
}

void onSensorError(int8_t error){
  // error happened
  // -1: CRC error
}

void setup() {
  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

  mqttClient.onConnect(onMqttConnected);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.setServer(BROKER, 1883);

  sds011.setup(&Serial);
  sds011.onData(onSensorData);
  sds011.onResponse(onSensorResponse);
  sds011.onError(onSensorResponse);
  sds011.setWorkingPeriod(5);

  connectToWifi();
}

void loop() {
  sds011.loop();
}

To Do

  • adjust readings based on humidity
  • possible timeout after sending a command
  • implement missing commands
  • multiple sensors (apparently the firmware supports this. However, they implemented hardware using 1-1 UART) ???

Issues, improvements?

Please create a ticket or pull request.

sds011's People

Contributors

bertmelis avatar suhlig avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

sds011's Issues

not working on esp32 with arduino

Unfortunatly it does not really work with the arduino IDE...

The sketch below compiles and it starts running without errors when i upload via ArduinoIDE. But it never delivers any values and is stuck at "Data should appear on the default serial port in less than a minute".

I know the hardware and wiring works since everything works as expected with esp_sds011 library.

Do you have any idea what might be the issue here?

#include <SDS011.h>

HardwareSerial usbSerial(0);

HardwareSerial sds011Serial(1);

SDS011 sds011;

void setup() {



  
  usbSerial.begin(115200);
  sds011.setup(&sds011Serial, 15, 2);  // Rx on GPIO14; Tx on GPIO12
    
  sds011.onData([](float pm25Value, float pm10Value) {
    usbSerial.println("Data arrived: PM2.5 = " + String(pm25Value, 1) + " μg/m³; PM10 = " + String(pm10Value, 1) + " μg/m³");
  });

  sds011.onResponse([](uint8_t command, uint8_t set, uint8_t result) {
    usbSerial.println("Response to command 0x" + String(command, HEX) + " received: 0x" + String(result, HEX));
  });

  sds011.onError([](int8_t error) {
    usbSerial.println("Error occurred: 0x" + String(error, HEX));
  });

  sds011.setWorkingPeriod(1);
  usbSerial.println("Data should appear on the default serial port in less than a minute");
}

void loop() {
   
  sds011.loop();
}

Can't compile on ESP32 with hardware serial 2

Hi,

I wanted to give a try with your non blocking library,
But I can't successfully compile it with arduino IDE 2.3.2.
The board I use is a ESP32 developpement board with 38 yellow pins https://arduino-projekte.info/wp-content/uploads/2021/08/Node_MCU_ESP32_38Pin_pinout.webp https://raw.githubusercontent.com/AchimPieters/esp32-homekit-camera/master/Images/ESP32-38%20PIN-DEVBOARD.png

I cloned the library this way:

cd Arduino/libraries
git clone https://github.com/bertmelis/SDS011.git

I modified the example this way:

#include <HardwareSerial.h>
#include <SDS011.h>//librairie clonee manuellement 1.0.0 du 14/09/2018 mais fichiers plus récents https://github.com/bertmelis/SDS011

#define RXD2 16
#define TXD2 17

HardwareSerial usbSerial(0);
HardwareSerial sds011Serial(2);
//HardwareSerial sds011Serial(Serial2);

SDS011 sds011;

void setup() {
  usbSerial.begin(115200);
  //Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);//SDS011

  sds011.setup(&sds011Serial, RXD2, TXD2);  // Rx on GPIO14; Tx on GPIO12
  //sds011.setup(&Serial2, RXD2, TXD2);  // Rx on GPIO14; Tx on GPIO12
  

  sds011.onData([](float pm25Value, float pm10Value) {
    usbSerial.println("Data arrived: PM2.5 = " + String(pm25Value, 1) + " μg/m³; PM10 = " + String(pm10Value, 1) + " μg/m³");
  });

  sds011.onResponse([](uint8_t command, uint8_t set, uint8_t result) {
    usbSerial.println("Response to command 0x" + String(command, HEX) + " received: 0x" + String(result, HEX));
  });

  sds011.onError([](int8_t error) {
    usbSerial.println("Error occurred: 0x" + String(error, HEX));
  });

  sds011.setWorkingPeriod(1);
  usbSerial.println("Data should appear on the default serial port in less than a minute");
}

void loop() {
  sds011.loop();
}

But I get this error:

WARNING: library SDS011 claims to run on esp8266 architecture(s) and may be incompatible with your current board which runs on esp32 architecture(s).
Arduino/libraries/SDS011/src/SDS011.cpp: In member function 'void SDS011::setup(HardwareSerial*, uint8_t, uint8_t)':
Arduino/libraries/SDS011/src/SDS011.cpp:58:12: error: 'class Stream' has no member named 'begin'
   _serial->begin(9600, SERIAL_8N1, rx_pin, tx_pin);
            ^~~~~

exit status 1

Compilation error: exit status 1

I previously could use my sds011 with this other library https://github.com/lewapek/sds-dust-sensors-arduino-library/tree/master with this code:

#include "SdsDustSensor.h" //Nova Fitness Sds dust sensors library by Paweł Kołodziejczyk 1.5.1 du 14/02/2022 https://github.com/lewapek/sds-dust-sensors-arduino-library/tree/master

// tested on Arduino Leonardo with Serial1
SdsDustSensor sds(Serial2); // passing HardwareSerial& as parameter
#define RXD2 16
#define TXD2 17


void setup() {
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);//SDS011
  sds.begin(9600); // this line will begin Serial1 with given baud rate (9600 by default)

  Serial.println(sds.queryFirmwareVersion().toString()); // prints firmware version
  Serial.println(sds.setQueryReportingMode().toString()); // ensures sensor is in 'query' reporting mode
}

void loop() {
  sds.wakeup();
  delay(10000); // working 30 seconds

  PmResult pm = sds.queryPm();
  if (pm.isOk()) {
    //Serial.print("PM2.5 = ");
    //Serial.print(pm.pm25);
    //Serial.print(", PM10 = ");
    //Serial.println(pm.pm10);

    // if you want to just print the measured values, you can use toString() method as well
    Serial.println(pm.toString());
  } else {
    Serial.print("Could not read values from sensor, reason: ");
    Serial.println(pm.statusToString());
  }

  WorkingStateResult state = sds.sleep();
  if (state.isWorking()) {
    Serial.println("Problem with sleeping the sensor.");
  } else {
    Serial.println("Sensor is sleeping");
    delay(10000); // wait 1 minute
  }
}

Could you please help me to find what I am missing?

improvement? Software serial

I have had so much trouble with this sensor and the esp8266. esp32 works and then I have more issues in other areas with that device. Specifically with my home automation setup.

Could you add software serial or maybe hint to how I could use it instead or hardware? I have successfully been able to use software serial with the espsoftwareserial library and the sdsdustsensor library. Allowing serial debugging while I build out the code.

The problem is that the sdsdustsensor library is blocking the entire time it sleeps the sds sensor. I find your library and it seems to be the godsend I am after. I just cannot understand how to add a different port, softwareserial port, to the example myself.

I looked through the library to see the references used and I cannot figure out how to modify it so that I can use something other than hardware serial.

can I somehow change the sds011.setup line to use softwareserial?

Error-Feature request

I'm trying to use yr example but unfortunatley it keeps coming up with the following error at 👍
sds011.onResponse({
// command has been executed
});
error: no matching function for call to 'SDS011::onResponse(setup()::__lambda5)'

Moreover, my MQTT broker uses an mqttusername and mqttpassword, could that be implemented.
Thnks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.