From d149aaa2d35a6965413f338fdf1d602752e904f8 Mon Sep 17 00:00:00 2001 From: Masterz69 Date: Tue, 2 Apr 2024 18:09:55 +0300 Subject: [PATCH] Create ultrasonic_sensor.cpp --- .../ultrasonic_uart/ultrasonic_sensor.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 esphome/components/ultrasonic_uart/ultrasonic_sensor.cpp diff --git a/esphome/components/ultrasonic_uart/ultrasonic_sensor.cpp b/esphome/components/ultrasonic_uart/ultrasonic_sensor.cpp new file mode 100644 index 0000000000..c683ce6712 --- /dev/null +++ b/esphome/components/ultrasonic_uart/ultrasonic_sensor.cpp @@ -0,0 +1,28 @@ +#include "ultrasonic_sensor.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace ultrasonic_uart { + +static const char *const TAG = "ultrasonic_uart"; + +void UltrasonicSensorComponent_UART::setup() { + ESP_LOGCONFIG(TAG, "Setting up Ultrasonic Sensor..."); +} +void UltrasonicSensorComponent_UART::update() { + this->write(0x55); + while (this->available() == 4) { + auto frame = *this->read_array<4>(); + if ((frame[0] == 0xFF) && (((frame[0] + frame[1] + frame[2]) & 0x00FF) == frame[3])) { + float value = ((frame[1] << 8) + frame[2]) / 10.0; + this->publish_state(value); + } + } +} +void UltrasonicSensorComponent_UART::dump_config() { + LOG_SENSOR("", "Ultrasonic Sensor", this); + LOG_UPDATE_INTERVAL(this); +} +float UltrasonicSensorComponent_UART::get_setup_priority() const { return setup_priority::DATA; } +} // namespace ultrasonic_uart +} // namespace esphome