ESPHome 2025.6.0
Loading...
Searching...
No Matches
scd4x.cpp
Go to the documentation of this file.
1#include "scd4x.h"
2#include "esphome/core/hal.h"
3#include "esphome/core/log.h"
4
5namespace esphome {
6namespace scd4x {
7
8static const char *const TAG = "scd4x";
9
10static const uint16_t SCD4X_CMD_GET_SERIAL_NUMBER = 0x3682;
11static const uint16_t SCD4X_CMD_TEMPERATURE_OFFSET = 0x241d;
12static const uint16_t SCD4X_CMD_ALTITUDE_COMPENSATION = 0x2427;
13static const uint16_t SCD4X_CMD_AMBIENT_PRESSURE_COMPENSATION = 0xe000;
14static const uint16_t SCD4X_CMD_AUTOMATIC_SELF_CALIBRATION = 0x2416;
15static const uint16_t SCD4X_CMD_START_CONTINUOUS_MEASUREMENTS = 0x21b1;
16static const uint16_t SCD4X_CMD_START_LOW_POWER_CONTINUOUS_MEASUREMENTS = 0x21ac;
17static const uint16_t SCD4X_CMD_START_LOW_POWER_SINGLE_SHOT = 0x219d; // SCD41 only
18static const uint16_t SCD4X_CMD_START_LOW_POWER_SINGLE_SHOT_RHT_ONLY = 0x2196;
19static const uint16_t SCD4X_CMD_GET_DATA_READY_STATUS = 0xe4b8;
20static const uint16_t SCD4X_CMD_READ_MEASUREMENT = 0xec05;
21static const uint16_t SCD4X_CMD_PERFORM_FORCED_CALIBRATION = 0x362f;
22static const uint16_t SCD4X_CMD_STOP_MEASUREMENTS = 0x3f86;
23static const uint16_t SCD4X_CMD_FACTORY_RESET = 0x3632;
24static const uint16_t SCD4X_CMD_GET_FEATURESET = 0x202f;
25static const float SCD4X_TEMPERATURE_OFFSET_MULTIPLIER = (1 << 16) / 175.0f;
26static const uint16_t SCD41_ID = 0x1408;
27static const uint16_t SCD40_ID = 0x440;
28
30 ESP_LOGCONFIG(TAG, "Running setup");
31 // the sensor needs 1000 ms to enter the idle state
32 this->set_timeout(1000, [this]() {
33 this->status_clear_error();
34 if (!this->write_command(SCD4X_CMD_STOP_MEASUREMENTS)) {
35 ESP_LOGE(TAG, "Failed to stop measurements");
36 this->mark_failed();
37 return;
38 }
39 // According to the SCD4x datasheet the sensor will only respond to other commands after waiting 500 ms after
40 // issuing the stop_periodic_measurement command
41 this->set_timeout(500, [this]() {
42 uint16_t raw_serial_number[3];
43 if (!this->get_register(SCD4X_CMD_GET_SERIAL_NUMBER, raw_serial_number, 3, 1)) {
44 ESP_LOGE(TAG, "Failed to read serial number");
46 this->mark_failed();
47 return;
48 }
49 ESP_LOGD(TAG, "Serial number %02d.%02d.%02d", (uint16_t(raw_serial_number[0]) >> 8),
50 uint16_t(raw_serial_number[0] & 0xFF), (uint16_t(raw_serial_number[1]) >> 8));
51
52 if (!this->write_command(SCD4X_CMD_TEMPERATURE_OFFSET,
53 (uint16_t) (temperature_offset_ * SCD4X_TEMPERATURE_OFFSET_MULTIPLIER))) {
54 ESP_LOGE(TAG, "Error setting temperature offset.");
56 this->mark_failed();
57 return;
58 }
59
60 // If pressure compensation available use it
61 // else use altitude
64 ESP_LOGE(TAG, "Error setting ambient pressure compensation.");
66 this->mark_failed();
67 return;
68 }
69 } else {
70 if (!this->write_command(SCD4X_CMD_ALTITUDE_COMPENSATION, altitude_compensation_)) {
71 ESP_LOGE(TAG, "Error setting altitude compensation.");
73 this->mark_failed();
74 return;
75 }
76 }
77
78 if (!this->write_command(SCD4X_CMD_AUTOMATIC_SELF_CALIBRATION, enable_asc_ ? 1 : 0)) {
79 ESP_LOGE(TAG, "Error setting automatic self calibration.");
81 this->mark_failed();
82 return;
83 }
84
85 initialized_ = true;
86 // Finally start sensor measurements
87 this->start_measurement_();
88 ESP_LOGD(TAG, "Sensor initialized");
89 });
90 });
91}
92
94 ESP_LOGCONFIG(TAG, "scd4x:");
95 LOG_I2C_DEVICE(this);
96 if (this->is_failed()) {
97 switch (this->error_code_) {
99 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
100 break;
102 ESP_LOGW(TAG, "Measurement Initialization failed");
103 break;
105 ESP_LOGW(TAG, "Unable to read sensor firmware version");
106 break;
107 default:
108 ESP_LOGW(TAG, "Unknown setup error");
109 break;
110 }
111 }
112 ESP_LOGCONFIG(TAG, " Automatic self calibration: %s", ONOFF(this->enable_asc_));
113 if (this->ambient_pressure_source_ != nullptr) {
114 ESP_LOGCONFIG(TAG, " Dynamic ambient pressure compensation using sensor '%s'",
116 } else {
118 ESP_LOGCONFIG(TAG,
119 " Altitude compensation disabled\n"
120 " Ambient pressure compensation: %dmBar",
121 this->ambient_pressure_);
122 } else {
123 ESP_LOGCONFIG(TAG,
124 " Ambient pressure compensation disabled\n"
125 " Altitude compensation: %dm",
127 }
128 }
129 switch (this->measurement_mode_) {
130 case PERIODIC:
131 ESP_LOGCONFIG(TAG, " Measurement mode: periodic (5s)");
132 break;
134 ESP_LOGCONFIG(TAG, " Measurement mode: low power periodic (30s)");
135 break;
136 case SINGLE_SHOT:
137 ESP_LOGCONFIG(TAG, " Measurement mode: single shot");
138 break;
140 ESP_LOGCONFIG(TAG, " Measurement mode: single shot rht only");
141 break;
142 }
143 ESP_LOGCONFIG(TAG, " Temperature offset: %.2f °C", this->temperature_offset_);
144 LOG_UPDATE_INTERVAL(this);
145 LOG_SENSOR(" ", "CO2", this->co2_sensor_);
146 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
147 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
148}
149
151 if (!initialized_) {
152 return;
153 }
154
155 if (this->ambient_pressure_source_ != nullptr) {
157 if (!std::isnan(pressure)) {
159 }
160 }
161
162 uint32_t wait_time = 0;
165 wait_time =
166 this->measurement_mode_ == SINGLE_SHOT ? 5000 : 50; // Single shot measurement takes 5 secs rht mode 50 ms
167 }
168 this->set_timeout(wait_time, [this]() {
169 // Check if data is ready
170 if (!this->write_command(SCD4X_CMD_GET_DATA_READY_STATUS)) {
171 this->status_set_warning();
172 return;
173 }
174
175 uint16_t raw_read_status;
176
177 if (!this->read_data(raw_read_status) || raw_read_status == 0x00) {
178 this->status_set_warning();
179 ESP_LOGW(TAG, "Data not ready yet!");
180 return;
181 }
182
183 if (!this->write_command(SCD4X_CMD_READ_MEASUREMENT)) {
184 ESP_LOGW(TAG, "Error reading measurement!");
185 this->status_set_warning();
186 return; // NO RETRY
187 }
188 // Read off sensor data
189 uint16_t raw_data[3];
190 if (!this->read_data(raw_data, 3)) {
191 this->status_set_warning();
192 return;
193 }
194 if (this->co2_sensor_ != nullptr)
195 this->co2_sensor_->publish_state(raw_data[0]);
196
197 if (this->temperature_sensor_ != nullptr) {
198 const float temperature = -45.0f + (175.0f * (raw_data[1])) / (1 << 16);
199 this->temperature_sensor_->publish_state(temperature);
200 }
201 if (this->humidity_sensor_ != nullptr) {
202 const float humidity = (100.0f * raw_data[2]) / (1 << 16);
203 this->humidity_sensor_->publish_state(humidity);
204 }
205 this->status_clear_warning();
206 }); // set_timeout
207}
208
209bool SCD4XComponent::perform_forced_calibration(uint16_t current_co2_concentration) {
210 /*
211 Operate the SCD4x in the operation mode later used in normal sensor operation (periodic measurement, low power
212 periodic measurement or single shot) for > 3 minutes in an environment with homogeneous and constant CO2
213 concentration before performing a forced recalibration.
214 */
215 if (!this->write_command(SCD4X_CMD_STOP_MEASUREMENTS)) {
216 ESP_LOGE(TAG, "Failed to stop measurements");
217 this->status_set_warning();
218 }
219 this->set_timeout(500, [this, current_co2_concentration]() {
220 if (this->write_command(SCD4X_CMD_PERFORM_FORCED_CALIBRATION, current_co2_concentration)) {
221 ESP_LOGD(TAG, "setting forced calibration Co2 level %d ppm", current_co2_concentration);
222 // frc takes 400 ms
223 // because this method will be used very rarly
224 // the simple approach with delay is ok
225 delay(400); // NOLINT'
226 if (!this->start_measurement_()) {
227 return false;
228 } else {
229 ESP_LOGD(TAG, "forced calibration complete");
230 }
231 return true;
232 } else {
233 ESP_LOGE(TAG, "force calibration failed");
234 this->error_code_ = FRC_FAILED;
235 this->status_set_warning();
236 return false;
237 }
238 });
239 return true;
240}
241
243 if (!this->write_command(SCD4X_CMD_STOP_MEASUREMENTS)) {
244 ESP_LOGE(TAG, "Failed to stop measurements");
245 this->status_set_warning();
246 return false;
247 }
248
249 this->set_timeout(500, [this]() {
250 if (!this->write_command(SCD4X_CMD_FACTORY_RESET)) {
251 ESP_LOGE(TAG, "Failed to send factory reset command");
252 this->status_set_warning();
253 return false;
254 }
255 ESP_LOGD(TAG, "Factory reset complete");
256 return true;
257 });
258 return true;
259}
260
263 uint16_t new_ambient_pressure = (uint16_t) pressure_in_hpa;
264 if (!initialized_) {
265 ambient_pressure_ = new_ambient_pressure;
266 return;
267 }
268 // Only send pressure value if it has changed since last update
269 if (new_ambient_pressure != ambient_pressure_) {
270 update_ambient_pressure_compensation_(new_ambient_pressure);
271 ambient_pressure_ = new_ambient_pressure;
272 } else {
273 ESP_LOGD(TAG, "ambient pressure compensation skipped - no change required");
274 }
275}
276
278 if (this->write_command(SCD4X_CMD_AMBIENT_PRESSURE_COMPENSATION, pressure_in_hpa)) {
279 ESP_LOGD(TAG, "setting ambient pressure compensation to %d hPa", pressure_in_hpa);
280 return true;
281 } else {
282 ESP_LOGE(TAG, "Error setting ambient pressure compensation.");
283 return false;
284 }
285}
286
288 uint16_t measurement_command = SCD4X_CMD_START_CONTINUOUS_MEASUREMENTS;
289 switch (this->measurement_mode_) {
290 case PERIODIC:
291 measurement_command = SCD4X_CMD_START_CONTINUOUS_MEASUREMENTS;
292 break;
294 measurement_command = SCD4X_CMD_START_LOW_POWER_CONTINUOUS_MEASUREMENTS;
295 break;
296 case SINGLE_SHOT:
297 measurement_command = SCD4X_CMD_START_LOW_POWER_SINGLE_SHOT;
298 break;
300 measurement_command = SCD4X_CMD_START_LOW_POWER_SINGLE_SHOT_RHT_ONLY;
301 break;
302 }
303
304 static uint8_t remaining_retries = 3;
305 while (remaining_retries) {
306 if (!this->write_command(measurement_command)) {
307 ESP_LOGE(TAG, "Error starting measurements.");
309 this->status_set_warning();
310 if (--remaining_retries == 0)
311 return false;
312 delay(50); // NOLINT wait 50 ms and try again
313 }
314 this->status_clear_warning();
315 return true;
316 }
317 return false;
318}
319
320} // namespace scd4x
321} // namespace esphome
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
void status_set_warning(const char *message="unspecified")
void status_clear_warning()
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
const StringRef & get_name() const
constexpr const char * c_str() const
Definition string_ref.h:69
sensor::Sensor * humidity_sensor_
Definition scd4x.h:55
bool update_ambient_pressure_compensation_(uint16_t pressure_in_hpa)
Definition scd4x.cpp:277
sensor::Sensor * ambient_pressure_source_
Definition scd4x.h:57
bool perform_forced_calibration(uint16_t current_co2_concentration)
Definition scd4x.cpp:209
sensor::Sensor * temperature_sensor_
Definition scd4x.h:54
MeasurementMode measurement_mode_
Definition scd4x.h:52
sensor::Sensor * co2_sensor_
Definition scd4x.h:53
void set_ambient_pressure_compensation(float pressure_in_hpa)
Definition scd4x.cpp:261
void dump_config() override
Definition scd4x.cpp:93
bool get_register(uint16_t command, uint16_t *data, uint8_t len, uint8_t delay=0)
get data words from i2c register.
bool write_command(T i2c_register)
Write a command to the i2c device.
bool read_data(uint16_t *data, uint8_t len)
Read data words from i2c device.
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:39
float state
This member variable stores the last state that has passed through all filters.
Definition sensor.h:136
@ COMMUNICATION_FAILED
Definition scd4x.h:12
@ SERIAL_NUMBER_IDENTIFICATION_FAILED
Definition scd4x.h:13
@ MEASUREMENT_INIT_FAILED
Definition scd4x.h:14
@ SINGLE_SHOT_RHT_ONLY
Definition scd4x.h:18
@ LOW_POWER_PERIODIC
Definition scd4x.h:18
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint16_t temperature
Definition sun_gtil2.cpp:12
uint8_t pressure
Definition tt21100.cpp:7