ESPHome  2023.11.6
a01nyub.cpp
Go to the documentation of this file.
1 // Datasheet https://wiki.dfrobot.com/A01NYUB%20Waterproof%20Ultrasonic%20Sensor%20SKU:%20SEN0313
2 
3 #include "a01nyub.h"
4 #include "esphome/core/helpers.h"
5 #include "esphome/core/log.h"
6 
7 namespace esphome {
8 namespace a01nyub {
9 
10 static const char *const TAG = "a01nyub.sensor";
11 static const uint8_t MAX_DATA_LENGTH_BYTES = 4;
12 
14  uint8_t data;
15  while (this->available() > 0) {
16  if (this->read_byte(&data)) {
17  buffer_.push_back(data);
18  this->check_buffer_();
19  }
20  }
21 }
22 
24  if (this->buffer_.size() >= MAX_DATA_LENGTH_BYTES) {
25  size_t i;
26  for (i = 0; i < this->buffer_.size(); i++) {
27  // Look for the first packet
28  if (this->buffer_[i] == 0xFF) {
29  if (i + 1 + 3 < this->buffer_.size()) { // Packet is not complete
30  return; // Wait for completion
31  }
32 
33  uint8_t checksum = (this->buffer_[i] + this->buffer_[i + 1] + this->buffer_[i + 2]) & 0xFF;
34  if (this->buffer_[i + 3] == checksum) {
35  float distance = (this->buffer_[i + 1] << 8) + this->buffer_[i + 2];
36  if (distance > 280) {
37  float meters = distance / 1000.0;
38  ESP_LOGV(TAG, "Distance from sensor: %f mm, %f m", distance, meters);
39  this->publish_state(meters);
40  } else {
41  ESP_LOGW(TAG, "Invalid data read from sensor: %s", format_hex_pretty(this->buffer_).c_str());
42  }
43  }
44  break;
45  }
46  }
47  this->buffer_.clear();
48  }
49 }
50 
52  ESP_LOGCONFIG(TAG, "A01nyub Sensor:");
53  LOG_SENSOR(" ", "Distance", this);
54 }
55 
56 } // namespace a01nyub
57 } // 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:350
std::vector< uint8_t > buffer_
Definition: a01nyub.h:23
bool read_byte(uint8_t *data)
Definition: uart.h:29
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
uint8_t checksum
Definition: bl0939.h:35
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7