ESPHome  2024.12.2
m5stack_8angle.cpp
Go to the documentation of this file.
1 #include "m5stack_8angle.h"
2 #include "esphome/core/hal.h"
3 #include "esphome/core/log.h"
4 
5 namespace esphome {
6 namespace m5stack_8angle {
7 
8 static const char *const TAG = "m5stack_8angle";
9 
11  ESP_LOGCONFIG(TAG, "Setting up M5STACK_8ANGLE...");
12  i2c::ErrorCode err;
13 
14  err = this->read(nullptr, 0);
15  if (err != i2c::NO_ERROR) {
16  ESP_LOGE(TAG, "I2C error %02X...", err);
17  this->mark_failed();
18  return;
19  };
20 
21  err = this->read_register(M5STACK_8ANGLE_REGISTER_FW_VERSION, &this->fw_version_, 1);
22  if (err != i2c::NO_ERROR) {
23  ESP_LOGE(TAG, "I2C error %02X...", err);
24  this->mark_failed();
25  return;
26  };
27 }
28 
30  ESP_LOGCONFIG(TAG, "M5STACK_8ANGLE:");
31  LOG_I2C_DEVICE(this);
32  ESP_LOGCONFIG(TAG, " Firmware version: %d ", this->fw_version_);
33 }
34 
35 float M5Stack8AngleComponent::read_knob_pos(uint8_t channel, AnalogBits bits) {
36  int32_t raw_pos = this->read_knob_pos_raw(channel, bits);
37  if (raw_pos == -1) {
38  return NAN;
39  }
40  return (float) raw_pos / ((1 << bits) - 1);
41 }
42 
43 int32_t M5Stack8AngleComponent::read_knob_pos_raw(uint8_t channel, AnalogBits bits) {
44  uint16_t knob_pos = 0;
45  i2c::ErrorCode err;
46  if (bits == BITS_8) {
47  err = this->read_register(M5STACK_8ANGLE_REGISTER_ANALOG_INPUT_8B + channel, (uint8_t *) &knob_pos, 1);
48  } else if (bits == BITS_12) {
49  err = this->read_register(M5STACK_8ANGLE_REGISTER_ANALOG_INPUT_12B + (channel * 2), (uint8_t *) &knob_pos, 2);
50  } else {
51  ESP_LOGE(TAG, "Invalid number of bits: %d", bits);
52  return -1;
53  }
54  if (err == i2c::NO_ERROR) {
55  return knob_pos;
56  } else {
57  return -1;
58  }
59 }
60 
62  uint8_t out;
63  i2c::ErrorCode err = this->read_register(M5STACK_8ANGLE_REGISTER_DIGITAL_INPUT, (uint8_t *) &out, 1);
64  if (err == i2c::NO_ERROR) {
65  return out ? 1 : 0;
66  } else {
67  return -1;
68  }
69 }
70 
72 
73 } // namespace m5stack_8angle
74 } // namespace esphome
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:19
ErrorCode read_register(uint8_t a_register, uint8_t *data, size_t len, bool stop=true)
reads an array of bytes from a specific register in the I²C device
Definition: i2c.cpp:10
ErrorCode read(uint8_t *data, size_t len)
reads an array of bytes from the device using an I2CBus
Definition: i2c.h:160
No error found during execution of method.
Definition: i2c_bus.h:12
float read_knob_pos(uint8_t channel, AnalogBits bits=AnalogBits::BITS_8)
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:118
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition: i2c_bus.h:11
int32_t read_knob_pos_raw(uint8_t channel, AnalogBits bits=AnalogBits::BITS_8)