ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
ads131m0x.cpp
Go to the documentation of this file.
1#include "ads131m0x.h"
2
3#ifdef USE_ESP32
4
5#include <algorithm>
6#include <cmath>
7#include <cstring>
8
9#include <esp_heap_caps.h>
10#include <sdkconfig.h>
11#include <soc/soc_caps.h>
12
15#include "esphome/core/log.h"
17
19
20ESPHOME_LOG_TAG(TAG, "ads131m0x");
21
22// Commands, 16 bit, left-aligned in a 24-bit word
23static constexpr uint16_t CMD_NULL = 0x0000;
24static constexpr uint16_t CMD_RREG = 0xA000; // 101a aaaa annn nnnn
25static constexpr uint16_t CMD_WREG = 0x6000; // 011a aaaa annn nnnn
26static constexpr uint8_t REG_ADDRESS_SHIFT = 7;
27
28static constexpr uint8_t REG_ID = 0x00;
29static constexpr uint8_t REG_MODE = 0x02;
30static constexpr uint8_t REG_CLOCK = 0x03;
31static constexpr uint8_t REG_GAIN1 = 0x04;
32static constexpr uint8_t REG_GAIN2 = 0x05;
33
34// ID: bits 15:12 = 0010, bits 11:8 = channel count
35static constexpr uint16_t ID_FAMILY = 0x2;
36// STATUS.RESET is set after power-up or any device reset and cleared by writing MODE.RESET = 0
37static constexpr uint16_t STATUS_RESET = 1 << 10;
38// MODE: 24-bit words, CCITT output CRC, no input CRC, RESET flag cleared, SPI timeout on, DRDY active low
39static constexpr uint16_t MODE_VALUE = 0x0110;
40static constexpr uint8_t CLOCK_CH_EN_SHIFT = 8;
41static constexpr uint8_t CLOCK_OSR_SHIFT = 2;
42static constexpr uint8_t GAIN_CHANNELS_PER_REGISTER = 4;
43
44static constexpr size_t WORD_BYTES = 3;
45static constexpr size_t MAX_FRAME_BYTES = (2 + MAX_CHANNELS) * WORD_BYTES; // response + channels + CRC
46// Conversions the chip buffers per channel (datasheet 8.5.1.9.1)
47static constexpr uint32_t FIFO_DEPTH = 2;
48#if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE
49// Internal RAM is cached (ESP32-P4): pad the receive buffer to a full cache line.
50static constexpr size_t DMA_ALIGNMENT = CONFIG_CACHE_L1_CACHE_LINE_SIZE;
51#else
52// The SPI DMA writes whole 32-bit words, and older ESP-IDF versions bounce receive buffers whose length is not a
53// multiple of 4 through a temporary allocation for every transfer.
54static constexpr size_t DMA_ALIGNMENT = 4;
55#endif
56// Padding must match DMA_ALIGNMENT_BYTES in __init__.py; the chip accepts frames longer than needed.
57static constexpr float CODE_FULL_SCALE = 8388608.0f; // 2^23
58static constexpr float INTERNAL_REFERENCE_V = 1.2f;
59static constexpr uint16_t CRC_INIT = 0xFFFF;
60static constexpr uint16_t CRC_CCITT_POLY = 0x1021;
61
62static constexpr uint32_t TASK_STACK_SIZE = 4096;
63static constexpr UBaseType_t TASK_PRIORITY = 5; // above the main loop task (1)
64#if CONFIG_FREERTOS_UNICORE
65static constexpr BaseType_t TASK_CORE = tskNO_AFFINITY;
66#else
67// The network stack runs on core 0 at priorities up to 18 and would delay the task past the two-sample FIFO.
68static constexpr BaseType_t TASK_CORE = 1;
69#endif
70static constexpr uint32_t MIN_DRDY_TIMEOUT_MS = 20;
71static constexpr uint32_t RESET_LOW_MS = 10; // > 2048 CLKIN periods at the 0.3 MHz minimum clock (6.8 ms)
72static constexpr uint32_t STARTUP_DELAY_MS = 10;
73static constexpr uint32_t RETRY_DELAY_MS = 1000;
74static constexpr uint32_t MAX_CONSECUTIVE_TIMEOUTS = 50;
75static constexpr uint32_t MAX_CONSECUTIVE_CRC_ERRORS = 50;
76static constexpr uint32_t HEALTH_CHECK_INTERVAL_MS = 1000;
77// When conversions keep arriving faster than they are read, the task never blocks. After this long without waiting
78// for DRDY it blocks for one tick, so lower-priority tasks on its core (e.g. the main loop) are not starved.
79static constexpr uint32_t OVERLOAD_BACKOFF_MS = 50;
80// The sample rate is averaged over this many health checks before it is compared with the nominal rate, so a
81// single blocked loop iteration does not skew it.
82static constexpr uint8_t RATE_AVERAGE_CHECKS = 10;
83// Below this fraction of the nominal rate, conversions are being lost (e.g. too many fast devices on one bus).
84static constexpr float RATE_DEGRADED_FRACTION = 0.95f;
85
86// Indexed by ADS131M0xPowerMode; the last entry is the fallback for out-of-range values
87PROGMEM_STRING_TABLE(PowerModeStrings, "very low power", "low power", "high resolution", "unknown");
88
90 const size_t frame_bytes = this->frame_bytes_();
91 this->transfer_bytes_ = (frame_bytes + DMA_ALIGNMENT - 1) / DMA_ALIGNMENT * DMA_ALIGNMENT;
92 this->frame_buf_ = static_cast<uint8_t *>(
93 heap_caps_aligned_calloc(DMA_ALIGNMENT, 1, this->transfer_bytes_, MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL));
94 if (this->frame_buf_ == nullptr) {
95 this->mark_failed(LOG_STR("Failed to allocate the frame buffer"));
96 return;
97 }
98
99 this->spi_setup();
100 if (!this->spi_is_ready()) {
101 this->mark_failed(LOG_STR("SPI bus not ready"));
102 return;
103 }
104 this->drdy_pin_->setup();
105 setup_output_pin(this->reset_pin_, true);
106
107 if (!this->task_.create(task_entry, "ads131m0x", TASK_STACK_SIZE, this, TASK_PRIORITY, false, TASK_CORE)) {
108 this->mark_failed(LOG_STR("Failed to create sampling task"));
109 return;
110 }
112
113 this->last_health_check_ = millis();
114 this->set_interval(HEALTH_CHECK_INTERVAL_MS, [this]() { this->check_health_(); });
115}
116
118 ESP_LOGCONFIG(TAG,
119 "ADS131M0x:\n"
120 " Channels: %u\n"
121 " Power mode: %s\n"
122 " Sample rate: %.1f SPS\n"
123 " Window: %" PRIu32 " ms",
124 this->num_channels_, LOG_STR_ARG(PowerModeStrings::get_log_str(this->power_mode_)), this->sample_rate_,
125 this->window_ms_);
126 LOG_PIN(" CS Pin: ", this->cs_);
127 LOG_PIN(" DRDY Pin: ", this->drdy_pin_);
128 LOG_PIN(" RESET Pin: ", this->reset_pin_);
129 for (uint8_t ch = 0; ch < this->num_channels_; ch++) {
130 ESP_LOGCONFIG(TAG, " CH%u: gain %u (+/-%.4f V)", ch, 1u << this->gain_codes_[ch], this->get_full_scale(ch));
131 }
132}
133
134float ADS131M0x::get_full_scale(uint8_t channel) const {
135 return INTERNAL_REFERENCE_V / float(1u << this->gain_codes_[channel]);
136}
137
139 taskENTER_CRITICAL(&this->lock_);
140 Snapshot copy = this->snapshot_;
141 taskEXIT_CRITICAL(&this->lock_);
142 return copy;
143}
144
147 const uint32_t elapsed = now - this->last_health_check_;
148 this->last_health_check_ = now;
149 if (elapsed == 0) {
150 return;
151 }
152
153 const uint32_t frames = this->frames_.load(std::memory_order_relaxed);
154 const uint32_t crc_errors = this->crc_errors_.load(std::memory_order_relaxed);
155 const uint32_t device_resets = this->device_resets_.load(std::memory_order_relaxed);
156 // Measure against real elapsed time: the first check can include slow setup of other components.
157 const float rate = float(frames - this->last_frames_) * 1000.0f / float(elapsed);
158 const uint32_t new_crc_errors = crc_errors - this->last_crc_errors_;
159 const uint32_t new_resets = device_resets - this->last_device_resets_;
160 this->last_frames_ = frames;
161 this->last_crc_errors_ = crc_errors;
162 this->last_device_resets_ = device_resets;
163
164 if (new_crc_errors > 0) {
165 ESP_LOGW(TAG, "%" PRIu32 " frames dropped due to CRC errors (total %" PRIu32 ")", new_crc_errors, crc_errors);
166 }
167 if (new_resets > 0) {
168 ESP_LOGW(TAG, "Unexpected device reset detected, reconfiguring (total %" PRIu32 ")", device_resets);
169 }
170
171 // Tolerate short overload, but a quarter of the nominal rate means sampling is broken.
172 const bool healthy = this->configured_.load() != 0 && rate >= this->sample_rate_ / 4.0f;
173 const bool was_healthy = this->healthy_.exchange(healthy) != 0;
174 this->check_rate_(healthy ? elapsed : 0, frames);
175 if (healthy && !was_healthy) {
176 ESP_LOGI(TAG, "Sampling at %.0f SPS", rate);
177 this->status_clear_warning();
178 } else if (!healthy && (was_healthy || !this->status_has_warning())) {
179 // Also covers a device that never delivered data since boot
180 ESP_LOGW(TAG, "No data from ADC (%.0f SPS)", rate);
181 this->status_set_warning(LOG_STR("No data from ADC"));
182 }
183}
184
185void ADS131M0x::check_rate_(uint32_t elapsed_ms, uint32_t frames) {
186 if (elapsed_ms == 0) {
187 // Not sampling: start the average over once sampling resumes
188 this->rate_checks_ = 0;
189 return;
190 }
191 // The first check only sets the baseline: its elapsed time belongs to frames counted before it.
192 if (this->rate_checks_ > 0) {
193 this->rate_elapsed_ms_ += elapsed_ms;
194 }
195 if (this->rate_checks_ >= RATE_AVERAGE_CHECKS) {
196 const float rate = float(frames - this->rate_start_frames_) * 1000.0f / float(this->rate_elapsed_ms_);
197 ESP_LOGV(TAG, "Sampling at %.1f SPS (average over %" PRIu32 " ms)", rate, this->rate_elapsed_ms_);
198 const bool degraded = rate < this->sample_rate_ * RATE_DEGRADED_FRACTION;
199 if (degraded && !this->rate_degraded_) {
200 ESP_LOGW(TAG, "Sampling at %.0f of %.0f SPS: conversions are being lost", rate, this->sample_rate_);
201 } else if (!degraded && this->rate_degraded_) {
202 ESP_LOGI(TAG, "Sampling at %.0f SPS again", rate);
203 }
204 this->rate_degraded_ = degraded;
205 this->rate_checks_ = 0;
206 }
207 if (this->rate_checks_ == 0) {
208 this->rate_start_frames_ = frames;
209 this->rate_elapsed_ms_ = 0;
210 }
211 this->rate_checks_++;
212}
213
214void IRAM_ATTR ADS131M0x::drdy_isr(ADS131M0x *self) {
215 BaseType_t woken = pdFALSE;
216 vTaskNotifyGiveFromISR(self->task_.get_handle(), &woken);
217 portYIELD_FROM_ISR(woken);
218}
219
220void ADS131M0x::task_entry(void *arg) { static_cast<ADS131M0x *>(arg)->task_loop_(); }
221
222size_t ADS131M0x::frame_bytes_() const { return (2 + this->num_channels_) * WORD_BYTES; }
223
224bool ADS131M0x::transfer_frame_(uint16_t command, uint16_t data, uint16_t *response, int32_t *samples) {
225 uint8_t *buf = this->frame_buf_;
226 const size_t len = this->frame_bytes_();
227 std::memset(buf, 0, this->transfer_bytes_);
228 put_be16(buf, command);
229 put_be16(buf + WORD_BYTES, data);
230
231 this->enable();
232 this->transfer_array(buf, this->transfer_bytes_);
233 this->disable();
234
235 // The output CRC covers every word before the CRC word, including the padding byte of each word.
236 const size_t crc_pos = len - WORD_BYTES;
237 const uint16_t expected = encode_uint16(buf[crc_pos], buf[crc_pos + 1]);
238 if (crc16be(buf, crc_pos, CRC_INIT, CRC_CCITT_POLY) != expected) {
239 return false;
240 }
241
242 if (response != nullptr) {
243 *response = encode_uint16(buf[0], buf[1]);
244 }
245 if (samples != nullptr) {
246 for (uint8_t ch = 0; ch < this->num_channels_; ch++) {
247 const uint8_t *word = &buf[(1 + ch) * WORD_BYTES];
248 samples[ch] = sign_extend<24>(encode_uint24(word[0], word[1], word[2]));
249 }
250 }
251 return true;
252}
253
255 for (uint32_t i = 0; i < FIFO_DEPTH; i++) {
256 this->transfer_frame_(CMD_NULL, 0, nullptr, nullptr);
257 }
258}
259
261 taskENTER_CRITICAL(&this->lock_);
262 this->snapshot_ = Snapshot{};
263 taskEXIT_CRITICAL(&this->lock_);
264}
265
266bool ADS131M0x::read_register_(uint8_t address, uint16_t *value) {
267 // The response to a command arrives in the following frame.
268 return this->transfer_frame_(CMD_RREG | (uint16_t(address) << REG_ADDRESS_SHIFT), 0, nullptr, nullptr) &&
269 this->transfer_frame_(CMD_NULL, 0, value, nullptr);
270}
271
272bool ADS131M0x::write_register_(uint8_t address, uint16_t value) {
273 if (!this->transfer_frame_(CMD_WREG | (uint16_t(address) << REG_ADDRESS_SHIFT), value, nullptr, nullptr) ||
274 !this->transfer_frame_(CMD_NULL, 0, nullptr, nullptr)) {
275 ESP_LOGD(TAG, "Register 0x%02X: write failed (CRC)", address);
276 return false;
277 }
278 uint16_t readback = 0;
279 if (!this->read_register_(address, &readback)) {
280 ESP_LOGD(TAG, "Register 0x%02X: readback failed (CRC)", address);
281 return false;
282 }
283 if (readback != value) {
284 ESP_LOGD(TAG, "Register 0x%02X: wrote 0x%04X, read back 0x%04X", address, value, readback);
285 return false;
286 }
287 return true;
288}
289
290const LogString *ADS131M0x::configure_() {
291 pulse_reset(this->reset_pin_, {.low_ms = RESET_LOW_MS});
292 vTaskDelay(pdMS_TO_TICKS(STARTUP_DELAY_MS));
293 // Discard whatever was pending; its CRC may be invalid after a reset.
294 this->transfer_frame_(CMD_NULL, 0, nullptr, nullptr);
295
296 uint16_t id = 0;
297 if (!this->read_register_(REG_ID, &id)) {
298 return LOG_STR("no valid response from device (CRC)");
299 }
300 if ((id >> 12) != ID_FAMILY || ((id >> 8) & 0x0F) != this->num_channels_) {
301 ESP_LOGD(TAG, "Chip ID 0x%04X, expected a %u-channel model", id, this->num_channels_);
302 return LOG_STR("unexpected chip ID");
303 }
304
305 const uint16_t channel_mask = (1u << this->num_channels_) - 1;
306 const uint16_t clock = (channel_mask << CLOCK_CH_EN_SHIFT) | (uint16_t(this->osr_code_ & 0x07) << CLOCK_OSR_SHIFT) |
307 (this->power_mode_ & 0x03);
308 uint16_t gain1 = 0;
309 uint16_t gain2 = 0;
310 for (uint8_t ch = 0; ch < this->num_channels_; ch++) {
311 const uint16_t field = uint16_t(this->gain_codes_[ch] & 0x07) << (4 * (ch % GAIN_CHANNELS_PER_REGISTER));
312 if (ch < GAIN_CHANNELS_PER_REGISTER) {
313 gain1 |= field;
314 } else {
315 gain2 |= field;
316 }
317 }
318
319 bool ok = this->write_register_(REG_MODE, MODE_VALUE);
320 ok = ok && this->write_register_(REG_CLOCK, clock);
321 ok = ok && this->write_register_(REG_GAIN1, gain1);
322 if (this->num_channels_ > GAIN_CHANNELS_PER_REGISTER) {
323 ok = ok && this->write_register_(REG_GAIN2, gain2);
324 }
325 if (!ok) {
326 return LOG_STR("register write not verified by readback");
327 }
328 ESP_LOGD(TAG, "Configured (chip ID 0x%04X)", id);
329 return nullptr;
330}
331
333 const uint32_t window_samples =
334 std::max<uint32_t>(1, uint32_t(std::lround(this->sample_rate_ * float(this->window_ms_) / 1000.0f)));
335 const uint32_t drdy_timeout_ms =
336 std::max<uint32_t>(MIN_DRDY_TIMEOUT_MS, uint32_t(std::ceil(4000.0f / this->sample_rate_)));
337 std::array<int64_t, MAX_CHANNELS> sum{};
338 // A square is never negative; unsigned keeps a full window of -2^23 codes (2^63) representable
339 std::array<uint64_t, MAX_CHANNELS> sum_sq{};
340 std::array<int32_t, MAX_CHANNELS> samples{};
341 uint32_t count = 0;
342 uint32_t consecutive_timeouts = 0;
343 uint32_t consecutive_crc_errors = 0;
344 uint32_t failed_attempts = 0;
345 uint32_t busy_since = millis();
346 bool configured = false;
347
348 // A window only holds consecutive conversions; after a gap it starts over.
349 auto restart_window = [&]() {
350 count = 0;
351 sum.fill(0);
352 sum_sq.fill(0);
353 };
354
355 while (true) {
356 if (!configured) {
357 // Readings from before the reconfiguration must not be published as current
358 this->invalidate_snapshot_();
359 this->configured_.store(false);
360 const LogString *error = this->configure_();
361 if (error != nullptr) {
362 // Warn once; a missing or miswired chip would otherwise log a warning every retry
363 if (failed_attempts++ == 0) {
364 ESP_LOGW(TAG, "Configuration failed: %s; retrying every %" PRIu32 " ms", LOG_STR_ARG(error), RETRY_DELAY_MS);
365 } else {
366 ESP_LOGD(TAG, "Configuration failed: %s", LOG_STR_ARG(error));
367 }
368 vTaskDelay(pdMS_TO_TICKS(RETRY_DELAY_MS));
369 continue;
370 }
371 if (failed_attempts > 0) {
372 ESP_LOGI(TAG, "Configured after %" PRIu32 " failed attempts", failed_attempts);
373 failed_attempts = 0;
374 }
375 configured = true;
376 this->configured_.store(true);
377 restart_window();
378 consecutive_timeouts = 0;
379 consecutive_crc_errors = 0;
380 // Conversions ran unread during configuration: empty the FIFO, then follow DRDY from the next one. Clear the
381 // stale notifications first, so a conversion completing during the drain still wakes the task.
382 ulTaskNotifyTake(pdTRUE, 0);
383 this->drain_fifo_();
384 continue;
385 }
386
387 uint32_t pending = ulTaskNotifyTake(pdTRUE, 0);
388 if (pending == 0) {
389 // About to block: the task is keeping up
390 busy_since = millis();
391 pending = ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(drdy_timeout_ms));
392 } else if (millis() - busy_since > OVERLOAD_BACKOFF_MS) {
393 // Overloaded: conversions are lost either way, the health check reports the lower rate
394 vTaskDelay(1);
395 busy_since = millis();
396 }
397 if (pending == 0) {
398 // A full FIFO holds DRDY low, so no falling edge follows; reading both slots releases it.
399 this->drain_fifo_();
400 restart_window();
401 if (++consecutive_timeouts >= MAX_CONSECUTIVE_TIMEOUTS) {
402 ESP_LOGW(TAG, "DRDY not toggling, reconfiguring");
403 configured = false;
404 }
405 continue;
406 }
407 consecutive_timeouts = 0;
408
409 // DRDY stays low while a conversion is buffered. Follow its level rather than counting edges: reading the
410 // first of two buffered conversions makes a short DRDY pulse, which would count as an extra edge.
411 for (uint32_t i = 0; i < FIFO_DEPTH && configured && !this->drdy_pin_->digital_read(); i++) {
412 uint16_t status = 0;
413 if (!this->transfer_frame_(CMD_NULL, 0, &status, samples.data())) {
414 this->crc_errors_.store(this->crc_errors_.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed);
415 if (++consecutive_crc_errors >= MAX_CONSECUTIVE_CRC_ERRORS) {
416 configured = false;
417 }
418 continue;
419 }
420 consecutive_crc_errors = 0;
421
422 if (status & STATUS_RESET) {
423 // Registers are back at their defaults (gain 1, default data rate): this window is invalid.
424 this->device_resets_.store(this->device_resets_.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed);
425 configured = false;
426 continue;
427 }
428
429 this->frames_.store(this->frames_.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed);
430 for (uint8_t ch = 0; ch < this->num_channels_; ch++) {
431 sum[ch] += samples[ch];
432 sum_sq[ch] += uint64_t(int64_t(samples[ch]) * samples[ch]);
433 }
434 if (++count < window_samples) {
435 continue;
436 }
437
439 for (uint8_t ch = 0; ch < this->num_channels_; ch++) {
440 const float volts_per_code = this->get_full_scale(ch) / CODE_FULL_SCALE;
441 const double mean = double(sum[ch]) / count;
442 // AC RMS = sqrt(E[x^2] - E[x]^2): removes the DC offset of the input
443 const double variance = double(sum_sq[ch]) / count - mean * mean;
444 result.mean[ch] = float(mean) * volts_per_code;
445 result.rms[ch] = variance > 0 ? float(std::sqrt(variance)) * volts_per_code : 0.0f;
446 }
447 restart_window();
448 result.timestamp_ms = millis();
449 if (++this->window_sequence_ == 0) {
450 this->window_sequence_ = 1; // 0 means "no valid data"
451 }
452 result.sequence = this->window_sequence_;
453
454 taskENTER_CRITICAL(&this->lock_);
455 this->snapshot_ = result;
456 taskEXIT_CRITICAL(&this->lock_);
457 }
458 }
459}
460
461} // namespace esphome::ads131m0x
462
463#endif // USE_ESP32
uint8_t status
Definition bl0942.h:8
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool status_has_warning() const
Definition component.h:293
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
void status_clear_warning()
Definition component.h:317
TaskHandle_t get_handle() const
Get the FreeRTOS task handle.
Definition static_task.h:31
bool create(TaskFunction_t fn, const char *name, uint32_t stack_size, void *param, UBaseType_t priority, bool use_psram, BaseType_t core_id=tskNO_AFFINITY)
Allocate the TCB (always internal RAM) and the stack, then create the task.
TI ADS131M02/04/08 simultaneous-sampling 24-bit delta-sigma ADC (https://www.ti.com/lit/ds/symlink/ad...
Definition ads131m0x.h:40
void drain_fifo_()
Reads both FIFO slots back to back, as the datasheet requires after a gap in reading.
const LogString * configure_()
Resets (if a reset pin is set) and configures the device. Returns nullptr on success,...
std::atomic< uint32_t > device_resets_
Definition ads131m0x.h:106
void check_rate_(uint32_t elapsed_ms, uint32_t frames)
Averages the sample rate over several health checks and warns when conversions are being lost.
InternalGPIOPin * reset_pin_
Definition ads131m0x.h:84
static void task_entry(void *arg)
uint8_t * frame_buf_
DMA-capable, allocated once in setup()
Definition ads131m0x.h:95
void invalidate_snapshot_()
Marks the snapshot as invalid (sequence 0) until a full window has been sampled again.
bool transfer_frame_(uint16_t command, uint16_t data, uint16_t *response, int32_t *samples)
Clocks one full frame. Returns false on an output CRC mismatch. response receives the first word.
std::atomic< uint8_t > healthy_
Definition ads131m0x.h:102
ADS131M0xPowerMode power_mode_
Definition ads131m0x.h:86
InternalGPIOPin * drdy_pin_
Definition ads131m0x.h:83
size_t transfer_bytes_
Frame length, padded where the DMA requires it.
Definition ads131m0x.h:96
float get_full_scale(uint8_t channel) const
Input full scale of a channel in volts (the input range is +/- this value).
std::atomic< uint32_t > crc_errors_
Definition ads131m0x.h:105
bool write_register_(uint8_t address, uint16_t value)
static void drdy_isr(ADS131M0x *self)
std::atomic< uint8_t > configured_
Definition ads131m0x.h:103
Snapshot get_snapshot()
Copy of the latest completed window; sequence is 0 until the first window after (re)configuration.
std::array< uint8_t, MAX_CHANNELS > gain_codes_
Definition ads131m0x.h:90
bool read_register_(uint8_t address, uint16_t *value)
std::atomic< uint32_t > frames_
Definition ads131m0x.h:104
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
Definition gpio.h:32
unsigned count
Definition gif.cpp:51
PROGMEM_STRING_TABLE(PowerModeStrings, "very low power", "low power", "high resolution", "unknown")
ESPHOME_LOG_TAG(TAG, "ads131m0x")
@ INTERRUPT_FALLING_EDGE
Definition gpio_pin.h:53
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition helpers.h:1203
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:154
constexpr uint8_t * put_be16(uint8_t *dst, uint16_t value)
Write the low 16, 24 or 32 bits of value to dst, most significant byte first (be) or least significan...
Definition helpers.h:1268
constexpr int32_t sign_extend(uint32_t value)
Sign-extend the low BITS bits of value, e.g. sign_extend<24>(0xFFFFFE) == -2. Higher bits are ignored...
Definition helpers.h:1213
void setup_output_pin(GPIOPin *pin, bool level)
Set up pin and drive it to level. Does nothing when pin is null, so an optional pin needs no check.
Definition gpio.cpp:43
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1199
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
ESPHOME_ALWAYS_INLINE void pulse_reset(GPIOPin *pin, ResetPulse pulse)
Set up an active-low reset pin and drive it through pulse.
Definition gpio_pin.h:214
static void uint32_t
Result of one measurement window, in volts at the ADC input.
Definition ads131m0x.h:28
uint32_t sequence
Incremented with every completed window; 0 = no valid data.
Definition ads131m0x.h:31
esp_err_t result