ESPHome 2026.1.4
Loading...
Searching...
No Matches
jsn_sr04t.cpp
Go to the documentation of this file.
1#include "jsn_sr04t.h"
3#include "esphome/core/log.h"
4
5// Very basic support for JSN_SR04T V3.0 distance sensor in mode 2
6
7namespace esphome {
8namespace jsn_sr04t {
9
10static const char *const TAG = "jsn_sr04t.sensor";
11
13 this->write_byte((this->model_ == AJ_SR04M) ? 0x01 : 0x55);
14 ESP_LOGV(TAG, "Request read out from sensor");
15}
16
18 while (this->available() > 0) {
19 uint8_t data;
20 this->read_byte(&data);
21
22 ESP_LOGV(TAG, "Read byte from sensor: %x", data);
23
24 if (this->buffer_.empty() && data != 0xFF)
25 continue;
26
27 this->buffer_.push_back(data);
28 if (this->buffer_.size() == 4)
29 this->check_buffer_();
30 }
31}
32
34 uint8_t checksum = this->buffer_[0] + this->buffer_[1] + this->buffer_[2];
35 if (this->buffer_[3] == checksum) {
36 uint16_t distance = encode_uint16(this->buffer_[1], this->buffer_[2]);
37 if (distance > ((this->model_ == AJ_SR04M) ? 200 : 250)) {
38 float meters = distance / 1000.0f;
39 ESP_LOGV(TAG, "Distance from sensor: %umm, %.3fm", distance, meters);
40 this->publish_state(meters);
41 } else {
42 char hex_buf[format_hex_pretty_size(4)];
43 ESP_LOGW(TAG, "Invalid data read from sensor: %s",
44 format_hex_pretty_to(hex_buf, this->buffer_.data(), this->buffer_.size()));
45 }
46 } else {
47 ESP_LOGW(TAG, "checksum failed: %02x != %02x", checksum, this->buffer_[3]);
48 }
49 this->buffer_.clear();
50}
51
53 LOG_SENSOR("", "JST_SR04T Sensor", this);
54 switch (this->model_) {
55 case JSN_SR04T:
56 ESP_LOGCONFIG(TAG, " sensor model: jsn_sr04t");
57 break;
58 case AJ_SR04M:
59 ESP_LOGCONFIG(TAG, " sensor model: aj_sr04m");
60 break;
61 }
62 LOG_UPDATE_INTERVAL(this);
63}
64
65} // namespace jsn_sr04t
66} // namespace esphome
uint8_t checksum
Definition bl0906.h:3
std::vector< uint8_t > buffer_
Definition jsn_sr04t.h:30
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:76
bool read_byte(uint8_t *data)
Definition uart.h:34
void write_byte(uint8_t data)
Definition uart.h:18
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:334
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:830
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:463