9#include <esp_heap_caps.h>
11#include <soc/soc_caps.h>
23static constexpr uint16_t CMD_NULL = 0x0000;
24static constexpr uint16_t CMD_RREG = 0xA000;
25static constexpr uint16_t CMD_WREG = 0x6000;
26static constexpr uint8_t REG_ADDRESS_SHIFT = 7;
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;
35static constexpr uint16_t ID_FAMILY = 0x2;
37static constexpr uint16_t STATUS_RESET = 1 << 10;
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;
44static constexpr size_t WORD_BYTES = 3;
45static constexpr size_t MAX_FRAME_BYTES = (2 + MAX_CHANNELS) * WORD_BYTES;
47static constexpr uint32_t FIFO_DEPTH = 2;
48#if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE
50static constexpr size_t DMA_ALIGNMENT = CONFIG_CACHE_L1_CACHE_LINE_SIZE;
54static constexpr size_t DMA_ALIGNMENT = 4;
57static constexpr float CODE_FULL_SCALE = 8388608.0f;
58static constexpr float INTERNAL_REFERENCE_V = 1.2f;
59static constexpr uint16_t CRC_INIT = 0xFFFF;
60static constexpr uint16_t CRC_CCITT_POLY = 0x1021;
62static constexpr uint32_t TASK_STACK_SIZE = 4096;
63static constexpr UBaseType_t TASK_PRIORITY = 5;
64#if CONFIG_FREERTOS_UNICORE
65static constexpr BaseType_t TASK_CORE = tskNO_AFFINITY;
68static constexpr BaseType_t TASK_CORE = 1;
70static constexpr uint32_t MIN_DRDY_TIMEOUT_MS = 20;
71static constexpr uint32_t RESET_LOW_MS = 10;
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;
79static constexpr uint32_t OVERLOAD_BACKOFF_MS = 50;
82static constexpr uint8_t RATE_AVERAGE_CHECKS = 10;
84static constexpr float RATE_DEGRADED_FRACTION = 0.95f;
91 this->
transfer_bytes_ = (frame_bytes + DMA_ALIGNMENT - 1) / DMA_ALIGNMENT * DMA_ALIGNMENT;
93 heap_caps_aligned_calloc(DMA_ALIGNMENT, 1, this->
transfer_bytes_, MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL));
95 this->
mark_failed(LOG_STR(
"Failed to allocate the frame buffer"));
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"));
122 " Sample rate: %.1f SPS\n"
123 " Window: %" PRIu32
" ms",
126 LOG_PIN(
" CS Pin: ", this->
cs_);
135 return INTERNAL_REFERENCE_V / float(1u << this->
gain_codes_[channel]);
139 taskENTER_CRITICAL(&this->
lock_);
141 taskEXIT_CRITICAL(&this->
lock_);
148 this->last_health_check_ = now;
157 const float rate = float(frames - this->
last_frames_) * 1000.0f / float(elapsed);
161 this->last_crc_errors_ = crc_errors;
162 this->last_device_resets_ = device_resets;
164 if (new_crc_errors > 0) {
165 ESP_LOGW(TAG,
"%" PRIu32
" frames dropped due to CRC errors (total %" PRIu32
")", new_crc_errors, crc_errors);
167 if (new_resets > 0) {
168 ESP_LOGW(TAG,
"Unexpected device reset detected, reconfiguring (total %" PRIu32
")", device_resets);
173 const bool was_healthy = this->
healthy_.exchange(healthy) != 0;
175 if (healthy && !was_healthy) {
176 ESP_LOGI(TAG,
"Sampling at %.0f SPS", rate);
180 ESP_LOGW(TAG,
"No data from ADC (%.0f SPS)", rate);
186 if (elapsed_ms == 0) {
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;
200 ESP_LOGW(TAG,
"Sampling at %.0f of %.0f SPS: conversions are being lost", rate, this->
sample_rate_);
202 ESP_LOGI(TAG,
"Sampling at %.0f SPS again", rate);
215 BaseType_t woken = pdFALSE;
217 portYIELD_FROM_ISR(woken);
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) {
242 if (response !=
nullptr) {
245 if (samples !=
nullptr) {
247 const uint8_t *word = &buf[(1 + ch) * WORD_BYTES];
255 for (
uint32_t i = 0; i < FIFO_DEPTH; i++) {
261 taskENTER_CRITICAL(&this->
lock_);
263 taskEXIT_CRITICAL(&this->
lock_);
275 ESP_LOGD(TAG,
"Register 0x%02X: write failed (CRC)",
address);
278 uint16_t readback = 0;
280 ESP_LOGD(TAG,
"Register 0x%02X: readback failed (CRC)",
address);
283 if (readback !=
value) {
284 ESP_LOGD(TAG,
"Register 0x%02X: wrote 0x%04X, read back 0x%04X",
address,
value, readback);
292 vTaskDelay(pdMS_TO_TICKS(STARTUP_DELAY_MS));
298 return LOG_STR(
"no valid response from device (CRC)");
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");
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) |
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) {
322 if (this->num_channels_ > GAIN_CHANNELS_PER_REGISTER) {
326 return LOG_STR(
"register write not verified by readback");
328 ESP_LOGD(TAG,
"Configured (chip ID 0x%04X)",
id);
337 std::array<int64_t, MAX_CHANNELS> sum{};
339 std::array<uint64_t, MAX_CHANNELS> sum_sq{};
340 std::array<int32_t, MAX_CHANNELS> samples{};
343 uint32_t consecutive_crc_errors = 0;
346 bool configured =
false;
349 auto restart_window = [&]() {
361 if (error !=
nullptr) {
363 if (failed_attempts++ == 0) {
364 ESP_LOGW(TAG,
"Configuration failed: %s; retrying every %" PRIu32
" ms", LOG_STR_ARG(error), RETRY_DELAY_MS);
366 ESP_LOGD(TAG,
"Configuration failed: %s", LOG_STR_ARG(error));
368 vTaskDelay(pdMS_TO_TICKS(RETRY_DELAY_MS));
371 if (failed_attempts > 0) {
372 ESP_LOGI(TAG,
"Configured after %" PRIu32
" failed attempts", failed_attempts);
378 consecutive_timeouts = 0;
379 consecutive_crc_errors = 0;
382 ulTaskNotifyTake(pdTRUE, 0);
387 uint32_t pending = ulTaskNotifyTake(pdTRUE, 0);
391 pending = ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(drdy_timeout_ms));
392 }
else if (
millis() - busy_since > OVERLOAD_BACKOFF_MS) {
401 if (++consecutive_timeouts >= MAX_CONSECUTIVE_TIMEOUTS) {
402 ESP_LOGW(TAG,
"DRDY not toggling, reconfiguring");
407 consecutive_timeouts = 0;
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) {
420 consecutive_crc_errors = 0;
422 if (
status & STATUS_RESET) {
429 this->
frames_.store(this->
frames_.load(std::memory_order_relaxed) + 1, std::memory_order_relaxed);
431 sum[ch] += samples[ch];
432 sum_sq[ch] += uint64_t(int64_t(samples[ch]) * samples[ch]);
434 if (++
count < window_samples) {
440 const float volts_per_code = this->
get_full_scale(ch) / CODE_FULL_SCALE;
441 const double mean = double(sum[ch]) /
count;
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;
454 taskENTER_CRITICAL(&this->
lock_);
456 taskEXIT_CRITICAL(&this->
lock_);
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.
void status_set_warning()
bool status_has_warning() const
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
void status_clear_warning()
TaskHandle_t get_handle() const
Get the FreeRTOS task handle.
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...
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,...
uint32_t last_device_resets_
void dump_config() override
std::atomic< uint32_t > device_resets_
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_
static void task_entry(void *arg)
uint8_t * frame_buf_
DMA-capable, allocated once in setup()
uint32_t rate_elapsed_ms_
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_
size_t frame_bytes_() const
ADS131M0xPowerMode power_mode_
InternalGPIOPin * drdy_pin_
size_t transfer_bytes_
Frame length, padded where the DMA requires it.
uint32_t last_crc_errors_
uint32_t rate_start_frames_
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_
bool write_register_(uint8_t address, uint16_t value)
static void drdy_isr(ADS131M0x *self)
std::atomic< uint8_t > configured_
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_
uint32_t window_sequence_
bool read_register_(uint8_t address, uint16_t *value)
uint32_t last_health_check_
std::atomic< uint32_t > frames_
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
bool digital_read() override
void spi_setup() override
void transfer_array(uint8_t *data, size_t length)
PROGMEM_STRING_TABLE(PowerModeStrings, "very low power", "low power", "high resolution", "unknown")
ESPHOME_LOG_TAG(TAG, "ads131m0x")
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.
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
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...
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...
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.
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
uint32_t IRAM_ATTR HOT millis()
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.
Result of one measurement window, in volts at the ADC input.
uint32_t sequence
Incremented with every completed window; 0 = no valid data.