ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
gp2y1010au0f.cpp
Go to the documentation of this file.
1#include "gp2y1010au0f.h"
2#include "esphome/core/hal.h"
3#include "esphome/core/log.h"
4
5#include <cinttypes>
6
8
9ESPHOME_LOG_TAG(TAG, "gp2y1010au0f");
10
11static constexpr uint32_t READ_TIMEOUT_ID = 0;
12
13static const float MIN_VOLTAGE = 0.0f;
14static const float MAX_VOLTAGE = 4.0f;
15
17 LOG_SENSOR("", "Sharp GP2Y1010AU0F PM2.5 Sensor", this);
18 ESP_LOGCONFIG(TAG,
19 " Sampling duration: %" PRId32 " ms\n"
20 " ADC voltage multiplier: %.3f",
22 LOG_UPDATE_INTERVAL(this);
23}
24
26 is_sampling_ = true;
27
28 this->set_timeout(READ_TIMEOUT_ID, this->sample_duration_, [this]() {
29 this->is_sampling_ = false;
30 if (this->num_samples_ == 0)
31 return;
32
33 float mean = this->sample_sum_ / float(this->num_samples_);
34 ESP_LOGD(TAG, "ADC read voltage: %.3f V (mean from %" PRId32 " samples)", mean, this->num_samples_);
35
36 // PM2.5 calculation
37 // ref: https://www.howmuchsnow.com/arduino/airquality/
38 int16_t pm_2_5_value = 170 * mean;
39 this->publish_state(pm_2_5_value);
40 });
41
42 // reset readings
43 this->num_samples_ = 0;
44 this->sample_sum_ = 0.0f;
45}
46
48 if (!this->is_sampling_)
49 return;
50
51 // enable the internal IR LED
52 this->led_output_->turn_on();
53 // wait for the sensor to stabilize
55 // perform a single sample
56 float read_voltage = this->source_->sample();
57 // disable the internal IR LED
58 this->led_output_->turn_off();
59
60 if (std::isnan(read_voltage))
61 return;
62 read_voltage = read_voltage * this->voltage_multiplier_ - this->voltage_offset_;
63 if (read_voltage < MIN_VOLTAGE || read_voltage > MAX_VOLTAGE)
64 return;
65
66 this->num_samples_++;
67 this->sample_sum_ += read_voltage;
68}
69
70} // namespace esphome::gp2y1010au0f
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
voltage_sampler::VoltageSampler * source_
virtual void turn_off()
Disable this binary output.
virtual void turn_on()
Enable this binary output.
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
virtual float sample()=0
Get a voltage reading, in V.
ESPHOME_LOG_TAG(TAG, "gp2y1010au0f")
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
static void uint32_t