ESPHome  2024.9.0
jsn_sr04t.cpp
Go to the documentation of this file.
1 #include "jsn_sr04t.h"
2 #include "esphome/core/helpers.h"
3 #include "esphome/core/log.h"
4 
5 // Very basic support for JSN_SR04T V3.0 distance sensor in mode 2
6 
7 namespace esphome {
8 namespace jsn_sr04t {
9 
10 static const char *const TAG = "jsn_sr04t.sensor";
11 
13  this->write_byte(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 = 0;
35  switch (this->model_) {
36  case JSN_SR04T:
37  checksum = this->buffer_[0] + this->buffer_[1] + this->buffer_[2];
38  break;
39  case AJ_SR04M:
40  checksum = this->buffer_[1] + this->buffer_[2];
41  break;
42  }
43 
44  if (this->buffer_[3] == checksum) {
45  uint16_t distance = encode_uint16(this->buffer_[1], this->buffer_[2]);
46  if (distance > 250) {
47  float meters = distance / 1000.0f;
48  ESP_LOGV(TAG, "Distance from sensor: %umm, %.3fm", distance, meters);
49  this->publish_state(meters);
50  } else {
51  ESP_LOGW(TAG, "Invalid data read from sensor: %s", format_hex_pretty(this->buffer_).c_str());
52  }
53  } else {
54  ESP_LOGW(TAG, "checksum failed: %02x != %02x", checksum, this->buffer_[3]);
55  }
56  this->buffer_.clear();
57 }
58 
60  LOG_SENSOR("", "JST_SR04T Sensor", this);
61  switch (this->model_) {
62  case JSN_SR04T:
63  ESP_LOGCONFIG(TAG, " sensor model: jsn_sr04t");
64  break;
65  case AJ_SR04M:
66  ESP_LOGCONFIG(TAG, " sensor model: aj_sr04m");
67  break;
68  }
69  LOG_UPDATE_INTERVAL(this);
70 }
71 
72 } // namespace jsn_sr04t
73 } // namespace esphome
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition: helpers.cpp:361
void write_byte(uint8_t data)
Definition: uart.h:19
uint8_t checksum
Definition: bl0906.h:210
bool read_byte(uint8_t *data)
Definition: uart.h:29
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:39
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:182
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7