From 5fec7dcb10f7f2e1d75859eb45eca33586044f19 Mon Sep 17 00:00:00 2001 From: Sam Redfern Date: Mon, 5 May 2025 22:36:58 +1000 Subject: [PATCH] Refactor SEN0590 sensor implementation: update command and data register handling, improve error logging, and enhance distance measurement validation. --- components/sen0590/sen0590.cpp | 35 +++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/components/sen0590/sen0590.cpp b/components/sen0590/sen0590.cpp index 08026c3..3ee84f8 100644 --- a/components/sen0590/sen0590.cpp +++ b/components/sen0590/sen0590.cpp @@ -1,3 +1,4 @@ +#include "sen0590.h" #include "esphome/core/log.h" #include "esphome/core/hal.h" #include "esphome/core/component.h" @@ -8,42 +9,50 @@ namespace esphome { namespace sen0590 { static const char *const TAG = "sen0590"; -static const uint8_t COMMAND_REG = 0x10; -static const uint8_t DATA_REG = 0x02; +static const uint8_t COMMAND_REG = 0x00; +static const uint8_t DATA_REG_HIGH = 0x01; +static const uint8_t DATA_REG_LOW = 0x02; static const uint8_t MEASURE_COMMAND = 0xB0; class SEN0590Component : public sensor::Sensor, public PollingComponent, public i2c::I2CDevice { public: void setup() override { ESP_LOGD(TAG, "Setting up SEN0590 laser distance sensor..."); - // Power-on delay time is ≤800ms according to specs - delay(800); + if (!this->write_byte(COMMAND_REG, 0x00)) { + ESP_LOGE(TAG, "SEN0590 not responding. Check wiring and address."); + this->mark_failed(); + return; + } + ESP_LOGD(TAG, "SEN0590 Setup complete."); } void update() override { - // Send measurement command if (!this->write_byte(COMMAND_REG, MEASURE_COMMAND)) { - ESP_LOGE(TAG, "Failed to write command"); + ESP_LOGW(TAG, "Failed to send measurement command"); this->status_set_warning(); return; } - // Wait for measurement to complete delay(50); - // Read measurement result uint8_t buffer[2]; - if (!this->read_bytes(DATA_REG, buffer, 2)) { - ESP_LOGE(TAG, "Failed to read distance data"); + if (this->read_register(DATA_REG_HIGH, &buffer[0], 1) != i2c::ERROR_OK || + this->read_register(DATA_REG_LOW, &buffer[1], 1) != i2c::ERROR_OK) { + ESP_LOGW(TAG, "Failed to read distance data"); + this->status_set_warning(); + return; + } + + int distance_mm = (buffer[0] << 8) | buffer[1]; + if (distance_mm == 0xFFFF) { + ESP_LOGW(TAG, "Received invalid distance data (0xFFFF)"); this->status_set_warning(); return; } - // Calculate distance in mm and convert to cm - int distance_mm = (buffer[0] << 8) + buffer[1] + 10; float distance_cm = distance_mm / 10.0f; - ESP_LOGD(TAG, "Distance: %.1f cm", distance_cm); + ESP_LOGD(TAG, "Distance: %.1f cm (Raw: %d mm)", distance_cm, distance_mm); this->publish_state(distance_cm); this->status_clear_warning(); }