10static const uint8_t HMC5883L_ADDRESS = 0x1E;
11static const uint8_t HMC5883L_REGISTER_CONFIG_A = 0x00;
12static const uint8_t HMC5883L_REGISTER_CONFIG_B = 0x01;
13static const uint8_t HMC5883L_REGISTER_MODE = 0x02;
14static const uint8_t HMC5883L_REGISTER_DATA_X_MSB = 0x03;
15static const uint8_t HMC5883L_REGISTER_DATA_X_LSB = 0x04;
16static const uint8_t HMC5883L_REGISTER_DATA_Z_MSB = 0x05;
17static const uint8_t HMC5883L_REGISTER_DATA_Z_LSB = 0x06;
18static const uint8_t HMC5883L_REGISTER_DATA_Y_MSB = 0x07;
19static const uint8_t HMC5883L_REGISTER_DATA_Y_LSB = 0x08;
20static const uint8_t HMC5883L_REGISTER_STATUS = 0x09;
21static const uint8_t HMC5883L_REGISTER_IDENTIFICATION_A = 0x0A;
22static const uint8_t HMC5883L_REGISTER_IDENTIFICATION_B = 0x0B;
23static const uint8_t HMC5883L_REGISTER_IDENTIFICATION_C = 0x0C;
27 if (!this->
read_byte(HMC5883L_REGISTER_IDENTIFICATION_A, &
id[0]) ||
28 !this->
read_byte(HMC5883L_REGISTER_IDENTIFICATION_B, &
id[1]) ||
29 !this->
read_byte(HMC5883L_REGISTER_IDENTIFICATION_C, &
id[2])) {
38 if (
id[0] != 0x48 ||
id[1] != 0x34 ||
id[2] != 0x33) {
39 this->
mark_failed(LOG_STR(
"The ID registers don't match - Is this really an HMC5883L?"));
47 if (!this->
write_byte(HMC5883L_REGISTER_CONFIG_A, config_a)) {
53 config_b |= this->
range_ << 5;
54 if (!this->
write_byte(HMC5883L_REGISTER_CONFIG_B, config_b)) {
67void HMC5883LComponent::dump_config() {
68 ESP_LOGCONFIG(TAG,
"HMC5883L:");
70 LOG_UPDATE_INTERVAL(
this);
72 LOG_SENSOR(
" ",
"X Axis", this->x_sensor_);
73 LOG_SENSOR(
" ",
"Y Axis", this->y_sensor_);
74 LOG_SENSOR(
" ",
"Z Axis", this->z_sensor_);
75 LOG_SENSOR(
" ",
"Heading", this->heading_sensor_);
77void HMC5883LComponent::update() {
78 uint16_t raw_x, raw_y, raw_z;
79 if (!this->
read_byte_16(HMC5883L_REGISTER_DATA_X_MSB, &raw_x) ||
80 !this->
read_byte_16(HMC5883L_REGISTER_DATA_Y_MSB, &raw_y) ||
81 !this->
read_byte_16(HMC5883L_REGISTER_DATA_Z_MSB, &raw_z)) {
117 const float x = int16_t(raw_x) * mg_per_bit * 0.1f;
118 const float y = int16_t(raw_y) * mg_per_bit * 0.1f;
119 const float z = int16_t(raw_z) * mg_per_bit * 0.1f;
121 float heading = atan2f(0.0f -
x,
y) * 180.0f / std::numbers::pi_v<float>;
122 ESP_LOGD(TAG,
"Got x=%0.02fµT y=%0.02fµT z=%0.02fµT heading=%0.01f°",
x,
y,
z, heading);
124 PUBLISH_STATE(this->x_sensor_,
x);
125 PUBLISH_STATE(this->y_sensor_,
y);
126 PUBLISH_STATE(this->z_sensor_,
z);
127 PUBLISH_STATE(this->heading_sensor_, heading);