ESPHome 2026.5.0b1
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
8
9static const char *const TAG = "jsn_sr04t.sensor";
10
12 this->write_byte((this->model_ == AJ_SR04M) ? 0x01 : 0x55);
13 ESP_LOGV(TAG, "Request read out from sensor");
14}
15
17 while (this->available() > 0) {
18 uint8_t data;
19 this->read_byte(&data);
20
21 ESP_LOGV(TAG, "Read byte from sensor: %x", data);
22
23 if (this->buffer_.empty() && data != 0xFF)
24 continue;
25
26 this->buffer_.push_back(data);
27 if (this->buffer_.size() == 4)
28 this->check_buffer_();
29 }
30}
31
33 uint8_t checksum = this->buffer_[0] + this->buffer_[1] + this->buffer_[2];
34 if (this->buffer_[3] == checksum) {
35 uint16_t distance = encode_uint16(this->buffer_[1], this->buffer_[2]);
36 if (distance > ((this->model_ == AJ_SR04M) ? 200 : 250)) {
37 float meters = distance / 1000.0f;
38 ESP_LOGV(TAG, "Distance from sensor: %umm, %.3fm", distance, meters);
39 this->publish_state(meters);
40 } else {
41 char hex_buf[format_hex_pretty_size(4)];
42 ESP_LOGW(TAG, "Invalid data read from sensor: %s",
43 format_hex_pretty_to(hex_buf, this->buffer_.data(), this->buffer_.size()));
44 }
45 } else {
46 ESP_LOGW(TAG, "checksum failed: %02x != %02x", checksum, this->buffer_[3]);
47 }
48 this->buffer_.clear();
49}
50
52 LOG_SENSOR("", "JST_SR04T Sensor", this);
53 switch (this->model_) {
54 case JSN_SR04T:
55 ESP_LOGCONFIG(TAG, " sensor model: jsn_sr04t");
56 break;
57 case AJ_SR04M:
58 ESP_LOGCONFIG(TAG, " sensor model: aj_sr04m");
59 break;
60 }
61 LOG_UPDATE_INTERVAL(this);
62}
63
64} // namespace esphome::jsn_sr04t
uint8_t checksum
Definition bl0906.h:3
std::vector< uint8_t > buffer_
Definition jsn_sr04t.h:29
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
bool read_byte(uint8_t *data)
Definition uart.h:34
void write_byte(uint8_t data)
Definition uart.h:18
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:341
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:1386
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:859