ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
bmi270.cpp
Go to the documentation of this file.
1#include "bmi270.h"
2#include "bmi270_config.h"
3#include "esphome/core/log.h"
4#include "esphome/core/hal.h"
6
7namespace esphome::bmi270 {
8
9#ifdef USE_BMI270_BMM150
10using namespace bmm150; // NOLINT - sole consumer of the BMM150 aux-device definitions
11#endif
12
13ESPHOME_LOG_TAG(TAG, "bmi270");
14
15PROGMEM_STRING_TABLE(AccelRangeStrings, "±2g", "±4g", "±8g", "±16g");
16PROGMEM_STRING_TABLE(GyroRangeStrings, "±2000°/s", "±1000°/s", "±500°/s", "±250°/s", "±125°/s");
17
18#if defined(USE_ARDUINO) && !defined(USE_ESP32)
19static constexpr size_t MAX_I2C_BUFFER_SIZE = 32;
20#else
21static constexpr size_t MAX_I2C_BUFFER_SIZE = 256;
22#endif
23
24// Configuration blob upload
25// The BMI270 requires a firmware config blob to be written to its internal
26// memory after every power-on before sensors can be used.
27
29 // 1. Disable advanced power-save so the config port is accessible
30 if (!this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_ADV_POWER_SAVE_OFF))
31 return false;
32 delay(1);
33
34 // 2. Prepare config load: write 0x00 to INIT_CTRL to start
35 if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_START))
36 return false;
37
38 // 3. Burst-write the config in pages
39 const uint8_t *cfg = BMI270_CONFIG_FILE;
40 constexpr size_t cfg_len = sizeof(BMI270_CONFIG_FILE);
41 size_t index = 0;
42
43 while (index != cfg_len) {
44 // Set the page address in INIT_ADDR registers
45 uint8_t addr_lsb = (uint8_t) ((index / 2) & 0x0F);
46 uint8_t addr_msb = (uint8_t) ((index / 2) >> 4);
47 if (!this->write_byte(BMI270_REG_INIT_ADDR_0, addr_lsb))
48 return false;
49 if (!this->write_byte(BMI270_REG_INIT_ADDR_0 + 1, addr_msb))
50 return false;
51
52 // Write a burst of up to the maximum allowed size
53 size_t burst = clamp_at_most(cfg_len - index, MAX_I2C_BUFFER_SIZE);
54 if (this->write_register(BMI270_REG_INIT_DATA, cfg + index, burst) != i2c::ERROR_OK)
55 return false;
56
57 index += burst;
58 }
59
60 // 4. Signal end of config load
61 if (!this->write_byte(BMI270_REG_INIT_CTRL, BMI270_INIT_CTRL_LOAD_DONE))
62 return false;
63 delay(20); // spec: wait ≥20 ms for init to complete
64
65 // 5. Check INTERNAL_STATUS: bit[0:3] should be 0x01 ("initialisation OK")
66 uint8_t status = 0;
67 if (!this->read_byte(BMI270_REG_INTERNAL_STATUS, &status))
68 return false;
69 if ((status & BMI270_INTERNAL_STATUS_MASK) != BMI270_INTERNAL_STATUS_INIT_OK) {
70 ESP_LOGE(TAG, "Config load failed: INTERNAL_STATUS=0x%02X (expected 0x01)", status);
71 return false;
72 }
73 return true;
74}
75
76// setup() ─
77
79 MotionComponent::setup();
80 // 1. Verify chip ID
81 if (!this->check_chip_id(this, BMI270_REG_CHIP_ID, BMI270_CHIP_ID_VALUE))
82 return;
83
84 // 2. Soft-reset via CMD register (0x7E = 0xB6)
85 if (!this->write_byte(BMI270_REG_CMD, BMI270_CMD_SOFT_RESET)) {
86 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
87 return;
88 }
89 delay(20);
90
91 // 4. Upload the configuration blob
92 if (!load_config_file_()) {
93 this->mark_failed(LOG_STR("Config file upload failed"));
94 return;
95 }
96 ESP_LOGD(TAG, "Config blob uploaded ✓");
97
98 // 5. Configure accelerometer
99 // ACC_CONF: ODR | BWP(0x2 = normal avg4) | perf_mode(1)
100 uint8_t acc_conf =
101 (uint8_t) (accel_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) | BMI270_ACC_CONF_PERF_MODE;
102 if (!this->write_byte(BMI270_REG_ACC_CONF, acc_conf)) {
103 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
104 return;
105 }
106 if (!this->write_byte(BMI270_REG_ACC_RANGE, (uint8_t) accel_range_)) {
107 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
108 return;
109 }
110
111 // 6. Configure gyroscope
112 // GYR_CONF: ODR | BWP(0x2 = normal) | noise_perf(1) | filter_perf(1)
113 uint8_t gyr_conf = (uint8_t) (gyro_odr_) | (BMI270_CONF_BWP_NORMAL << BMI270_CONF_BWP_SHIFT) |
114 BMI270_GYR_CONF_NOISE_PERF | BMI270_GYR_CONF_FILTER_PERF;
115 if (!this->write_byte(BMI270_REG_GYR_CONF, gyr_conf)) {
116 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
117 return;
118 }
119 if (!this->write_byte(BMI270_REG_GYR_RANGE, (uint8_t) gyro_range_)) {
120 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
121 return;
122 }
123
124 // 7. Enable accelerometer, gyroscope, and temperature sensor
125 // PWR_CTRL bits: temp_en[3] | gyr_en[2] | acc_en[1]
126 if (!this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU)) {
127 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
128 return;
129 }
130 delay(5);
131
132 // 8. Re-enable advanced power save (optional; keeps current low between reads)
133 // Disabled here for simplicity – leave in performance mode
134 if (!this->write_byte(BMI270_REG_PWR_CONF, BMI270_PWR_CONF_FIFO_SELF_WAKEUP)) { // bit1 = fifo_self_wakeup
135 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
136 return;
137 }
138
139 // 9. Optionally bring up whatever is wired to the aux interface.
140 // This is entirely additive: it is off by default, and failure only disables
141 // magnetometer reporting rather than the whole component.
142#ifdef USE_BMI270_BMM150
145 if (!this->magnetometer_ready_) {
146 ESP_LOGW(TAG, "BMM150 magnetometer setup failed; continuing without it");
147 }
148 }
149#endif
150
151 ESP_LOGCONFIG(TAG, "BMI270 initialised successfully");
152}
153
154#ifdef USE_BMI270_BMM150
156 // The STATUS aux-busy bit is set while an aux transaction is in flight. Aux transaction
157 // duration depends on the attached device's own timing, so poll with a bounded
158 // timeout instead of guessing a fixed delay.
159 uint32_t start = millis();
160 while (true) {
161 uint8_t status = 0;
162 if (!this->read_byte(BMI270_REG_STATUS, &status))
163 return false;
164 if ((status & BMI270_STATUS_AUX_BUSY) == 0)
165 return true;
166 if (millis() - start >= timeout_ms)
167 return false;
168 delay(1);
169 }
170}
171
172bool BMI270Component::write_aux_register_(uint8_t reg, uint8_t value) {
173 if (!this->write_byte(BMI270_REG_AUX_WR_DATA, value))
174 return false;
175 if (!this->write_byte(BMI270_REG_AUX_WR_ADDR, reg))
176 return false;
177 return this->wait_for_aux_idle_(20);
178}
179
180bool BMI270Component::read_aux_block_(uint8_t reg, uint8_t *buf) {
181 if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, reg))
182 return false;
183 if (!this->wait_for_aux_idle_(20))
184 return false;
185 return this->read_bytes(BMI270_REG_AUX_X_LSB, buf, BMI270_AUX_DATA_LEN);
186}
187
189 uint8_t regs[BMM150_TRIM_BLOCKS * BMM150_TRIM_BLOCK_LEN];
190 for (uint8_t i = 0; i < BMM150_TRIM_BLOCKS; i++) {
191 if (!this->read_aux_block_(BMM150_REG_TRIM_START + i * BMM150_TRIM_BLOCK_LEN, regs + i * BMM150_TRIM_BLOCK_LEN))
192 return false;
193 }
194 this->mag_trim_ = bmm150_parse_trim(regs);
195 return true;
196}
197
199 // Sequence adapted from the Bosch BMI270 aux-interface protocol: enable the secondary
200 // I2C master in manual mode, point it at the BMM150's address, power the BMM150 up
201 // and soft-reset it, verify its chip ID, read its factory trim values, put it in
202 // normal/30Hz mode, then switch the aux interface to auto-burst mode so BMI270 keeps
203 // AUX_X/Y/Z/R refreshed from the BMM150's data registers.
204 ESP_LOGD(TAG, "Setting up BMM150 magnetometer via BMI270 aux interface...");
205
206 if (!this->write_byte(BMI270_REG_IF_CONF, BMI270_IF_CONF_AUX_IF_EN))
207 return false;
208 if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_MANUAL_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8))
209 return false;
210 if (!this->write_byte(BMI270_REG_AUX_DEV_ID, (uint8_t) (this->aux_device_address_ << 1)))
211 return false;
212
213 // Suspend -> sleep, then a soft reset so the BMM150 starts from a known state even if it
214 // stayed powered across a restart. The chip ID is only readable once the power bit is set.
215 if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_POWER_ON)) {
216 ESP_LOGW(TAG, "BMM150 power-on write timed out");
217 return false;
218 }
219 delay(BMM150_START_UP_TIME_MS);
220 if (!this->write_aux_register_(BMM150_REG_POWER_CONTROL, BMM150_CMD_SOFT_RESET)) {
221 ESP_LOGW(TAG, "BMM150 soft-reset write timed out");
222 return false;
223 }
224 delay(BMM150_SOFT_RESET_TIME_MS);
225
226 uint8_t chip_id[BMI270_AUX_DATA_LEN];
227 if (!this->read_aux_block_(BMM150_REG_CHIP_ID, chip_id)) {
228 ESP_LOGW(TAG, "BMM150 chip-ID read failed");
229 return false;
230 }
231 if (chip_id[0] != BMM150_CHIP_ID_VALUE) {
232 ESP_LOGW(TAG, "BMM150 not detected (chip ID 0x%02X, expected 0x%02X)", chip_id[0], BMM150_CHIP_ID_VALUE);
233 return false;
234 }
235
236 if (!this->read_magnetometer_trim_()) {
237 ESP_LOGW(TAG, "BMM150 trim data read failed");
238 return false;
239 }
240
241 if (!this->write_aux_register_(BMM150_REG_OP_MODE, BMM150_CMD_NORMAL_MODE_ODR_30HZ)) {
242 ESP_LOGW(TAG, "BMM150 mode write timed out");
243 return false;
244 }
245
246 // Switch to auto-burst mode: BMI270 will keep polling 8 bytes from the BMM150's
247 // data registers (0x42) into its own AUX_X/Y/Z/R registers automatically.
248 if (!this->write_byte(BMI270_REG_AUX_IF_CONF, BMI270_AUX_IF_CONF_FCU_WRITE_EN | BMI270_AUX_IF_CONF_MAN_RD_BURST_8 |
249 BMI270_AUX_IF_CONF_RD_BURST_8))
250 return false;
251 if (!this->write_byte(BMI270_REG_AUX_RD_ADDR, BMM150_REG_DATA_X_LSB))
252 return false;
253 if (!this->write_byte(BMI270_REG_PWR_CTRL, BMI270_PWR_CTRL_IMU | BMI270_PWR_CTRL_AUX_EN))
254 return false;
255
256 ESP_LOGD(TAG, "BMM150 magnetometer ready");
257 return true;
258}
259#endif // USE_BMI270_BMM150
260
262 ESP_LOGCONFIG(TAG, "BMI270 IMU:");
263 LOG_I2C_DEVICE(this);
264 if (this->is_failed())
265 return;
266
267 ESP_LOGCONFIG(TAG, " Accel range : %s",
268 LOG_STR_ARG(AccelRangeStrings::get_log_str(this->accel_range_, AccelRangeStrings::LAST_INDEX)));
269 ESP_LOGCONFIG(TAG, " Gyro range : %s",
270 LOG_STR_ARG(GyroRangeStrings::get_log_str(this->gyro_range_, GyroRangeStrings::LAST_INDEX)));
271#ifdef USE_BMI270_BMM150
273 ESP_LOGCONFIG(TAG, " Aux device : BMM150 magnetometer (%s)",
274 this->magnetometer_ready_ ? LOG_STR_LITERAL("ready") : LOG_STR_LITERAL("NOT DETECTED"));
275 }
276#endif
277 MotionComponent::dump_config();
278}
279
280// update() ─
281// Reads all 6 axes + temperature in one block
282
284 if (this->is_failed())
285 return false;
286
287 // Accelerometer: registers 0x0C–0x11 (6 bytes: x_lsb, x_msb, y_lsb, y_msb, z_lsb, z_msb)
288 // When the magnetometer is active, the 8 aux data bytes (0x04–0x0B) sit directly before
289 // the accel data, so one burst read from AUX_X_LSB fetches both.
290#ifdef USE_BMI270_BMM150
291 const bool read_mag = this->magnetometer_ready_ && !this->magnetometer_callback_.empty();
292 uint8_t buf[BMI270_AUX_DATA_LEN + REG_READ_LEN];
293 const uint8_t *mag_raw = buf;
294 const uint8_t *raw_data = read_mag ? buf + BMI270_AUX_DATA_LEN : buf;
295 const bool read_ok = read_mag ? this->read_bytes(BMI270_REG_AUX_X_LSB, buf, sizeof(buf))
296 : this->read_bytes(BMI270_REG_DATA_8, buf, REG_READ_LEN);
297#else
298 uint8_t buf[REG_READ_LEN];
299 const uint8_t *raw_data = buf;
300 const bool read_ok = this->read_bytes(BMI270_REG_DATA_8, buf, REG_READ_LEN);
301#endif
302 if (!read_ok) {
303 ESP_LOGW(TAG, "Failed to read IMU data");
304 return false;
305 }
306 // Scale factor: LSB/g depends on range
307 // raw is a signed 16-bit value; full-scale = range_g * 2^15 lsb
308 // In PROGMEM; each read is a 32-bit load, which is safe from flash on ESP8266
309 alignas(4) static constexpr float ACCEL_SCALE[] PROGMEM = {
310 2.0f / 32768.0f,
311 4.0f / 32768.0f,
312 8.0f / 32768.0f,
313 16.0f / 32768.0f,
314 };
315 float scale = ACCEL_SCALE[this->accel_range_];
316
317 data.acceleration[motion::X_AXIS] = encode_value_le<int16_t>(raw_data) * scale;
318 data.acceleration[motion::Y_AXIS] = encode_value_le<int16_t>(&raw_data[2]) * scale;
319 data.acceleration[motion::Z_AXIS] = encode_value_le<int16_t>(&raw_data[4]) * scale;
320
321 // Gyroscope: registers 0x12–0x17 (6 bytes)
322 // Scale: full-scale range / 2^15
323 alignas(4) static constexpr float GYRO_SCALE[] PROGMEM = {
324 2000.0f / 32768.0f, 1000.0f / 32768.0f, 500.0f / 32768.0f, 250.0f / 32768.0f, 125.0f / 32768.0f,
325 };
326 static constexpr uint8_t GYR_OFFS = BMI270_REG_DATA_14 - BMI270_REG_DATA_8;
327 scale = GYRO_SCALE[this->gyro_range_];
328
329 data.angular_rate[motion::X_AXIS] = encode_value_le<int16_t>(&raw_data[GYR_OFFS]) * scale;
330 data.angular_rate[motion::Y_AXIS] = encode_value_le<int16_t>(&raw_data[GYR_OFFS + 2]) * scale;
331 data.angular_rate[motion::Z_AXIS] = encode_value_le<int16_t>(&raw_data[GYR_OFFS + 4]) * scale;
332
333 if (!this->temperature_callback_.empty()) {
334 // Temperature: registers 0x22–0x23
335 // Formula from datasheet: T[°C] = raw / 512 + 23
336 static constexpr uint8_t TEMP_OFFS = BMI270_REG_TEMP_0 - BMI270_REG_DATA_8;
337 int16_t raw_t = encode_value_le<int16_t>(&raw_data[TEMP_OFFS]);
338 float temperature = (raw_t / 512.0f) + 23.0f;
339 this->temperature_callback_.call(temperature);
340 }
341
342#ifdef USE_BMI270_BMM150
343 if (read_mag) {
344 const BMM150Data mag_data = bmm150_convert(this->mag_trim_, mag_raw);
345 this->magnetometer_callback_.call(mag_data);
346 }
347#endif
348 return true;
349}
350
351} // namespace esphome::bmi270
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:287
bmm150::BMM150Trim mag_trim_
Definition bmi270.h:178
LazyCallbackManager< void(const bmm150::BMM150Data &)> magnetometer_callback_
Definition bmi270.h:177
LazyCallbackManager< void(float)> temperature_callback_
Definition bmi270.h:175
bool update_data(motion::MotionData &data) override
Definition bmi270.cpp:283
bool read_aux_block_(uint8_t reg, uint8_t *buf)
Definition bmi270.cpp:180
BMI270AuxDevice aux_device_
Definition bmi270.h:179
BMI270AccelRange accel_range_
Definition bmi270.h:171
bool wait_for_aux_idle_(uint32_t timeout_ms)
Definition bmi270.cpp:155
bool write_aux_register_(uint8_t reg, uint8_t value)
Definition bmi270.cpp:172
BMI270GyroRange gyro_range_
Definition bmi270.h:173
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:54
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
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
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:129
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
T clamp_at_most(T value, U max)
Definition helpers.h:2576
uint32_t value
Definition hal.cpp:41
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:1084
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
uint16_t temperature
Definition sun_gtil2.cpp:12