ESPHome  2024.10.3
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 
7 namespace esphome {
8 namespace gp2y1010au0f {
9 
10 static const char *const TAG = "gp2y1010au0f";
11 static const float MIN_VOLTAGE = 0.0f;
12 static const float MAX_VOLTAGE = 4.0f;
13 
15  LOG_SENSOR("", "Sharp GP2Y1010AU0F PM2.5 Sensor", this);
16  ESP_LOGCONFIG(TAG, " Sampling duration: %" PRId32 " ms", this->sample_duration_);
17  ESP_LOGCONFIG(TAG, " ADC voltage multiplier: %.3f", this->voltage_multiplier_);
18  LOG_UPDATE_INTERVAL(this);
19 }
20 
22  is_sampling_ = true;
23 
24  this->set_timeout("read", this->sample_duration_, [this]() {
25  this->is_sampling_ = false;
26  if (this->num_samples_ == 0)
27  return;
28 
29  float mean = this->sample_sum_ / float(this->num_samples_);
30  ESP_LOGD(TAG, "ADC read voltage: %.3f V (mean from %" PRId32 " samples)", mean, this->num_samples_);
31 
32  // PM2.5 calculation
33  // ref: https://www.howmuchsnow.com/arduino/airquality/
34  int16_t pm_2_5_value = 170 * mean;
35  this->publish_state(pm_2_5_value);
36  });
37 
38  // reset readings
39  this->num_samples_ = 0;
40  this->sample_sum_ = 0.0f;
41 }
42 
44  if (!this->is_sampling_)
45  return;
46 
47  // enable the internal IR LED
48  this->led_output_->turn_on();
49  // wait for the sensor to stabilize
51  // perform a single sample
52  float read_voltage = this->source_->sample();
53  // disable the internal IR LED
54  this->led_output_->turn_off();
55 
56  if (std::isnan(read_voltage))
57  return;
58  read_voltage = read_voltage * this->voltage_multiplier_ - this->voltage_offset_;
59  if (read_voltage < MIN_VOLTAGE || read_voltage > MAX_VOLTAGE)
60  return;
61 
62  this->num_samples_++;
63  this->sample_sum_ += read_voltage;
64 }
65 
66 } // namespace gp2y1010au0f
67 } // namespace esphome
virtual void turn_on()
Enable this binary output.
Definition: binary_output.h:43
virtual void turn_off()
Disable this binary output.
Definition: binary_output.h:51
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:69
voltage_sampler::VoltageSampler * source_
Definition: gp2y1010au0f.h:38
virtual float sample()=0
Get a voltage reading, in V.
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition: core.cpp:28