Here is a simple example of how to use the Adafruit library https://github.com/adafruit/Adafruit_PM25AQI with a Custom Sensor in ESPHome.
# YAML File esphome: name: bentoair platform: ESP32 board: esp-wrover-kit includes: - BentoAir.h libraries: - "Adafruit PM25 AQI Sensor" - "Adafruit BusIO" - "SPI" wifi: ssid: "..." password: "..." # Enable fallback hotspot (captive portal) in case wifi connection fails ap: ssid: "Air Quality Fallback Hotspot" password: "NSZIXXkPiruF" captive_portal: # Enable logging logger: # Enable Home Assistant API api: ota: i2c: sda: 21 scl: 22 scan: True id: bus_a sensor: - platform: custom lambda: |- auto my_sensor = new MyCustomSensor(); App.register_component(my_sensor); return {my_sensor->pm10s_sensor, my_sensor->pm25s_sensor, my_sensor->pm100s_sensor}; sensors: - name: "PM1.0 Sensor" unit_of_measurement: ug/m3 - name: "PM2.5 Sensor" unit_of_measurement: ug/m3 - name: "PM10.0 Sensor" unit_of_measurement: ug/m3
And the C++ Custom Sensor file BentoAir.h looks like this:
#include "esphome.h" #include "Adafruit_PM25AQI.h" class MyCustomSensor : public PollingComponent, public Sensor { public: Adafruit_PM25AQI aqi = Adafruit_PM25AQI(); Sensor *pm10s_sensor = new Sensor(); Sensor *pm25s_sensor = new Sensor(); Sensor *pm100s_sensor = new Sensor(); MyCustomSensor() : PollingComponent(1000) { } // every 60 seconds void setup() override { delay(1000); if (! aqi.begin_I2C()) { // connect to the sensor over I2C //if (! aqi.begin_UART(&Serial1)) { // connect to the sensor over hardware serial //if (! aqi.begin_UART(&pmSerial)) { // connect to the sensor over software serial Serial.println("Could not find PM 2.5 sensor!"); while (1) delay(10); } } void update() override { float temp_f; PM25_AQI_Data data; // Read AQI Sensor if (! aqi.read(&data)) { Serial.println("Could not read from AQI"); delay(500); // try again in a bit! return; } pm10s_sensor->publish_state(data.pm10_standard); pm25s_sensor->publish_state(data.pm25_standard); pm100s_sensor->publish_state(data.pm100_standard); } };