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