ESPHome 2026.6.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
9static const char *const TAG = "gp2y1010au0f";
10static const float MIN_VOLTAGE = 0.0f;
11static const float MAX_VOLTAGE = 4.0f;
12
14 LOG_SENSOR("", "Sharp GP2Y1010AU0F PM2.5 Sensor", this);
15 ESP_LOGCONFIG(TAG,
16 " Sampling duration: %" PRId32 " ms\n"
17 " ADC voltage multiplier: %.3f",
19 LOG_UPDATE_INTERVAL(this);
20}
21
23 is_sampling_ = true;
24
25 this->set_timeout("read", this->sample_duration_, [this]() {
26 this->is_sampling_ = false;
27 if (this->num_samples_ == 0)
28 return;
29
30 float mean = this->sample_sum_ / float(this->num_samples_);
31 ESP_LOGD(TAG, "ADC read voltage: %.3f V (mean from %" PRId32 " samples)", mean, this->num_samples_);
32
33 // PM2.5 calculation
34 // ref: https://www.howmuchsnow.com/arduino/airquality/
35 int16_t pm_2_5_value = 170 * mean;
36 this->publish_state(pm_2_5_value);
37 });
38
39 // reset readings
40 this->num_samples_ = 0;
41 this->sample_sum_ = 0.0f;
42}
43
45 if (!this->is_sampling_)
46 return;
47
48 // enable the internal IR LED
49 this->led_output_->turn_on();
50 // wait for the sensor to stabilize
52 // perform a single sample
53 float read_voltage = this->source_->sample();
54 // disable the internal IR LED
55 this->led_output_->turn_off();
56
57 if (std::isnan(read_voltage))
58 return;
59 read_voltage = read_voltage * this->voltage_multiplier_ - this->voltage_offset_;
60 if (read_voltage < MIN_VOLTAGE || read_voltage > MAX_VOLTAGE)
61 return;
62
63 this->num_samples_++;
64 this->sample_sum_ += read_voltage;
65}
66
67} // namespace esphome::gp2y1010au0f
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:493
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:68
virtual float sample()=0
Get a voltage reading, in V.
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48