ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
mt6701_spi.cpp
Go to the documentation of this file.
1#include "mt6701_spi.h"
3#include "esphome/core/log.h"
4
5namespace esphome::mt6701_spi {
6
7ESPHOME_LOG_TAG(TAG, "mt6701_spi");
8
9// The 6-bit CRC (x^6 + x + 1) over 18 bits is crc8 with the polynomial shifted up by two
10static constexpr uint8_t CRC6_AS_CRC8_POLY = 0x0C;
11
12bool decode_frame(const uint8_t frame[3], uint16_t &count, uint8_t &status) {
13 if (crc8(frame, 3, 0x00, CRC6_AS_CRC8_POLY, true) != 0)
14 return false;
15 const uint32_t bits = encode_uint24(frame[0], frame[1], frame[2]);
16 count = bits >> 10;
17 status = (bits >> 6) & 0x0F;
18 return true;
19}
20
21ProbeResult probe_result(uint8_t valid_frames, bool any_nonzero) {
22 if (valid_frames < PROBE_MIN_VALID)
25}
26
28 this->spi_setup();
29 // All-zero frames only warn: an encoder at rest looks like a stuck-low data line
30 uint8_t valid = 0;
31 bool nonzero = false;
32 for (uint8_t i = 0; i < PROBE_FRAMES && (valid < PROBE_MIN_VALID || !nonzero); i++) {
33 uint16_t count;
34 if (this->read_count(count)) {
35 valid++;
36 nonzero |= count != 0 || this->status_ != 0;
37 }
38 }
39 switch (probe_result(valid, nonzero)) {
41 this->mark_failed(LOG_STR("no valid frame received, check the wiring and CS pin"));
42 break;
44 ESP_LOGW(TAG, "Every frame read zero: the data line may be stuck low");
45 break;
47 break;
48 }
49}
50
52 ESP_LOGCONFIG(TAG, "MT6701 (SSI/SPI):");
53 LOG_PIN(" CS Pin: ", this->cs_);
54 if (this->is_failed()) {
55 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
56 }
57}
58
60 uint8_t buffer[3] = {0, 0, 0};
61 this->enable();
62 this->read_array(buffer, 3);
63 this->disable();
64 return decode_frame(buffer, count, this->status_);
65}
66
67} // namespace esphome::mt6701_spi
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:274
bool read_count(uint16_t &count) override
unsigned count
Definition gif.cpp:51
uint32_t buffer
Definition gif.cpp:50
ESPHOME_LOG_TAG(TAG, "mt6701_spi.binary_sensor")
bool decode_frame(const uint8_t frame[3], uint16_t &count, uint8_t &status)
Decode a 24-bit SSI frame (14-bit angle, 4 status bits, 6-bit CRC); false when the CRC fails.
ProbeResult probe_result(uint8_t valid_frames, bool any_nonzero)
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition helpers.h:1002
uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc, uint8_t poly, bool msb_first)
Calculate a CRC-8 checksum of data with size len.
Definition helpers.cpp:68
bool valid
static void uint32_t