ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
bmi270.cpp
Go to the documentation of this file.
1#include "bmi270.h"
2#include "bmi270_config.h"
4#include "esphome/core/log.h"
5#include "esphome/core/hal.h"
7
8namespace esphome::bmi270 {
9
10#ifdef USE_BMI270_BMM150
11using namespace bmm150; // NOLINT - sole consumer of the BMM150 aux-device definitions
12#endif
13
14ESPHOME_LOG_TAG(TAG, "bmi270");
15
16PROGMEM_STRING_TABLE(AccelRangeStrings, "±2g", "±4g", "±8g", "±16g");
17PROGMEM_STRING_TABLE(GyroRangeStrings, "±2000°/s", "±1000°/s", "±500°/s", "±250°/s", "±125°/s");
18
19#if defined(USE_ARDUINO) && !defined(USE_ESP32)
20static constexpr size_t MAX_I2C_BUFFER_SIZE = 32;
21#else
22static constexpr size_t MAX_I2C_BUFFER_SIZE = 256;
23#endif
24
26 // The config port is only reachable with advanced power save off
27 if (!this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_ADV_POWER_SAVE_OFF))
28 return false;
29 delay(1);
30 if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_START))
31 return false;
32
33 constexpr size_t cfg_len = sizeof(BMI270_CONFIG_FILE);
34 // The register byte goes first, so each burst is copied once and sent with write()
35 uint8_t buf[1 + MAX_I2C_BUFFER_SIZE];
36 buf[0] = BMI270_REG_INIT_DATA;
37 size_t index = 0;
38
39 while (index != cfg_len) {
40 // INIT_ADDR_0 takes the word address bits 0-3 and INIT_ADDR_1 bits 4-11
41 const uint8_t addr[2] = {static_cast<uint8_t>((index / 2) & 0x0F), static_cast<uint8_t>((index / 2) >> 4)};
42 if (this->write_register(BMI270_REG_INIT_ADDR_0, addr, sizeof(addr)) != i2c::ERROR_OK)
43 return false;
44
45 size_t burst = clamp_at_most(cfg_len - index, MAX_I2C_BUFFER_SIZE);
46 progmem_memcpy(buf + 1, BMI270_CONFIG_FILE + index, burst);
47 if (this->write(buf, burst + 1) != i2c::ERROR_OK)
48 return false;
49
50 index += burst;
51 // 256 bursts at 50 kHz, or through an I2C multiplexer, outlast the ESP8266 soft watchdog
52 App.feed_wdt();
53 }
54
55 if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_DONE))
56 return false;
57 delay(20); // The datasheet asks for at least 20 ms before INTERNAL_STATUS is valid
58
59 uint8_t status = 0;
60 if (!this->read_byte(BMI270_REG_INTERNAL_STATUS, &status))
61 return false;
62 if ((status & BMI270_INTERNAL_STATUS_MASK) != BMI270_INTERNAL_STATUS_INIT_OK) {
63 ESP_LOGE(TAG, "Config load failed: INTERNAL_STATUS=0x%02X (expected 0x01)", status);
64 return false;
65 }
66 return true;
67}
68
70 MotionComponent::setup();
71 if (!this->check_chip_id(this, BMI270_REG_CHIP_ID, BMI270_CHIP_ID_VALUE))
72 return;
73
74 if (!this->setup_check(this->write_byte(BMI270_REG_CMD, BMI270_CMD_SOFT_RESET)))
75 return;
76 delay(20);
77
78 if (!this->setup_check(this->load_config_file_(), LOG_STR("Config file upload failed")))
79 return;
80
81 // Normal filter bandwidth; performance mode for the accelerometer, noise and filter performance for the gyroscope
82 const uint8_t acc_conf =
83 this->accel_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
84 const uint8_t gyr_conf = this->gyro_odr_ | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
85 BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
86 if (!this->setup_check(this->write_byte(BMI270_REG_ACC_CONF, acc_conf) &&
87 this->write_byte(BMI270_REG_ACC_RANGE, this->accel_range_) &&
88 this->write_byte(BMI270_REG_GYR_CONF, gyr_conf) &&
89 this->write_byte(BMI270_REG_GYR_RANGE, this->gyro_range_) &&
90 this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)))
91 return;
92 delay(5);
93
94 // Advanced power save stays off; FIFO self-wakeup on
95 if (!this->setup_check(this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_FIFO_SELF_WAKEUP)))
96 return;
97
98#ifdef USE_BMI270_BMM150
99 // A missing magnetometer only disables magnetometer reporting
101 const LogString *failed_step = this->setup_magnetometer_();
102 this->magnetometer_ready_ = failed_step == nullptr;
103 if (!this->magnetometer_ready_) {
104 ESP_LOGW(TAG, "BMM150 magnetometer setup failed at %s; continuing without it", LOG_STR_ARG(failed_step));
105 }
106 }
107#endif
108}
109
110#ifdef USE_BMI270_BMM150
111static_assert(BMM150_TRIM_BLOCK_LEN == BMI270_AUX_DATA_LEN, "each trim block is one aux read");
112
114 static constexpr uint32_t AUX_IDLE_TIMEOUT_MS = 20;
115 uint32_t start = millis();
116 while (true) {
117 uint8_t status = 0;
118 if (!this->read_byte(BMI270_REG_STATUS, &status))
119 return false;
120 if ((status & BMI270_STATUS_AUX_BUSY) == 0)
121 return true;
122 if (millis() - start >= AUX_IDLE_TIMEOUT_MS)
123 return false;
124 delay(1);
125 }
126}
127
128bool BMI270Component::write_aux_register_(uint8_t reg, uint8_t value) {
129 return this->write_byte(BMI270_REG_AUX_WR_DATA, value) && this->write_byte(BMI270_REG_AUX_WR_ADDR, reg) &&
130 this->wait_for_aux_idle_();
131}
132
133bool BMI270Component::read_aux_block_(uint8_t reg, uint8_t *buf) {
134 return this->write_byte(BMI270_REG_AUX_RD_ADDR, reg) && this->wait_for_aux_idle_() &&
135 this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
136}
137
138// Follows the Bosch BMI270 aux-interface sequence; ends in auto-burst mode, where the BMI270 keeps
139// AUX_X/Y/Z/R filled from the BMM150's data registers
141 if (!(this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN) &&
142 this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8) &&
143 this->write_byte(BMI270_REG_AUX_DEV_ID, this->aux_device_address_ << 1)))
144 return LOG_STR("aux interface");
145
146 // Suspend -> sleep, then a soft reset so the BMM150 starts from a known state even if it
147 // stayed powered across a restart. The chip ID is only readable once the power bit is set.
148 if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON))
149 return LOG_STR("power-on");
150 delay(BMM150_START_UP_TIME_MS);
151 if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET))
152 return LOG_STR("soft reset");
153 delay(BMM150_SOFT_RESET_TIME_MS);
154
155 uint8_t chip_id[BMI270_AUX_DATA_LEN];
156 if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id))
157 return LOG_STR("chip ID read");
158 if (chip_id[0] != BMM150_CHIP_ID_VALUE) {
159 ESP_LOGW(TAG, "BMM150 chip ID 0x%02X, expected 0x%02X", chip_id[0], BMM150_CHIP_ID_VALUE);
160 return LOG_STR("chip ID check");
161 }
162
163 uint8_t trim[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
164 for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
165 if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, trim + i * BMM150_TRIM_BLOCK_LEN))
166 return LOG_STR("trim read");
167 }
168 this->mag_trim_ = bmm150_parse_trim(trim);
169
170 if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ))
171 return LOG_STR("normal mode");
172
173 if (!(this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
174 BMI270_AUX_IF_CONF_RD_BURST_8) &&
175 this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB) &&
176 this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN)))
177 return LOG_STR("auto-burst mode");
178 return nullptr;
179}
180#endif // USE_BMI270_BMM150
181
183 ESP_LOGCONFIG(TAG, "BMI270 IMU:");
184 LOG_I2C_DEVICE(this);
185 if (this->is_failed())
186 return;
187
188 ESP_LOGCONFIG(TAG,
189 " Accel range : %s\n"
190 " Gyro range : %s",
191 LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_)),
192 LOG_STR_ARG(GyroRangeStrings::get_log_str(this->gyro_range_)));
193#ifdef USE_BMI270_BMM150
195 ESP_LOGCONFIG(TAG, " Aux device : BMM150 magnetometer (%s)",
196 this->magnetometer_ready_ ? LOG_STR_LITERAL("ready") : LOG_STR_LITERAL("NOT DETECTED"));
197 }
198#endif
199 MotionComponent::dump_config();
200}
201
203 if (this->is_failed())
204 return false;
205
206 // Accelerometer: registers 0x0C–0x11 (6 bytes: x_lsb, x_msb, y_lsb, y_msb, z_lsb, z_msb)
207 // When the magnetometer is active, the 8 aux data bytes (0x04–0x0B) sit directly before
208 // the accel data, so one burst read from AUX_X_LSB fetches both.
209#ifdef USE_BMI270_BMM150
210 const bool read_mag = this->magnetometer_ready_ && this->magnetometer_publisher_ != nullptr;
211 uint8_t buf[BMI270_AUX_DATA_LEN + REG_READ_LEN];
212 const uint8_t *mag_raw = buf;
213 const uint8_t *raw_data = read_mag ? buf + BMI270_AUX_DATA_LEN : buf;
214 const bool read_ok = read_mag ? this->read_bytes(BMI270_REG_AUX_X_LSB, buf, sizeof(buf))
215 : this->read_bytes(BMI270_REG_DATA_8, buf, REG_READ_LEN);
216#else
217 uint8_t buf[REG_READ_LEN];
218 const uint8_t *raw_data = buf;
219 const bool read_ok = this->read_bytes(BMI270_REG_DATA_8, buf, REG_READ_LEN);
220#endif
221 if (!read_ok) {
222 ESP_LOGW(TAG, "Failed to read IMU data");
223 return false;
224 }
225 // Scale factor: LSB/g depends on range
226 // raw is a signed 16-bit value; full-scale = range_g * 2^15 lsb
227 // In PROGMEM; each read is a 32-bit load, which is safe from flash on ESP8266
228 alignas(4) static constexpr float ACCEL_SCALE[] PROGMEM = {
229 2.0f / 32768.0f,
230 4.0f / 32768.0f,
231 8.0f / 32768.0f,
232 16.0f / 32768.0f,
233 };
234 float scale = ACCEL_SCALE[this->accel_range_];
235
236 data.acceleration[motion::X_AXIS] = encode_value_le<int16_t>(raw_data) * scale;
237 data.acceleration[motion::Y_AXIS] = encode_value_le<int16_t>(&raw_data[2]) * scale;
238 data.acceleration[motion::Z_AXIS] = encode_value_le<int16_t>(&raw_data[4]) * scale;
239
240 // Gyroscope: registers 0x12–0x17 (6 bytes)
241 // Scale: full-scale range / 2^15
242 alignas(4) static constexpr float GYRO_SCALE[] PROGMEM = {
243 2000.0f / 32768.0f, 1000.0f / 32768.0f, 500.0f / 32768.0f, 250.0f / 32768.0f, 125.0f / 32768.0f,
244 };
245 static constexpr uint8_t GYR_OFFS = BMI270_REG_DATA_14 - BMI270_REG_DATA_8;
246 scale = GYRO_SCALE[this->gyro_range_];
247
248 data.angular_rate[motion::X_AXIS] = encode_value_le<int16_t>(&raw_data[GYR_OFFS]) * scale;
249 data.angular_rate[motion::Y_AXIS] = encode_value_le<int16_t>(&raw_data[GYR_OFFS + 2]) * scale;
250 data.angular_rate[motion::Z_AXIS] = encode_value_le<int16_t>(&raw_data[GYR_OFFS + 4]) * scale;
251
252#ifdef USE_MOTION_TEMPERATURE_PUBLISHER
253 if (this->temperature_publisher_ != nullptr) {
254 // Temperature: registers 0x22–0x23
255 // Formula from datasheet: T[°C] = raw / 512 + 23
256 static constexpr uint8_t TEMP_OFFS = BMI270_REG_TEMP_0 - BMI270_REG_DATA_8;
257 int16_t raw_t = encode_value_le<int16_t>(&raw_data[TEMP_OFFS]);
258 float temperature = (raw_t / 512.0f) + 23.0f;
259 this->temperature_publisher_(temperature);
260 }
261#endif
262
263#ifdef USE_BMI270_BMM150
264 if (read_mag) {
265 const BMM150Data mag_data = bmm150_convert(this->mag_trim_, mag_raw);
266 this->magnetometer_publisher_(mag_data);
267 }
268#endif
269 return true;
270}
271
272} // namespace esphome::bmi270
uint8_t status
Definition bl0942.h:8
void feed_wdt()
Feed the task watchdog.
bool is_failed() const
Definition component.h:288
bool ESPHOME_ALWAYS_INLINE setup_check(bool ok)
Marks the component failed with message (default "Communication failed") unless ok; returns ok.
Definition component.h:236
bmm150::BMM150Trim mag_trim_
Definition bmi270.h:158
HUB_PUBLISHER(magnetometer, const bmm150::BMM150Data &) protected boo load_config_file_)()
Definition bmi270.h:142
bool read_aux_block_(uint8_t reg, uint8_t *buf)
Definition bmi270.cpp:133
BMI270AuxDevice aux_device_
Definition bmi270.h:159
BMI270AccelRange accel_range_
Definition bmi270.h:153
bool write_aux_register_(uint8_t reg, uint8_t value)
Definition bmi270.cpp:128
const LogString * setup_magnetometer_()
Definition bmi270.cpp:140
BMI270GyroRange gyro_range_
Definition bmi270.h:155
ErrorCode write_register(uint8_t a_register, const uint8_t *data, size_t len) const
writes an array of bytes to a specific register in the I²C device
Definition i2c.cpp:79
bool check_chip_id(Component *component, uint8_t a_register, uint8_t expected, uint8_t mask=0xFF)
Read the 8-bit ID at a_register and accept it when it matches expected in the bits set in mask.
Definition i2c.h:232
ErrorCode write(const uint8_t *data, size_t len) const
writes an array of bytes to a device using an I2CBus
Definition i2c.h:195
bool write_byte(uint8_t a_register, uint8_t data) const
Definition i2c.h:312
bool read_byte(uint8_t a_register, uint8_t *data)
Definition i2c.h:272
I2CRegister reg(uint8_t a_register)
calls the I2CRegister constructor
Definition i2c.h:164
bool read_bytes(uint8_t a_register, uint8_t *data, uint8_t len)
Compat APIs All methods below have been added for compatibility reasons.
Definition i2c.h:249
virtual bool update_data(MotionData &data)=0
BMM150Data bmm150_convert(const BMM150Trim &trim, const uint8_t *raw)
Definition bmm150_aux.h:110
BMM150Trim bmm150_parse_trim(const uint8_t *regs)
Definition bmm150_aux.h:68
ESPHOME_LOG_TAG(TAG, "bmi270")
PROGMEM_STRING_TABLE(AccelRangeStrings, "±2g", "±4g", "±8g", "±16g")
@ BMI270_AUX_DEVICE_BMM150
Definition bmi270.h:121
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:13
std::span< const uint8_t > data
T clamp_at_most(T value, U max)
Definition helpers.h:2859
void progmem_memcpy(void *dst, const void *src, size_t len)
Definition hal.h:56
uint32_t value
Definition hal.cpp:59
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
Definition helpers.h:1268
void HOT delay(uint32_t ms)
Definition hal.cpp:78
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
uint16_t temperature
Definition sun_gtil2.cpp:12