From a7d4a0eab57612d9c24328d82ad80a991d173b55 Mon Sep 17 00:00:00 2001 From: Error414 Date: Wed, 7 Oct 2026 22:14:51 +0200 Subject: [PATCH 01/14] I2C CORE - baro + mag --- AGENTS.md | 1 + docs/Settings.md | 1 + docs/development/non-blocking-i2c.md | 176 ++++ src/main/build/debug.h | 1 + src/main/drivers/barometer/barometer.h | 11 + src/main/drivers/barometer/barometer_bmp280.c | 56 +- src/main/drivers/barometer/barometer_dps310.c | 53 +- src/main/drivers/barometer/barometer_spl06.c | 57 +- src/main/drivers/bus.c | 91 +- src/main/drivers/bus.h | 21 +- src/main/drivers/bus_busdev_i2c.c | 27 +- src/main/drivers/bus_i2c.h | 32 +- src/main/drivers/bus_i2c_at32f43x.c | 274 +++++- src/main/drivers/bus_i2c_hal.c | 305 +++++- src/main/drivers/bus_i2c_rp2350.c | 21 +- src/main/drivers/bus_i2c_soft.c | 27 + src/main/drivers/bus_i2c_stm32f40x.c | 916 ++++++++++-------- src/main/drivers/compass/compass.h | 6 +- src/main/drivers/compass/compass_qmc5883l.c | 55 +- src/main/drivers/compass/compass_qmc5883p.c | 50 +- src/main/drivers/sdcard/sdcard_spi.c | 4 +- src/main/fc/cli.c | 3 +- src/main/fc/fc_tasks.c | 16 +- src/main/fc/settings.yaml | 2 +- src/main/sensors/barometer.c | 129 ++- src/main/sensors/barometer.h | 2 +- src/main/sensors/compass.c | 55 +- src/main/sensors/compass.h | 6 +- 28 files changed, 1773 insertions(+), 625 deletions(-) create mode 100644 docs/development/non-blocking-i2c.md diff --git a/AGENTS.md b/AGENTS.md index b2c077191d5..8ea4f1bd419 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -327,6 +327,7 @@ docs — check it before assuming something isn't documented: versioning rules, when a new setting is warranted) - `build-system.md` - CMake build system internals - `pid-to-servo-computation.md` - PID-to-servo signal path (fixed-wing) +- `non-blocking-i2c.md` - Non-blocking I2C transfers (bus API, platform back-ends, timeouts and recovery, converting a driver) - `msp/` - MSP protocol doc generation tooling - Target-specific files in `/src/main/target/` diff --git a/docs/Settings.md b/docs/Settings.md index a0bdc187935..88df75b4845 100644 --- a/docs/Settings.md +++ b/docs/Settings.md @@ -803,6 +803,7 @@ Defines debug values exposed in debug variables (developer / debugging setting) | ESC | | | FW_TURN | | | MAG | | +| I2C | | --- diff --git a/docs/development/non-blocking-i2c.md b/docs/development/non-blocking-i2c.md new file mode 100644 index 00000000000..3bc10d95bdf --- /dev/null +++ b/docs/development/non-blocking-i2c.md @@ -0,0 +1,176 @@ +# Non-blocking I2C transfers + +How a driver starts an I2C transfer without waiting for it, how the platform +drivers carry it to the end, and what happens when it fails. This document +covers the bus layer, the barometer and the compass, the first sensors +converted to it. The other sensor layers (pitot, rangefinder) follow in +later changes. + +## Why + +An I2C register read of 6 bytes at 400 kHz keeps the wire busy for about +200 µs. Every `busReadBuf()` spins in the platform driver until the whole +transfer has finished, so a BARO task that needs a few microseconds of CPU +shows up as 100 to 300 µs in `tasks`, and the compass, pitot and +rangefinder tasks behave the same way. + +With the calls below a task starts a transfer, returns, and picks up the +result on a later run. The wire time stays the same, the CPU time moves to a +handful of short interrupts. The model follows Betaflight: no bus queue, no +DMA, one outstanding transfer per bus, the owner polls for its completion. + +## Platform drivers (`drivers/bus_i2c_*.c`) + +Every platform implements the same `drivers/bus_i2c.h` API: + +| Function | Behaviour | +|---|---| +| `i2cRead()`, `i2cWrite()`, `i2cWriteBuffer()` | Blocking, unchanged for callers. They first wait for a pending non-blocking transfer, so drivers that were not converted keep working on a shared bus. | +| `i2cReadStart()`, `i2cWriteStart()`, `i2cWriteBufferStart()` | Start a transfer and return at once. `false` means nothing was started (bus busy or start failed), try again later. | +| `i2cBusy(device, addr, &error)` | `true` while the given slave's non-blocking transfer runs. `error` reports the outcome of that slave's last completed transfer; the result is kept per address, so another device using the bus in between does not overwrite it. | + +| Platform | Implementation | +|---|---| +| STM32F4 | Own interrupt-driven engine in `bus_i2c_stm32f40x.c`, ported from the Betaflight `bus_i2c_stm32f4xx.c` driver. Blocking calls use the same engine and wait for it. | +| STM32F7/H7 | `HAL_I2C_Mem_Read_IT()` and friends, completion through the `HAL_I2C_*CpltCallback()` / `HAL_I2C_ErrorCallback()` hooks. | +| AT32F43x | `i2c_memory_read_int()` and friends from `i2c_application`. The library sends the slave and register address synchronously (tens of µs, bounded by the library timeout), only the data phase runs in the interrupt. | +| RP2350, software I2C, SITL | Synchronous: the start call completes the transfer, `i2cBusy()` is always `false`. | + +`i2cWriteStart()` copies the data byte into driver-owned storage, the caller +does not have to keep it alive. Buffers given to `i2cReadStart()` and +`i2cWriteBufferStart()` must stay valid until `i2cBusy()` reports idle, so +drivers use static buffers. + +A write with a zero length sends the register byte alone (the HAL and AT32 +blocking paths refuse zero-length transfers, the drivers wrap that). + +## Bus layer (`drivers/bus.h`) + +| Function | Behaviour | +|---|---| +| `busReadBufStart(dev, reg, buf, len)` | Non-blocking register read. On SPI the read completes inside the call. | +| `busWriteStart(dev, reg, data)` | Non-blocking single register write. | +| `busWriteBufStart(dev, reg, buf, len)` | Non-blocking multi-byte write, the buffer must stay valid until the bus is idle. A zero length sends the register byte alone. | +| `busIsBusy(dev, &error)` | Poll for completion of this device's transfer: `true` while it is on the bus, otherwise `error` carries its outcome. Another device's transfer on the same bus does not affect the result. SPI reports idle. | +| `busReadStepResult_e` | `BUS_READ_STEP_BUSY` (nothing started), `BUS_READ_STEP_NEXT` (intermediate transfer started), `BUS_READ_STEP_LAST` (final transfer started). Used by sensors whose sample needs several transfers. | + +Raw access (`reg == 0xFF` with `DEVFLAGS_USE_RAW_REGISTERS`) works the same +way as for the blocking calls. + +## Timeouts and recovery + +A non-blocking transfer is abandoned when it makes no progress for +`I2C_TIMEOUT` (10 ms) while somebody looks at it: the peripheral is +reinitialised with `i2cInit()`, the error counter goes up and the failure is +recorded for the transfer's owner. Progress is the number of bytes still to +go (`XferCount` on the HAL, `pcount` on the AT32, byte index and subaddress +phase on the F4), not the time since the start: + +* A gap between two looks longer than 1 ms counts as 1 ms. A main loop that + was busy elsewhere for a while (a settings save) does not get a transfer + that is merely late declared stuck, because the interrupts carried it on in + the meantime and the next look sees the progress. +* A transfer that really is stuck still times out when looked at seldom: + about ten looks at 1 ms intervals, or 10 ms of a blocking wait. + +A NACK or a bus error ends a non-blocking transfer at once: the error is +recorded for its owner and the counter shown by `status` goes up. The +peripheral is not reinitialised for that, it is fine after a NACK. The F4 +driver never did that for blocking calls either; the HAL and AT32 blocking +calls keep reinitialising on failure, as before. + +A blocking call issued while a non-blocking transfer is on the bus waits for +it with the same stuck detection, then runs as before. + +## Barometer (`sensors/barometer.c`, hooks in `drivers/barometer/barometer.h`) + +``` +start_ut -> (ut_delay) -> read_ut -> get_ut -> start_up -> (up_delay) -> read_up -> get_up -> calculate +``` + +* `start_*` triggers a measurement, usually a `busWriteStart()`. +* `read_*` starts the data transfer with `busReadBufStart()` and returns + `false` when the bus is busy. +* `get_*` only parses the static buffer and returns `false` when the sample + is unusable (the phase is restarted). +* `combined_read = true` skips the temperature phase for sensors that deliver + both values in one read. +* Drivers without `read_*` hooks keep their blocking `get_*` and run exactly + as before. + +While a transfer is on the bus the task asks to be called again after 1 ms, +otherwise it returns to the sensor's delays. A delay of 0 keeps the current +task period. The position estimator is fed only when a new sample was +produced, the 1 ms steps bring it nothing. + +Converted so far: + +* **DPS310 / SPL07-003**: the sensor runs in continuous mode. The temperature + phase reads `MEAS_CFG` every `ut_delay` and `get_ut` checks `PRS_RDY`; a + clear flag restarts the phase, a set flag moves on to the pressure phase, + which reads the six result bytes one scheduler step later. Same sample + rate as before, the sensor's 32 per second. +* **SPL06-001**: command mode, two phases. `start_ut` fires the temperature + command, the temperature bytes are read after `ut_delay`, then the same for + the pressure. A sample takes `ut_delay + up_delay` plus two 1 ms steps, + practically the previous cadence. +* **BMP280 / BME280**: forced mode. `start_up` fires the one-byte trigger + write, the pressure phase reads the six-byte frame after `up_delay`, and + the next trigger follows right after the parse. Note the cadence: a sample + now takes `up_delay` plus one 1 ms step instead of `2 * up_delay`, because + the blocking cycle spent its second half idle. For the default + oversampling that is about 24 ms per sample instead of 46 ms. + +The remaining barometer drivers are untouched and still block. + +## Compass (`sensors/compass.c`, hooks in `drivers/compass/compass.h`) + +`readStart(mag, firstStep)` returns a `busReadStepResult_e`. It is called with +`firstStep` set for the first transfer of a sample and again after every +completed transfer until it returns `BUS_READ_STEP_LAST`; `read()` then only +parses. `compassUpdate()` returns the delay until its next call: 1 ms while a +transfer is on the bus, the regular 100 ms period once the sample was +handled. Drivers without `readStart` keep their blocking `read()`. + +Converted so far: QMC5883L and QMC5883P, two transfers per sample. The status +byte is read first; the six data bytes only when `DRDY` confirms a fresh +sample, otherwise `read()` reports the miss as before. A sample costs three +task runs about 1 ms apart, then the task sleeps for the rest of the period. + +## Converting a driver + +1. Replace the bus access in the periodic measurement path with a static + buffer and a `busReadBufStart()` / `busWriteStart()` call. Return "busy" + to the caller when the start call refuses, and try again on the next run. +2. Pick up the result on a later run: `busIsBusy(dev, &error)` is `false` + once the transfer is over, `error` says whether the buffer is valid. +3. Keep the parse step free of bus access. +4. Leave initialisation and detection on the blocking calls; they wait for a + pending transfer first, so they are safe on a shared bus. +5. One outstanding transfer per device. A sample made of several transfers + (status, then data) takes several runs. + +Drivers for other buses (SPI gyros, MSP, fake sensors) need no change. + +## Debugging + +`set debug_mode = I2C`, then `debug` in the CLI: + +| Field | Meaning | +|---|---| +| `debug[0]` | interrupts during the last transfer (about 10 for a 6 byte read on F4) | +| `debug[1]` | error interrupts since boot | +| `debug[2]` | duration of the last transfer in µs (about 200 for 6 bytes at 400 kHz) | +| `debug[3]` | longest single interrupt handler run in µs (F4 only) | +| `debug[4]` | longest wait for a START / STOP bit release in µs (F4 only) | +| `debug[5]` | I2C error counter, also shown by `status` | +| `debug[6]` | interrupt enables found at transfer start (F4 only, 1024 is normal) | +| `debug[7]` | time spent in the start call in µs, should be a few µs on F4/F7/H7 | + +## Known limitations + +* No bus arbitration queue: a device that finds the bus busy retries later. + Fine at the 10 to 60 Hz rates the sensors use. +* On the AT32 the start call blocks for the address phase of the transfer. +* The RP2350 driver is still blocking. +* SPI stays synchronous. diff --git a/src/main/build/debug.h b/src/main/build/debug.h index 23caa6b6fa7..4b10d82202e 100644 --- a/src/main/build/debug.h +++ b/src/main/build/debug.h @@ -87,6 +87,7 @@ typedef enum { DEBUG_ESC, DEBUG_FW_TURN, DEBUG_MAG, + DEBUG_I2C, DEBUG_COUNT // also update debugModeNames in cli.c } debugType_e; diff --git a/src/main/drivers/barometer/barometer.h b/src/main/drivers/barometer/barometer.h index 980963f3f1f..cb7c3ad63e7 100644 --- a/src/main/drivers/barometer/barometer.h +++ b/src/main/drivers/barometer/barometer.h @@ -23,13 +23,24 @@ struct baroDev_s; typedef bool (*baroOpFuncPtr)(struct baroDev_s * baro); typedef bool (*baroCalculateFuncPtr)(struct baroDev_s * baro, int32_t *pressure, int32_t *temperature); +/* + * Measurement cycle driven by baroUpdate(): start_ut -> (ut_delay) -> read_ut -> get_ut -> start_up -> (up_delay) -> read_up -> get_up -> calculate + * + * A driver may leave any hook NULL. The optional read_* hooks start a non-blocking bus transfer and must return false + * when the bus is busy; the matching get_* then only parses the received buffer once the bus reports idle and returns + * false if the sample is not usable (the phase is restarted). Drivers without read_* hooks do their blocking bus access + * inside get_*. A delay of 0 keeps the current task period. + */ typedef struct baroDev_s { busDevice_t * busDev; + bool combined_read; // get_up delivers temperature as well, the temperature phase is skipped uint16_t ut_delay; uint16_t up_delay; baroOpFuncPtr start_ut; + baroOpFuncPtr read_ut; baroOpFuncPtr get_ut; baroOpFuncPtr start_up; + baroOpFuncPtr read_up; baroOpFuncPtr get_up; baroCalculateFuncPtr calculate; } baroDev_t; diff --git a/src/main/drivers/barometer/barometer_bmp280.c b/src/main/drivers/barometer/barometer_bmp280.c index 038c5029ce4..5124735d3d3 100644 --- a/src/main/drivers/barometer/barometer_bmp280.c +++ b/src/main/drivers/barometer/barometer_bmp280.c @@ -54,51 +54,30 @@ STATIC_UNIT_TESTED bmp280_calib_param_t bmp280_cal; int32_t bmp280_up = 0; int32_t bmp280_ut = 0; -static bool bmp280_start_ut(baroDev_t * baro) -{ - UNUSED(baro); - return true; -} - -static bool bmp280_get_ut(baroDev_t * baro) -{ - UNUSED(baro); - return true; -} +// Target of the non-blocking data read, filled by the bus driver in the background +static uint8_t bmp280_data[BMP280_DATA_FRAME_SIZE]; static bool bmp280_start_up(baroDev_t * baro) { // start measurement // set oversampling + power mode (forced), and start sampling - busWrite(baro->busDev, BMP280_CTRL_MEAS_REG, BMP280_MODE); - return true; + return busWriteStart(baro->busDev, BMP280_CTRL_MEAS_REG, BMP280_MODE); } -static bool bmp280_get_up(baroDev_t * baro) +static bool bmp280_read_up(baroDev_t * baro) { - uint8_t data[BMP280_DATA_FRAME_SIZE]; - - //error free measurements - static int32_t bmp280_up_valid; - static int32_t bmp280_ut_valid; + // kick off the read of pressure and temperature, bmp280_get_up() parses it once the bus is idle + return busReadBufStart(baro->busDev, BMP280_PRESSURE_MSB_REG, bmp280_data, BMP280_DATA_FRAME_SIZE); +} - //read data from sensor - bool ack = busReadBuf(baro->busDev, BMP280_PRESSURE_MSB_REG, data, BMP280_DATA_FRAME_SIZE); +static bool bmp280_get_up(baroDev_t * baro) +{ + UNUSED(baro); - //check if pressure and temperature readings are valid, otherwise use previous measurements from the moment - if (ack) { - bmp280_up = (int32_t)((((uint32_t)(data[0])) << 12) | (((uint32_t)(data[1])) << 4) | ((uint32_t)data[2] >> 4)); - bmp280_ut = (int32_t)((((uint32_t)(data[3])) << 12) | (((uint32_t)(data[4])) << 4) | ((uint32_t)data[5] >> 4)); - bmp280_up_valid = bmp280_up; - bmp280_ut_valid = bmp280_ut; - } - else { - //assign previous valid measurements - bmp280_up = bmp280_up_valid; - bmp280_ut = bmp280_ut_valid; - } + bmp280_up = (int32_t)((((uint32_t)(bmp280_data[0])) << 12) | (((uint32_t)(bmp280_data[1])) << 4) | ((uint32_t)bmp280_data[2] >> 4)); + bmp280_ut = (int32_t)((((uint32_t)(bmp280_data[3])) << 12) | (((uint32_t)(bmp280_data[4])) << 4) | ((uint32_t)bmp280_data[5] >> 4)); - return ack; + return true; } // Returns temperature in DegC, resolution is 0.01 DegC. Output value of "5123" equals 51.23 DegC @@ -197,12 +176,17 @@ bool bmp280Detect(baroDev_t *baro) // set oversampling + power mode (forced), and start sampling busWrite(baro->busDev, BMP280_CTRL_MEAS_REG, BMP280_MODE); + // Forced mode: one measurement per cycle, pressure and temperature come out of one read + baro->combined_read = true; + baro->ut_delay = 0; - baro->get_ut = bmp280_get_ut; - baro->start_ut = bmp280_start_ut; + baro->start_ut = NULL; + baro->read_ut = NULL; + baro->get_ut = NULL; baro->up_delay = ((T_INIT_MAX + T_MEASURE_PER_OSRS_MAX * (((1 << BMP280_TEMPERATURE_OSR) >> 1) + ((1 << BMP280_PRESSURE_OSR) >> 1)) + (BMP280_PRESSURE_OSR ? T_SETUP_PRESSURE_MAX : 0) + 15) / 16) * 1000; baro->start_up = bmp280_start_up; + baro->read_up = bmp280_read_up; baro->get_up = bmp280_get_up; baro->calculate = bmp280_calculate; diff --git a/src/main/drivers/barometer/barometer_dps310.c b/src/main/drivers/barometer/barometer_dps310.c index 7f5607f95ad..a3c60f83c25 100644 --- a/src/main/drivers/barometer/barometer_dps310.c +++ b/src/main/drivers/barometer/barometer_dps310.c @@ -110,6 +110,10 @@ typedef struct { static baroState_t baroState; static uint8_t chipId[1]; +// Targets of the non-blocking reads, filled by the bus driver in the background +static uint8_t measurementStatus; // MEAS_CFG, polled for PRS_RDY before the data is fetched +static uint8_t measurementBuf[6]; + // Helper functions static uint8_t registerRead(busDevice_t * busDev, uint8_t reg) @@ -252,26 +256,37 @@ static bool deviceConfigure(busDevice_t * busDev) return true; } +// The temperature phase of the measurement cycle is used to poll MEAS_CFG, the pressure phase fetches the data +static bool deviceStartReadStatus(baroDev_t *baro) +{ + return busReadBufStart(baro->busDev, DPS310_REG_MEAS_CFG, &measurementStatus, sizeof(measurementStatus)); +} + +static bool deviceCheckStatus(baroDev_t *baro) +{ + UNUSED(baro); + + // No new pressure result yet, the cycle restarts after ut_delay + return (measurementStatus & DPS310_MEAS_CFG_PRS_RDY) != 0; +} + +static bool deviceStartReadMeasurement(baroDev_t *baro) +{ + // Kick off the read of PSR_B2, PSR_B1, PSR_B0, TMP_B2, TMP_B1, TMP_B0 + return busReadBufStart(baro->busDev, DPS310_REG_PSR_B2, measurementBuf, sizeof(measurementBuf)); +} + static bool deviceReadMeasurement(baroDev_t *baro) { - // 1. Check if pressure is ready - bool pressure_ready = registerRead(baro->busDev, DPS310_REG_MEAS_CFG) & DPS310_MEAS_CFG_PRS_RDY; - if (!pressure_ready) { - return false; - } + UNUSED(baro); - // 2. Choose scaling factors kT (for temperature) and kP (for pressure) based on the chosen precision rate. + // 1. Choose scaling factors kT (for temperature) and kP (for pressure) based on the chosen precision rate. // The scaling factors are listed in Table 9. static float kT = 253952; // 16 times (Standard) static float kP = 253952; // 16 times (Standard) - // 3. Read the pressure and temperature result from the registers - // Read PSR_B2, PSR_B1, PSR_B0, TMP_B2, TMP_B1, TMP_B0 - uint8_t buf[6]; - if (!busReadBuf(baro->busDev, DPS310_REG_PSR_B2, buf, 6)) { - return false; - } - + // 2. Pick the pressure and temperature result from the buffer filled by deviceStartReadMeasurement() + const uint8_t *buf = measurementBuf; const int32_t Praw = getTwosComplement((buf[0] << 16) + (buf[1] << 8) + buf[2], 24); const int32_t Traw = getTwosComplement((buf[3] << 16) + (buf[4] << 8) + buf[5], 24); @@ -380,12 +395,18 @@ bool baroDPS310Detect(baroDev_t *baro) const uint32_t baroDelay = 1000000 / 32 / 2; // twice the sample rate to capture all new data - baro->ut_delay = 0; + // Continuous mode, nothing needs to be triggered. The temperature phase polls PRS_RDY every baroDelay, + // the pressure phase reads the result right after the flag was seen. + baro->combined_read = false; + + baro->ut_delay = baroDelay; baro->start_ut = NULL; - baro->get_ut = NULL; + baro->read_ut = deviceStartReadStatus; + baro->get_ut = deviceCheckStatus; - baro->up_delay = baroDelay; + baro->up_delay = 1000; // one scheduler step between the status check and the data read baro->start_up = NULL; + baro->read_up = deviceStartReadMeasurement; baro->get_up = deviceReadMeasurement; baro->calculate = deviceCalculate; diff --git a/src/main/drivers/barometer/barometer_spl06.c b/src/main/drivers/barometer/barometer_spl06.c index 99870dcaee6..e463ee1ea27 100644 --- a/src/main/drivers/barometer/barometer_spl06.c +++ b/src/main/drivers/barometer/barometer_spl06.c @@ -83,44 +83,50 @@ static int32_t spl06_raw_value_scale_factor(uint8_t oversampling_rate) } } -static bool spl06_start_temperature_measurement(baroDev_t * baro) +// Targets of the non-blocking reads, filled by the bus driver in the background +static uint8_t spl06_temperature_data[SPL06_TEMPERATURE_LEN]; +static uint8_t spl06_pressure_data[SPL06_PRESSURE_LEN]; + +static int32_t spl06_raw_from_bytes(const uint8_t *data) { - return busWrite(baro->busDev, SPL06_MODE_AND_STATUS_REG, SPL06_MEAS_TEMPERATURE); + return (int32_t)((data[0] & 0x80 ? 0xFF000000 : 0) | (((uint32_t)(data[0])) << 16) | (((uint32_t)(data[1])) << 8) | ((uint32_t)data[2])); } -static bool spl06_read_temperature(baroDev_t * baro) +// Command mode: each phase triggers one measurement, waits for it and reads the three result bytes +static bool spl06_start_temperature_measurement(baroDev_t * baro) { - uint8_t data[SPL06_TEMPERATURE_LEN]; - int32_t spl06_temperature; + return busWriteStart(baro->busDev, SPL06_MODE_AND_STATUS_REG, SPL06_MEAS_TEMPERATURE); +} - bool ack = busReadBuf(baro->busDev, SPL06_TEMPERATURE_START_REG, data, SPL06_TEMPERATURE_LEN); +static bool spl06_start_read_temperature(baroDev_t * baro) +{ + return busReadBufStart(baro->busDev, SPL06_TEMPERATURE_START_REG, spl06_temperature_data, SPL06_TEMPERATURE_LEN); +} - if (ack) { - spl06_temperature = (int32_t)((data[0] & 0x80 ? 0xFF000000 : 0) | (((uint32_t)(data[0])) << 16) | (((uint32_t)(data[1])) << 8) | ((uint32_t)data[2])); - spl06_temperature_raw = spl06_temperature; - } +static bool spl06_read_temperature(baroDev_t * baro) +{ + UNUSED(baro); - return ack; + spl06_temperature_raw = spl06_raw_from_bytes(spl06_temperature_data); + return true; } static bool spl06_start_pressure_measurement(baroDev_t * baro) { - return busWrite(baro->busDev, SPL06_MODE_AND_STATUS_REG, SPL06_MEAS_PRESSURE); + return busWriteStart(baro->busDev, SPL06_MODE_AND_STATUS_REG, SPL06_MEAS_PRESSURE); } -static bool spl06_read_pressure(baroDev_t * baro) +static bool spl06_start_read_pressure(baroDev_t * baro) { - uint8_t data[SPL06_PRESSURE_LEN]; - int32_t spl06_pressure; - - bool ack = busReadBuf(baro->busDev, SPL06_PRESSURE_START_REG, data, SPL06_PRESSURE_LEN); + return busReadBufStart(baro->busDev, SPL06_PRESSURE_START_REG, spl06_pressure_data, SPL06_PRESSURE_LEN); +} - if (ack) { - spl06_pressure = (int32_t)((data[0] & 0x80 ? 0xFF000000 : 0) | (((uint32_t)(data[0])) << 16) | (((uint32_t)(data[1])) << 8) | ((uint32_t)data[2])); - spl06_pressure_raw = spl06_pressure; - } +static bool spl06_read_pressure(baroDev_t * baro) +{ + UNUSED(baro); - return ack; + spl06_pressure_raw = spl06_raw_from_bytes(spl06_pressure_data); + return true; } // Returns temperature in degrees centigrade @@ -239,12 +245,17 @@ bool spl06Detect(baroDev_t *baro) return false; } + // Command mode: temperature and pressure are measured and read in turn + baro->combined_read = false; + baro->ut_delay = SPL06_MEASUREMENT_TIME(SPL06_TEMPERATURE_OVERSAMPLING) * 1000; - baro->get_ut = spl06_read_temperature; baro->start_ut = spl06_start_temperature_measurement; + baro->read_ut = spl06_start_read_temperature; + baro->get_ut = spl06_read_temperature; baro->up_delay = SPL06_MEASUREMENT_TIME(SPL06_PRESSURE_OVERSAMPLING) * 1000; baro->start_up = spl06_start_pressure_measurement; + baro->read_up = spl06_start_read_pressure; baro->get_up = spl06_read_pressure; baro->calculate = spl06_calculate; diff --git a/src/main/drivers/bus.c b/src/main/drivers/bus.c index 71410fb2748..3453d405e6d 100644 --- a/src/main/drivers/bus.c +++ b/src/main/drivers/bus.c @@ -418,8 +418,95 @@ void busDeselectDevice(const busDevice_t * dev) #endif } -bool busIsBusy(const busDevice_t * dev) +bool busReadBufStart(const busDevice_t * dev, uint8_t reg, uint8_t * data, uint8_t length) { +#if !defined(USE_SPI) && !defined(USE_I2C) + UNUSED(reg); + UNUSED(data); + UNUSED(length); +#endif + switch (dev->busType) { + case BUSTYPE_SPI: +#ifdef USE_SPI + // SPI is fast and synchronous, complete the read right away + return busReadBuf(dev, reg, data, length); +#else + return false; +#endif + + case BUSTYPE_I2C: +#ifdef USE_I2C + return i2cBusReadBufferStart(dev, reg, data, length); +#else + return false; +#endif + + default: + return false; + } +} + +bool busWriteStart(const busDevice_t * dev, uint8_t reg, uint8_t data) +{ +#if !defined(USE_SPI) && !defined(USE_I2C) + UNUSED(reg); + UNUSED(data); +#endif + switch (dev->busType) { + case BUSTYPE_SPI: +#ifdef USE_SPI + // SPI is fast and synchronous, complete the write right away + return busWrite(dev, reg, data); +#else + return false; +#endif + + case BUSTYPE_I2C: +#ifdef USE_I2C + return i2cBusWriteRegisterStart(dev, reg, data); +#else + return false; +#endif + + default: + return false; + } +} + +bool busWriteBufStart(const busDevice_t * dev, uint8_t reg, const uint8_t * data, uint8_t length) +{ +#if !defined(USE_SPI) && !defined(USE_I2C) + UNUSED(reg); + UNUSED(data); + UNUSED(length); +#endif + switch (dev->busType) { + case BUSTYPE_SPI: +#ifdef USE_SPI + // SPI is fast and synchronous, complete the write right away + return busWriteBuf(dev, reg, data, length); +#else + return false; +#endif + + case BUSTYPE_I2C: +#ifdef USE_I2C + return i2cBusWriteBufferStart(dev, reg, data, length); +#else + return false; +#endif + + default: + return false; + } +} + +bool busIsBusy(const busDevice_t * dev, bool * error) +{ + if (error) { + *error = false; + } + switch (dev->busType) { case BUSTYPE_SPI: #ifdef USE_SPI @@ -430,7 +517,7 @@ bool busIsBusy(const busDevice_t * dev) #endif case BUSTYPE_I2C: #ifdef USE_I2C - return i2cBusBusy(dev,NULL); + return i2cBusBusy(dev, error); #else UNUSED(dev); return false; diff --git a/src/main/drivers/bus.h b/src/main/drivers/bus.h index 0416f516ea1..fe2a9fd2e00 100644 --- a/src/main/drivers/bus.h +++ b/src/main/drivers/bus.h @@ -284,6 +284,17 @@ extern const busDeviceDescriptor_t __busdev_registry_end[]; #endif // busTransfer and busTransferMultiple are supported only on full-duplex SPI bus +/* + * Result of one step of a sensor read made of several non-blocking transfers (status poll, trigger, data). + * The sensor layer calls the driver's readStart(dev, firstStep) with firstStep set for the first transfer and + * again after each transfer completed, until the last one is started; read() then only parses the data. + */ +typedef enum { + BUS_READ_STEP_BUSY = 0, // nothing was started, the bus is busy - call again later + BUS_READ_STEP_NEXT, // an intermediate transfer was started, call readStart() again once it is done + BUS_READ_STEP_LAST, // the final transfer was started, call read() once it is done +} busReadStepResult_e; + typedef struct busTransferDescriptor_s { uint8_t * rxBuf; const uint8_t * txBuf; @@ -295,6 +306,9 @@ bool i2cBusWriteBuffer(const busDevice_t * dev, uint8_t reg, const uint8_t * dat bool i2cBusWriteRegister(const busDevice_t * dev, uint8_t reg, uint8_t data); bool i2cBusReadBuffer(const busDevice_t * dev, uint8_t reg, uint8_t * data, uint8_t length); bool i2cBusReadRegister(const busDevice_t * dev, uint8_t reg, uint8_t * data); +bool i2cBusReadBufferStart(const busDevice_t * dev, uint8_t reg, uint8_t * data, uint8_t length); +bool i2cBusWriteRegisterStart(const busDevice_t * dev, uint8_t reg, uint8_t data); +bool i2cBusWriteBufferStart(const busDevice_t * dev, uint8_t reg, const uint8_t * data, uint8_t length); bool i2cBusBusy(const busDevice_t *dev, bool *error); bool spiBusInitHost(const busDevice_t * dev); @@ -336,4 +350,9 @@ bool busWrite(const busDevice_t * busdev, uint8_t reg, uint8_t data); bool busTransfer(const busDevice_t * dev, uint8_t * rxBuf, const uint8_t * txBuf, int length); bool busTransferMultiple(const busDevice_t * dev, busTransferDescriptor_t * buffers, int count); -bool busIsBusy(const busDevice_t * dev); +/* Non-blocking register access. Start the transfer, then poll busIsBusy() until it reports idle and check error. + * On SPI the transfer completes inside the start call. */ +bool busReadBufStart(const busDevice_t * dev, uint8_t reg, uint8_t * data, uint8_t length); +bool busWriteStart(const busDevice_t * dev, uint8_t reg, uint8_t data); +bool busWriteBufStart(const busDevice_t * dev, uint8_t reg, const uint8_t * data, uint8_t length); // data must stay valid until busIsBusy() reports idle +bool busIsBusy(const busDevice_t * dev, bool * error); diff --git a/src/main/drivers/bus_busdev_i2c.c b/src/main/drivers/bus_busdev_i2c.c index fb255278d5b..370d7f308dc 100644 --- a/src/main/drivers/bus_busdev_i2c.c +++ b/src/main/drivers/bus_busdev_i2c.c @@ -53,13 +53,26 @@ bool i2cBusReadRegister(const busDevice_t * dev, uint8_t reg, uint8_t * data) const bool allowRawAccess = (dev->flags & DEVFLAGS_USE_RAW_REGISTERS); return i2cRead(dev->busdev.i2c.i2cBus, dev->busdev.i2c.address, reg, 1, data, allowRawAccess); } +bool i2cBusReadBufferStart(const busDevice_t * dev, uint8_t reg, uint8_t * data, uint8_t length) +{ + const bool allowRawAccess = (dev->flags & DEVFLAGS_USE_RAW_REGISTERS); + return i2cReadStart(dev->busdev.i2c.i2cBus, dev->busdev.i2c.address, reg, length, data, allowRawAccess); +} + +bool i2cBusWriteRegisterStart(const busDevice_t * dev, uint8_t reg, uint8_t data) +{ + const bool allowRawAccess = (dev->flags & DEVFLAGS_USE_RAW_REGISTERS); + return i2cWriteStart(dev->busdev.i2c.i2cBus, dev->busdev.i2c.address, reg, data, allowRawAccess); +} + +bool i2cBusWriteBufferStart(const busDevice_t * dev, uint8_t reg, const uint8_t * data, uint8_t length) +{ + const bool allowRawAccess = (dev->flags & DEVFLAGS_USE_RAW_REGISTERS); + return i2cWriteBufferStart(dev->busdev.i2c.i2cBus, dev->busdev.i2c.address, reg, length, data, allowRawAccess); +} + bool i2cBusBusy(const busDevice_t *dev, bool *error) -{ -#if defined(AT32F43x) - return i2cBusy(dev->busdev.i2c.i2cBus, error); -#endif - UNUSED(dev); - UNUSED(error); - return false; +{ + return i2cBusy(dev->busdev.i2c.i2cBus, dev->busdev.i2c.address, error); } #endif diff --git a/src/main/drivers/bus_i2c.h b/src/main/drivers/bus_i2c.h index bf685b1bfae..cd6f6578ebe 100644 --- a/src/main/drivers/bus_i2c.h +++ b/src/main/drivers/bus_i2c.h @@ -56,7 +56,7 @@ typedef struct i2cDevice_s { ioTag_t sda; rccPeriphTag_t rcc; I2CSpeed speed; -#if defined(STM32F7) || defined(STM32H7) || defined(AT32F43x) +#if defined(STM32F4) || defined(STM32F7) || defined(STM32H7) || defined(AT32F43x) uint8_t ev_irq; uint8_t er_irq; uint8_t af; @@ -68,6 +68,34 @@ void i2cInit(I2CDevice device); bool i2cWriteBuffer(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess); bool i2cWrite(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t data, bool allowRawAccess); bool i2cRead(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, uint8_t* buf, bool allowRawAccess); -bool i2cBusy(I2CDevice device, bool *error); + +// Non-blocking transfers: start returns immediately (false if the bus is busy or the transfer could not be started), +// completion and the result are polled with i2cBusy(). Platforms without an asynchronous driver complete the +// transfer synchronously inside the start call and report the bus as idle. +bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, uint8_t* buf, bool allowRawAccess); +bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t data, bool allowRawAccess); +bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, const uint8_t *data, bool allowRawAccess); // data must stay valid until i2cBusy() reports idle +bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error); // pending state and outcome of the given slave's transfer + +// Outcome of the last completed non-blocking transfer of every 7-bit slave address on one bus. The platform drivers +// keep one per bus so that a device still reads its own result after another device has used the bus in between. +typedef struct { + volatile uint32_t failed[4]; // one bit per address, set = the last transfer to that address failed +} i2cAddrResults_t; + +static inline void i2cAddrResultSet(i2cAddrResults_t *results, uint8_t addr_, bool error) +{ + const uint32_t mask = 1u << (addr_ & 31); + if (error) { + results->failed[(addr_ >> 5) & 3] |= mask; + } else { + results->failed[(addr_ >> 5) & 3] &= ~mask; + } +} + +static inline bool i2cAddrResultFailed(const i2cAddrResults_t *results, uint8_t addr_) +{ + return (results->failed[(addr_ >> 5) & 3] >> (addr_ & 31)) & 1u; +} uint16_t i2cGetErrorCounter(void); diff --git a/src/main/drivers/bus_i2c_at32f43x.c b/src/main/drivers/bus_i2c_at32f43x.c index 39e2d008ff6..74e8f8e42b7 100644 --- a/src/main/drivers/bus_i2c_at32f43x.c +++ b/src/main/drivers/bus_i2c_at32f43x.c @@ -19,6 +19,9 @@ #include #include + +#include "common/maths.h" +#include "build/debug.h" #include "io_impl.h" #include "drivers/io.h" #include "drivers/time.h" @@ -88,10 +91,52 @@ static volatile uint16_t i2cErrorCount = 0; typedef struct { bool initialised; i2c_handle_type handle; + + // Interrupt driven transfer started by i2cReadStart() / i2cWriteStart(). The i2c_application layer finishes it + // from the interrupt handlers: handle.status becomes I2C_END, or handle.error_code reports the failure. + bool pending; + uint8_t addr; // 7-bit address of the current / last non-blocking transfer + timeUs_t startUs; // start time of the transfer, for the debug statistics + uint16_t lastPcount; // bytes left at the previous look, a change means the transfer moves + uint32_t stuckUs; // time looked at without progress, a long gap between looks counts as I2C_STUCK_LOOK_GAP_US + timeUs_t lookUs; // time of the previous look + uint8_t txByte; // data of a non-blocking single byte write, must outlive the call + i2cAddrResults_t addrResults; // outcome per slave address, survives i2cInit() } i2cState_t; static i2cState_t i2cState[I2CDEV_COUNT]; +// Transfer statistics shown with debug_mode = I2C, shared by all buses +typedef struct { + uint16_t eventIrqs; // interrupts during the current / last transfer + uint16_t errorIrqs; // error interrupts / aborted transfers since boot + uint16_t lastTransferUs; // start to completion of the last non-blocking transfer + uint16_t startCallUs; // time spent in the last i2cStartTransfer() call +} i2cDebugStats_t; + +static i2cDebugStats_t i2cStats; + +static void i2cDebugPublish(void) +{ + DEBUG_SET(DEBUG_I2C, 0, i2cStats.eventIrqs); + DEBUG_SET(DEBUG_I2C, 1, i2cStats.errorIrqs); + DEBUG_SET(DEBUG_I2C, 2, i2cStats.lastTransferUs); + DEBUG_SET(DEBUG_I2C, 5, i2cErrorCount); + DEBUG_SET(DEBUG_I2C, 7, i2cStats.startCallUs); +} + +static void i2cEventIrq(I2CDevice device) +{ + i2cStats.eventIrqs++; + i2c_evt_irq_handler(&i2cState[device].handle); +} + +static void i2cErrorIrq(I2CDevice device) +{ + i2cStats.errorIrqs++; + i2c_err_irq_handler(&i2cState[device].handle); +} + void i2cSetSpeed(uint8_t speed) { for (unsigned int i = 0; i < ARRAYLEN(i2cHardwareMap); i++) { @@ -102,42 +147,223 @@ void i2cSetSpeed(uint8_t speed) //I2C1_ERR_IRQHandler void I2C1_ERR_IRQHandler(void) { - i2c_err_irq_handler(&i2cState[I2CDEV_1].handle); + i2cErrorIrq(I2CDEV_1); } void I2C1_EVT_IRQHandler(void) { - i2c_evt_irq_handler(&i2cState[I2CDEV_1].handle); + i2cEventIrq(I2CDEV_1); } void I2C2_ERR_IRQHandler(void) { - i2c_err_irq_handler(&i2cState[I2CDEV_2].handle); + i2cErrorIrq(I2CDEV_2); } void I2C2_EVT_IRQHandler(void) { - i2c_evt_irq_handler(&i2cState[I2CDEV_2].handle); + i2cEventIrq(I2CDEV_2); } void I2C3_ERR_IRQHandler(void) { - i2c_err_irq_handler(&i2cState[I2CDEV_3].handle); + i2cErrorIrq(I2CDEV_3); } void I2C3_EVT_IRQHandler(void) { - i2c_evt_irq_handler(&i2cState[I2CDEV_3].handle); + i2cEventIrq(I2CDEV_3); } static bool i2cHandleHardwareFailure(I2CDevice device) { - (void)device; i2cErrorCount++; i2cInit(device); return false; } +// A transfer is stuck when it made no progress for I2C_TIMEOUT while being looked at. A gap between two looks longer +// than I2C_STUCK_LOOK_GAP_US counts as that much only: a main loop that was busy elsewhere for a while (a settings save) +// does not make the transfer stuck, the interrupts carry it on however seldom somebody looks +#define I2C_STUCK_LOOK_GAP_US 1000 + +static bool i2cTransferStuck(i2cState_t * state) +{ + const timeUs_t now = micros(); + const uint16_t pcount = state->handle.pcount; + + if (pcount != state->lastPcount) { + state->lastPcount = pcount; + state->stuckUs = 0; + } + else { + state->stuckUs += MIN((uint32_t)cmpTimeUs(now, state->lookUs), (uint32_t)I2C_STUCK_LOOK_GAP_US); + } + state->lookUs = now; + + return state->stuckUs >= I2C_TIMEOUT; +} + +// Pick up the outcome of a pending interrupt driven transfer and reset a stuck one +static void i2cPollPending(I2CDevice device) +{ + i2cState_t * state = &(i2cState[device]); + + if (!state->pending) { + return; + } + + // The end-of-transfer status is private to i2c_application.c, i2c_wait_end() with a zero timeout only probes it: + // I2C_ERR_TIMEOUT means the transfer is still running, anything else means it finished + if (state->handle.error_code != I2C_OK || i2c_wait_end(&state->handle, 0) != I2C_ERR_TIMEOUT) { + i2cStats.lastTransferUs = micros() - state->startUs; + if (state->handle.error_code != I2C_OK) { + i2cErrorCount++; // keep the "I2C Errors" count of status / MSP meaningful for non-blocking transfers + } + i2cAddrResultSet(&state->addrResults, state->addr, state->handle.error_code != I2C_OK); + state->pending = false; + } + else if (i2cTransferStuck(state)) { + // No progress within the timeout, the transfer is stuck - reset the peripheral + i2cHandleHardwareFailure(device); + state->handle.error_code = I2C_ERR_TIMEOUT; + i2cAddrResultSet(&state->addrResults, state->addr, true); + } +} + +// Block until no interrupt driven transfer is in progress +static void i2cWaitForIdle(I2CDevice device) +{ + do { + i2cPollPending(device); + } while (i2cState[device].pending); +} + +/* + * Start an interrupt driven transfer. The i2c_application layer sends the slave and register address synchronously + * (a few tens of microseconds), the data phase runs from the interrupt handlers. + * Returns false if the bus is busy or the transfer could not be started. + */ +static bool i2cStartTransfer(I2CDevice device, uint8_t addr_, uint8_t reg_, bool allowRawAccess, bool reading, uint8_t len, uint8_t *buf) +{ + if (device == I2CINVALID || device >= I2CDEV_COUNT) + return false; + + i2cState_t * state = &(i2cState[device]); + + if (!state->initialised) + return false; + + if (reading && len == 0) + return false; + + i2cPollPending(device); + if (state->pending) + return false; + + const timeUs_t callStartUs = micros(); + i2cStats.eventIrqs = 0; + + i2c_status_type status; + + if (reading) { + if (reg_ == 0xFF && allowRawAccess) { + status = i2c_master_receive_int(&state->handle, addr_ << 1, buf, len, I2C_DEFAULT_TIMEOUT); + } + else { + status = i2c_memory_read_int(&state->handle, I2C_MEM_ADDR_WIDIH_8, addr_ << 1, reg_, buf, len, I2C_DEFAULT_TIMEOUT); + } + } + else if (len == 0) { + if (reg_ == 0xFF && allowRawAccess) { + return false; // nothing to send + } + // Register byte alone, sent as a plain one byte transfer + state->txByte = reg_; + status = i2c_master_transmit_int(&state->handle, addr_ << 1, &state->txByte, 1, I2C_DEFAULT_TIMEOUT); + } + else { + if (reg_ == 0xFF && allowRawAccess) { + status = i2c_master_transmit_int(&state->handle, addr_ << 1, buf, len, I2C_DEFAULT_TIMEOUT); + } + else { + status = i2c_memory_write_int(&state->handle, I2C_MEM_ADDR_WIDIH_8, addr_ << 1, reg_, buf, len, I2C_DEFAULT_TIMEOUT); + } + } + + if (status == I2C_ERR_STEP_1) { + return false; // bus still busy, try again later + } + + if (status != I2C_OK) { + /* wait for the stop flag to be set and clear it */ + i2c_wait_flag(&state->handle, I2C_STOPF_FLAG, I2C_EVENT_CHECK_NONE, I2C_DEFAULT_TIMEOUT); + i2c_flag_clear(state->handle.i2cx, I2C_STOPF_FLAG); + return i2cHandleHardwareFailure(device); + } + + state->addr = addr_; + state->startUs = callStartUs; + state->lastPcount = state->handle.pcount; + state->stuckUs = 0; + state->lookUs = callStartUs; + state->pending = true; + + i2cStats.startCallUs = micros() - callStartUs; + i2cDebugPublish(); + + return true; +} + +bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t* buf, bool allowRawAccess) +{ + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, true, len, buf); +} + +bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) +{ + // the platform API takes a non-const buffer, the data is only read + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, len_, (uint8_t *)data); +} + +bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t data, bool allowRawAccess) +{ + if (device == I2CINVALID || device >= I2CDEV_COUNT) + return false; + + i2cPollPending(device); + if (i2cState[device].pending) + return false; // don't touch txByte while it may still be going out + + i2cState[device].txByte = data; + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, 1, &i2cState[device].txByte); +} + +bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) +{ + if (device == I2CINVALID || device >= I2CDEV_COUNT) { + if (error) { + *error = true; + } + return false; + } + + i2cState_t * state = &(i2cState[device]); + + i2cPollPending(device); + + // Only the owner of the transfer on the bus is pending, everybody else gets the outcome of their own last transfer + const bool pending = state->pending && state->addr == addr_; + + if (error) { + *error = !pending && i2cAddrResultFailed(&state->addrResults, addr_); + } + + i2cDebugPublish(); + + return pending; +} + bool i2cWriteBuffer(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) { if (device == I2CINVALID) @@ -147,7 +373,10 @@ bool i2cWriteBuffer(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, if (!state->initialised) return false; - + + // Let a non-blocking transfer of another device finish first + i2cWaitForIdle(device); + i2c_status_type status; if ((reg_ == 0xFF || len_ == 0) && allowRawAccess) { @@ -200,7 +429,9 @@ bool i2cRead(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t if (!state->initialised) return false; - //HAL_StatusTypeDef status; + // Let a non-blocking transfer of another device finish first + i2cWaitForIdle(device); + i2c_status_type status; if (reg_ == 0xFF && allowRawAccess) { status = i2c_master_receive(&state->handle, addr_ << 1,buf, len, I2C_DEFAULT_TIMEOUT); @@ -416,7 +647,8 @@ void i2cInit(I2CDevice device) nvic_irq_enable(hardware->ev_irq, NVIC_PRIO_I2C_EV,0); i2c_enable(pHandle->i2cx, TRUE); - + + state->pending = false; state->initialised = true; } @@ -463,27 +695,5 @@ static void i2cUnstick(IO_t scl, IO_t sda) IOHi(sda); // Set bus sda high } -bool i2cBusy(I2CDevice device, bool *error) -{ - if (device == I2CINVALID) - return true; - - i2cState_t * state = &(i2cState[device]); - - if (error) { - *error = state->handle.error_code==I2C_OK?false:true; - } - - if(state->handle.error_code ==I2C_OK){ - - if (i2c_flag_get(state->handle.i2cx, I2C_BUSYF_FLAG) == SET) - { - return true; - } - return false; - } - - return true; -} #endif diff --git a/src/main/drivers/bus_i2c_hal.c b/src/main/drivers/bus_i2c_hal.c index 3b1459ab1fb..cfedbc211f0 100644 --- a/src/main/drivers/bus_i2c_hal.c +++ b/src/main/drivers/bus_i2c_hal.c @@ -20,6 +20,11 @@ #include +#include "build/debug.h" + +#include "common/utils.h" +#include "common/maths.h" + #include "drivers/io.h" #include "drivers/time.h" @@ -101,10 +106,109 @@ static volatile uint16_t i2cErrorCount = 0; typedef struct { bool initialised; I2C_HandleTypeDef handle; + + // Interrupt driven transfer started by i2cReadStart() / i2cWriteStart(), finished by the HAL callbacks below + volatile bool busy; + volatile bool error; + uint8_t addr; // 7-bit address of the current / last non-blocking transfer + timeUs_t startUs; // start time of the transfer, for the debug statistics + uint16_t lastXferCount; // bytes left at the previous look, a change means the transfer moves + uint32_t stuckUs; // time looked at without progress, a long gap between looks counts as I2C_STUCK_LOOK_GAP_US + timeUs_t lookUs; // time of the previous look + uint8_t txByte; // data of a non-blocking single byte write, must outlive the call + i2cAddrResults_t addrResults; // outcome per slave address, survives i2cInit() } i2cState_t; static i2cState_t i2cState[I2CDEV_COUNT]; +// Transfer statistics shown with debug_mode = I2C, shared by all buses +typedef struct { + uint16_t eventIrqs; // event interrupts during the current / last transfer + uint16_t errorIrqs; // error interrupts since boot + uint16_t lastTransferUs; // start to completion of the last non-blocking transfer + uint16_t startCallUs; // time spent in the last i2cStartTransfer() call +} i2cDebugStats_t; + +static i2cDebugStats_t i2cStats; + +static void i2cDebugPublish(void) +{ + DEBUG_SET(DEBUG_I2C, 0, i2cStats.eventIrqs); + DEBUG_SET(DEBUG_I2C, 1, i2cStats.errorIrqs); + DEBUG_SET(DEBUG_I2C, 2, i2cStats.lastTransferUs); + DEBUG_SET(DEBUG_I2C, 5, i2cErrorCount); + DEBUG_SET(DEBUG_I2C, 7, i2cStats.startCallUs); +} + +static void i2cEventIrq(I2CDevice device) +{ + i2cStats.eventIrqs++; + HAL_I2C_EV_IRQHandler(&i2cState[device].handle); +} + +static void i2cErrorIrq(I2CDevice device) +{ + i2cStats.errorIrqs++; + HAL_I2C_ER_IRQHandler(&i2cState[device].handle); +} + +static i2cState_t *i2cStateFromHandle(const I2C_HandleTypeDef *hi2c) +{ + for (unsigned i = 0; i < ARRAYLEN(i2cState); i++) { + if (&i2cState[i].handle == hi2c) { + return &i2cState[i]; + } + } + return NULL; +} + +// HAL completion hooks, called from the I2C interrupt handlers once an interrupt driven transfer is over +static void i2cTransferFinished(I2C_HandleTypeDef *hi2c, bool error) +{ + i2cState_t *state = i2cStateFromHandle(hi2c); + if (!state) { + return; + } + + i2cStats.lastTransferUs = microsISR() - state->startUs; + state->error = error; + if (error) { + i2cErrorCount++; // keep the "I2C Errors" count of status / MSP meaningful for non-blocking transfers + } + i2cAddrResultSet(&state->addrResults, state->addr, error); + state->busy = false; +} + +void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + i2cTransferFinished(hi2c, false); +} + +void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + i2cTransferFinished(hi2c, false); +} + +void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + i2cTransferFinished(hi2c, false); +} + +void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + i2cTransferFinished(hi2c, false); +} + +void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) +{ + i2cTransferFinished(hi2c, true); +} + +void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c) +{ + i2cTransferFinished(hi2c, true); +} + void i2cSetSpeed(uint8_t speed) { for (unsigned int i = 0; i < ARRAYLEN(i2cHardwareMap); i++) { @@ -114,43 +218,43 @@ void i2cSetSpeed(uint8_t speed) void I2C1_ER_IRQHandler(void) { - HAL_I2C_ER_IRQHandler(&i2cState[I2CDEV_1].handle); + i2cErrorIrq(I2CDEV_1); } void I2C1_EV_IRQHandler(void) { - HAL_I2C_EV_IRQHandler(&i2cState[I2CDEV_1].handle); + i2cEventIrq(I2CDEV_1); } void I2C2_ER_IRQHandler(void) { - HAL_I2C_ER_IRQHandler(&i2cState[I2CDEV_2].handle); + i2cErrorIrq(I2CDEV_2); } void I2C2_EV_IRQHandler(void) { - HAL_I2C_EV_IRQHandler(&i2cState[I2CDEV_2].handle); + i2cEventIrq(I2CDEV_2); } void I2C3_ER_IRQHandler(void) { - HAL_I2C_ER_IRQHandler(&i2cState[I2CDEV_3].handle); + i2cErrorIrq(I2CDEV_3); } void I2C3_EV_IRQHandler(void) { - HAL_I2C_EV_IRQHandler(&i2cState[I2CDEV_3].handle); + i2cEventIrq(I2CDEV_3); } #ifdef USE_I2C_DEVICE_4 void I2C4_ER_IRQHandler(void) { - HAL_I2C_ER_IRQHandler(&i2cState[I2CDEV_4].handle); + i2cErrorIrq(I2CDEV_4); } void I2C4_EV_IRQHandler(void) { - HAL_I2C_EV_IRQHandler(&i2cState[I2CDEV_4].handle); + i2cEventIrq(I2CDEV_4); } #endif @@ -162,6 +266,169 @@ static bool i2cHandleHardwareFailure(I2CDevice device) return false; } +// Reset the peripheral after a transfer that did not complete and record the failure for the transfer's owner +static void i2cRecoverStuckTransfer(I2CDevice device) +{ + i2cState_t * state = &(i2cState[device]); + + i2cHandleHardwareFailure(device); + state->error = true; + i2cAddrResultSet(&state->addrResults, state->addr, true); +} + +// A transfer is stuck when it made no progress for I2C_TIMEOUT while being looked at. A gap between two looks longer +// than I2C_STUCK_LOOK_GAP_US counts as that much only: a main loop that was busy elsewhere for a while (a settings save) +// does not make the transfer stuck, the interrupts carry it on however seldom somebody looks +#define I2C_STUCK_LOOK_GAP_US 1000 + +static bool i2cTransferStuck(i2cState_t * state) +{ + const timeUs_t now = micros(); + const uint16_t xferCount = state->handle.XferCount; + + if (xferCount != state->lastXferCount) { + state->lastXferCount = xferCount; + state->stuckUs = 0; + } + else { + state->stuckUs += MIN((uint32_t)cmpTimeUs(now, state->lookUs), (uint32_t)I2C_STUCK_LOOK_GAP_US); + } + state->lookUs = now; + + return state->stuckUs >= I2C_TIMEOUT; +} + +// Block until no interrupt driven transfer is in progress. Returns false if a stuck transfer had to be aborted. +static bool i2cWaitForIdle(I2CDevice device) +{ + i2cState_t * state = &(i2cState[device]); + + while (state->busy) { + if (i2cTransferStuck(state)) { + i2cRecoverStuckTransfer(device); + return false; + } + } + + return true; +} + +// Start an interrupt driven transfer. Returns false if the bus is busy or the transfer could not be started. +static bool i2cStartTransfer(I2CDevice device, uint8_t addr_, uint8_t reg_, bool allowRawAccess, bool reading, uint8_t len, uint8_t *buf) +{ + if (device == I2CINVALID || device >= I2CDEV_COUNT) + return false; + + i2cState_t * state = &(i2cState[device]); + + if (!state->initialised || state->busy) + return false; + + if (reading && len == 0) + return false; + + const timeUs_t callStartUs = micros(); + i2cStats.eventIrqs = 0; + + state->error = false; + state->addr = addr_; + state->startUs = callStartUs; + state->busy = true; + + HAL_StatusTypeDef status; + + if (reading) { + if (reg_ == 0xFF && allowRawAccess) { + status = HAL_I2C_Master_Receive_IT(&state->handle, addr_ << 1, buf, len); + } + else { + status = HAL_I2C_Mem_Read_IT(&state->handle, addr_ << 1, reg_, I2C_MEMADD_SIZE_8BIT, buf, len); + } + } + else if (len == 0) { + if (reg_ == 0xFF && allowRawAccess) { + state->busy = false; + return false; // nothing to send + } + // Register byte alone, the HAL refuses zero length transfers + state->txByte = reg_; + status = HAL_I2C_Master_Transmit_IT(&state->handle, addr_ << 1, &state->txByte, 1); + } + else { + if (reg_ == 0xFF && allowRawAccess) { + status = HAL_I2C_Master_Transmit_IT(&state->handle, addr_ << 1, buf, len); + } + else { + status = HAL_I2C_Mem_Write_IT(&state->handle, addr_ << 1, reg_, I2C_MEMADD_SIZE_8BIT, buf, len); + } + } + + if (status != HAL_OK) { + state->busy = false; + if (status == HAL_BUSY) { + return false; // HAL is still finishing the previous transfer (STOP in progress), try again later + } + return i2cHandleHardwareFailure(device); + } + + state->lastXferCount = state->handle.XferCount; + state->stuckUs = 0; + state->lookUs = callStartUs; + + i2cStats.startCallUs = micros() - callStartUs; + i2cDebugPublish(); + + return true; +} + +bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t* buf, bool allowRawAccess) +{ + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, true, len, buf); +} + +bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) +{ + // the platform API takes a non-const buffer, the data is only read + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, len_, (uint8_t *)data); +} + +bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t data, bool allowRawAccess) +{ + if (device == I2CINVALID || device >= I2CDEV_COUNT || i2cState[device].busy) + return false; // don't touch txByte while it may still be going out + + i2cState[device].txByte = data; + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, 1, &i2cState[device].txByte); +} + +bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) +{ + if (device == I2CINVALID || device >= I2CDEV_COUNT) { + if (error) { + *error = true; + } + return false; + } + + i2cState_t * state = &(i2cState[device]); + + if (state->busy && i2cTransferStuck(state)) { + // No progress within the timeout, the transfer is stuck - reset the peripheral + i2cRecoverStuckTransfer(device); + } + + // Only the owner of the transfer on the bus is pending, everybody else gets the outcome of their own last transfer + const bool pending = state->busy && state->addr == addr_; + + if (error) { + *error = !pending && i2cAddrResultFailed(&state->addrResults, addr_); + } + + i2cDebugPublish(); + + return pending; +} + bool i2cWriteBuffer(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) { if (device == I2CINVALID) @@ -172,9 +439,18 @@ bool i2cWriteBuffer(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, if (!state->initialised) return false; + // Let a non-blocking transfer of another device finish first + if (!i2cWaitForIdle(device)) + return false; + HAL_StatusTypeDef status; - if ((reg_ == 0xFF || len_ == 0) && allowRawAccess) { + if (len_ == 0 && !(reg_ == 0xFF && allowRawAccess)) { + // Register byte alone, the HAL refuses zero length transfers + uint8_t regByte = reg_; + status = HAL_I2C_Master_Transmit(&state->handle, addr_ << 1, ®Byte, 1, I2C_DEFAULT_TIMEOUT); + } + else if ((reg_ == 0xFF || len_ == 0) && allowRawAccess) { status = HAL_I2C_Master_Transmit(&state->handle, addr_ << 1, (uint8_t *)data, len_, I2C_DEFAULT_TIMEOUT); } else { @@ -202,6 +478,10 @@ bool i2cRead(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t if (!state->initialised) return false; + // Let a non-blocking transfer of another device finish first + if (!i2cWaitForIdle(device)) + return false; + HAL_StatusTypeDef status; if (reg_ == 0xFF && allowRawAccess) { @@ -333,6 +613,13 @@ void i2cInit(I2CDevice device) IOConfigGPIOAF(sda, IOCFG_I2C, hardware->af); // Init I2C peripheral + if (state->initialised) { + // Re-initialisation after a failure: drop whatever transfer the HAL still thinks is running + HAL_I2C_DeInit(pHandle); + } + state->busy = false; + state->error = false; + pHandle->Instance = hardware->dev; /* diff --git a/src/main/drivers/bus_i2c_rp2350.c b/src/main/drivers/bus_i2c_rp2350.c index cc1d5240c2d..b3714b28501 100644 --- a/src/main/drivers/bus_i2c_rp2350.c +++ b/src/main/drivers/bus_i2c_rp2350.c @@ -216,13 +216,30 @@ bool i2cRead(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, return true; } -bool i2cBusy(I2CDevice device, bool *error) +// Non-blocking transfers are not implemented for this platform yet - complete them synchronously +bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, uint8_t* buf, bool allowRawAccess) +{ + return i2cRead(device, addr_, reg, len, buf, allowRawAccess); +} + +bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) +{ + return i2cWriteBuffer(device, addr_, reg_, len_, data, allowRawAccess); +} + +bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t data, bool allowRawAccess) +{ + return i2cWrite(device, addr_, reg, data, allowRawAccess); +} + +bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) { UNUSED(device); + UNUSED(addr_); if (error) { *error = false; } - /* Blocking implementation — transfers complete before returning */ + /* Blocking implementation - transfers complete before returning */ return false; } diff --git a/src/main/drivers/bus_i2c_soft.c b/src/main/drivers/bus_i2c_soft.c index 5c7d866970e..aa6f13c30a7 100644 --- a/src/main/drivers/bus_i2c_soft.c +++ b/src/main/drivers/bus_i2c_soft.c @@ -290,6 +290,33 @@ bool i2cRead(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, uint8_t * return true; } +// Non-blocking transfers are not implemented for this platform yet - complete them synchronously +bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t* buf, bool allowRawAccess) +{ + return i2cRead(device, addr_, reg_, len, buf, allowRawAccess); +} + +bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) +{ + return i2cWriteBuffer(device, addr_, reg_, len_, data, allowRawAccess); +} + +bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t data, bool allowRawAccess) +{ + return i2cWrite(device, addr_, reg_, data, allowRawAccess); +} + +bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) +{ + UNUSED(device); + UNUSED(addr_); + if (error) { + *error = false; + } + // Blocking driver - a transfer is finished when the start call returns + return false; +} + uint16_t i2cGetErrorCounter(void) { return i2cErrorCount; diff --git a/src/main/drivers/bus_i2c_stm32f40x.c b/src/main/drivers/bus_i2c_stm32f40x.c index cc0ed558fc3..434a14fb34a 100644 --- a/src/main/drivers/bus_i2c_stm32f40x.c +++ b/src/main/drivers/bus_i2c_stm32f40x.c @@ -1,29 +1,40 @@ /* - * This file is part of Cleanflight. + * This file is part of INAV. * - * Cleanflight is free software: you can redistribute it and/or modify + * INAV is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Cleanflight is distributed in the hope that it will be useful, + * INAV is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License - * along with Cleanflight. If not, see . + * along with INAV. If not, see . + * + * Interrupt driven I2C master for STM32F4. The transfer engine (event and + * error handlers) is derived from the Betaflight bus_i2c_stm32f4xx.c driver. + * + * A transfer is started from task context and completed by the I2Cx_EV and + * I2Cx_ER interrupts. i2cRead()/i2cWrite() block until the transfer is done, + * i2cReadStart()/i2cWriteStart() return immediately and the caller polls + * i2cBusy(). A blocking call issued while a non-blocking transfer is in + * progress waits for it to finish first, so the two can share a bus. */ #include #include #include +#include #include -#include "build/atomic.h" +#include "build/debug.h" #include "common/utils.h" +#include "common/maths.h" #include "drivers/io.h" #include "drivers/time.h" @@ -32,16 +43,15 @@ #include "drivers/nvic.h" #include "io_impl.h" #include "rcc.h" -#include "drivers/light_led.h" #ifndef SOFT_I2C -static void i2cUnstick(IO_t scl, IO_t sda); +// Upper bound for the short waits on START/STOP bit release inside the handlers. +// Normally these clear within one SCL period; a longer wait means a stuck bus. +#define I2C_BIT_RELEASE_TIMEOUT_US 1000 #define GPIO_AF_I2C GPIO_AF_I2C1 -#ifdef STM32F4 - #if defined(USE_I2C_PULLUP) #define IOCFG_I2C IO_CONFIG(GPIO_Mode_AF, GPIO_Speed_50MHz, GPIO_OType_OD, GPIO_PuPd_UP) #else @@ -55,405 +65,147 @@ static void i2cUnstick(IO_t scl, IO_t sda); #define I2C1_SDA PB9 #endif -#else - -#ifndef I2C1_SCL -#define I2C1_SCL PB6 -#endif -#ifndef I2C1_SDA -#define I2C1_SDA PB7 -#endif -#define IOCFG_I2C IO_CONFIG(GPIO_Mode_AF_OD, GPIO_Speed_50MHz) - -#endif - #ifndef I2C2_SCL #define I2C2_SCL PB10 #endif - #ifndef I2C2_SDA #define I2C2_SDA PB11 #endif -#ifdef STM32F4 #ifndef I2C3_SCL #define I2C3_SCL PA8 #endif #ifndef I2C3_SDA #define I2C3_SDA PB4 #endif -#endif - -typedef enum { - I2C_STATE_STOPPED = 0, - I2C_STATE_STOPPING, - I2C_STATE_STARTING, - I2C_STATE_STARTING_WAIT, - - I2C_STATE_R_ADDR, - I2C_STATE_R_ADDR_WAIT, - I2C_STATE_R_REGISTER, - I2C_STATE_R_REGISTER_WAIT, - I2C_STATE_R_RESTARTING, - I2C_STATE_R_RESTARTING_WAIT, - I2C_STATE_R_RESTART_ADDR, - I2C_STATE_R_RESTART_ADDR_WAIT, - I2C_STATE_R_TRANSFER_EQ1, - I2C_STATE_R_TRANSFER_EQ2, - I2C_STATE_R_TRANSFER_GE2, - - I2C_STATE_W_ADDR, - I2C_STATE_W_ADDR_WAIT, - I2C_STATE_W_REGISTER, - I2C_STATE_W_TRANSFER_WAIT, - I2C_STATE_W_TRANSFER, - - I2C_STATE_NACK, - I2C_STATE_BUS_ERROR, -} i2cState_t; - -typedef enum { - I2C_TXN_READ, - I2C_TXN_WRITE -} i2cTransferDirection_t; typedef struct i2cBusState_s { - I2CDevice device; bool initialized; - i2cState_t state; - timeUs_t timeout; - - /* Active transfer */ - bool allowRawAccess; - uint8_t addr; // device address - i2cTransferDirection_t rw; // direction - uint8_t reg; // register - uint32_t len; // buffer length - uint8_t *buf; // buffer - bool txnOk; + volatile bool busy; // transfer in progress + volatile bool error; // last transfer failed (NACK, bus error, arbitration lost, overrun or timeout) + uint16_t lastProgress; // byte index and subaddress phase at the previous look, a change means the transfer moves + uint32_t stuckUs; // time looked at without progress, a long gap between looks counts as I2C_STUCK_LOOK_GAP_US + timeUs_t lookUs; // time of the previous look + + // Active transfer + bool reading; + bool rawAccess; // no register address phase + uint8_t addr; // 7-bit address, pre-shifted + uint8_t reg; + int16_t bytes; + uint8_t * readBuf; + const uint8_t * writeBuf; + uint8_t txByte; // storage for the data of a non-blocking single byte write + + // Event handler state + bool subaddressSent; + int16_t index; // next byte index, -1 = register address goes out next } i2cBusState_t; static volatile uint16_t i2cErrorCount = 0; -static i2cDevice_t i2cHardwareMap[] = { - { .dev = I2C1, .scl = IO_TAG(I2C1_SCL), .sda = IO_TAG(I2C1_SDA), .rcc = RCC_APB1(I2C1), .speed = I2C_SPEED_400KHZ }, - { .dev = I2C2, .scl = IO_TAG(I2C2_SCL), .sda = IO_TAG(I2C2_SDA), .rcc = RCC_APB1(I2C2), .speed = I2C_SPEED_400KHZ }, -#ifdef STM32F4 - { .dev = I2C3, .scl = IO_TAG(I2C3_SCL), .sda = IO_TAG(I2C3_SDA), .rcc = RCC_APB1(I2C3), .speed = I2C_SPEED_400KHZ } -#endif -}; - -static i2cBusState_t busState[I2CDEV_COUNT] = { { 0 } }; - -static void i2cResetInterface(i2cBusState_t * i2cBusState) +// Transfer statistics shown with debug_mode = I2C, shared by all buses +typedef struct { + timeUs_t startUs; // when the current transfer was started + uint16_t eventIrqs; // event interrupts during the current / last transfer + uint16_t errorIrqs; // error interrupts since boot + uint16_t lastTransferUs; // start to completion of the last transfer + uint16_t maxIrqUs; // longest single event handler run + uint16_t maxBitWaitUs; // longest wait for a START / STOP bit release + uint16_t startCr2; // interrupt enables found in CR2 when a transfer was started, should be 0 + uint16_t startCallUs; // time spent in the last i2cStartTransfer() call +} i2cDebugStats_t; + +static i2cDebugStats_t i2cStats; + +static void i2cDebugPublish(void) { - const i2cDevice_t * i2c = &(i2cHardwareMap[i2cBusState->device]); - IO_t scl = IOGetByTag(i2c->scl); - IO_t sda = IOGetByTag(i2c->sda); - - i2cErrorCount++; - i2cUnstick(scl, sda); - i2cInit(i2cBusState->device); + DEBUG_SET(DEBUG_I2C, 0, i2cStats.eventIrqs); + DEBUG_SET(DEBUG_I2C, 1, i2cStats.errorIrqs); + DEBUG_SET(DEBUG_I2C, 2, i2cStats.lastTransferUs); + DEBUG_SET(DEBUG_I2C, 3, i2cStats.maxIrqUs); + DEBUG_SET(DEBUG_I2C, 4, i2cStats.maxBitWaitUs); + DEBUG_SET(DEBUG_I2C, 5, i2cErrorCount); + DEBUG_SET(DEBUG_I2C, 6, i2cStats.startCr2); + DEBUG_SET(DEBUG_I2C, 7, i2cStats.startCallUs); } -static void i2cStateMachine(i2cBusState_t * i2cBusState, const timeUs_t currentTicksUs) -{ - I2C_TypeDef * I2Cx = i2cHardwareMap[i2cBusState->device].dev; - - switch (i2cBusState->state) { - case I2C_STATE_BUS_ERROR: - i2cResetInterface(i2cBusState); - i2cBusState->state = I2C_STATE_STOPPED; - break; - - case I2C_STATE_STOPPING: - // Wait for stop bit to clear - // RM0090: When the STOP, START or PEC bit is set, the software must not perform any write access - // to I2C_CR1 before this bit is cleared by hardware. Otherwise there is a risk of setting a second STOP, START or PEC request. - if ((I2Cx->CR1 & I2C_CR1_STOP) == 0) { - i2cBusState->state = I2C_STATE_STOPPED; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; - - case I2C_STATE_STOPPED: - // Stick here - break; - - case I2C_STATE_STARTING: - I2C_NACKPositionConfig(I2Cx, I2C_NACKPosition_Current); - I2C_AcknowledgeConfig(I2Cx, ENABLE); - I2C_GenerateSTART(I2Cx, ENABLE); - i2cBusState->state = I2C_STATE_STARTING_WAIT; - i2cBusState->timeout = currentTicksUs; - FALLTHROUGH; - - case I2C_STATE_STARTING_WAIT: - if (I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT) != ERROR) { - if (i2cBusState->rw == I2C_TXN_READ) { - // Special case - no register address - if (i2cBusState->reg == 0xFF && i2cBusState->allowRawAccess) { - i2cBusState->state = I2C_STATE_R_RESTART_ADDR; - } - else { - i2cBusState->state = I2C_STATE_R_ADDR; - } - } - else { - i2cBusState->state = I2C_STATE_W_ADDR; - } - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; - - case I2C_STATE_R_ADDR: - I2C_Send7bitAddress(I2Cx, i2cBusState->addr, I2C_Direction_Transmitter); - i2cBusState->state = I2C_STATE_R_ADDR_WAIT; - i2cBusState->timeout = currentTicksUs; - FALLTHROUGH; - - case I2C_STATE_R_ADDR_WAIT: - if (I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED) != ERROR) { - i2cBusState->state = I2C_STATE_R_REGISTER; - } - else if (I2C_GetFlagStatus(I2Cx, I2C_FLAG_AF) != RESET) { - i2cBusState->state = I2C_STATE_NACK; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; - - case I2C_STATE_R_REGISTER: /* Send Register address */ - I2C_SendData(I2Cx, i2cBusState->reg); - i2cBusState->state = I2C_STATE_R_REGISTER_WAIT; - i2cBusState->timeout = currentTicksUs; - FALLTHROUGH; - - case I2C_STATE_R_REGISTER_WAIT: - if (I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_BYTE_TRANSMITTED) != ERROR) { - if (i2cBusState->len == 0) { - I2C_GenerateSTOP(I2Cx, ENABLE); - i2cBusState->timeout = currentTicksUs; - i2cBusState->state = I2C_STATE_STOPPING; - } - else { - i2cBusState->state = I2C_STATE_R_RESTARTING; - } - } - else if (I2C_GetFlagStatus(I2Cx, I2C_FLAG_AF) != RESET) { - i2cBusState->state = I2C_STATE_NACK; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; - - case I2C_STATE_R_RESTARTING: - I2C_GenerateSTART(I2Cx, ENABLE); - i2cBusState->state = I2C_STATE_R_RESTARTING_WAIT; - i2cBusState->timeout = currentTicksUs; - FALLTHROUGH; - - case I2C_STATE_R_RESTARTING_WAIT: - if (I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_MODE_SELECT) != ERROR) { - i2cBusState->state = I2C_STATE_R_RESTART_ADDR; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; - - case I2C_STATE_R_RESTART_ADDR: - I2C_Send7bitAddress(I2Cx, i2cBusState->addr, I2C_Direction_Receiver); - i2cBusState->state = I2C_STATE_R_RESTART_ADDR_WAIT; - i2cBusState->timeout = currentTicksUs; - FALLTHROUGH; - - case I2C_STATE_R_RESTART_ADDR_WAIT: - if (I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED) != ERROR) { - if (i2cBusState->len == 1) { - // This TXN is 1-byte, disable ACK and generate stop early - I2C_AcknowledgeConfig(I2Cx, DISABLE); - - ATOMIC_BLOCK(NVIC_PRIO_MAX) { - (void) I2Cx->SR2; - I2C_GenerateSTOP(I2Cx, ENABLE); - } - - i2cBusState->state = I2C_STATE_R_TRANSFER_EQ1; - } - else if (i2cBusState->len == 2) { - // 2-byte transaction, disable ACK - I2C_NACKPositionConfig(I2Cx, I2C_NACKPosition_Next); - ATOMIC_BLOCK(NVIC_PRIO_MAX) { - (void) I2Cx->SR2; - I2C_AcknowledgeConfig(I2Cx, DISABLE); - } - - i2cBusState->state = I2C_STATE_R_TRANSFER_EQ2; - } - else { - (void) I2Cx->SR2; // Clear ADDR flag - i2cBusState->state = I2C_STATE_R_TRANSFER_GE2; - } - - i2cBusState->timeout = currentTicksUs; - } - else if (I2C_GetFlagStatus(I2Cx, I2C_FLAG_AF) != RESET) { - i2cBusState->state = I2C_STATE_NACK; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; +static i2cDevice_t i2cHardwareMap[] = { + { .dev = I2C1, .scl = IO_TAG(I2C1_SCL), .sda = IO_TAG(I2C1_SDA), .rcc = RCC_APB1(I2C1), .speed = I2C_SPEED_400KHZ, .ev_irq = I2C1_EV_IRQn, .er_irq = I2C1_ER_IRQn }, + { .dev = I2C2, .scl = IO_TAG(I2C2_SCL), .sda = IO_TAG(I2C2_SDA), .rcc = RCC_APB1(I2C2), .speed = I2C_SPEED_400KHZ, .ev_irq = I2C2_EV_IRQn, .er_irq = I2C2_ER_IRQn }, + { .dev = I2C3, .scl = IO_TAG(I2C3_SCL), .sda = IO_TAG(I2C3_SDA), .rcc = RCC_APB1(I2C3), .speed = I2C_SPEED_400KHZ, .ev_irq = I2C3_EV_IRQn, .er_irq = I2C3_ER_IRQn }, +}; - case I2C_STATE_R_TRANSFER_EQ1: - if (I2C_GetFlagStatus(I2Cx, I2C_FLAG_RXNE) != RESET) { - *i2cBusState->buf++ = I2C_ReceiveData(I2Cx); - i2cBusState->len--; +static i2cBusState_t busState[ARRAYLEN(i2cHardwareMap)]; - // This was the last successful byte - i2cBusState->txnOk = true; - i2cBusState->timeout = currentTicksUs; - i2cBusState->state = I2C_STATE_STOPPING; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; +// Per address outcome of the last transfer. Kept outside busState so that the reset in i2cInit() does not wipe the +// results of the other devices on the bus +static i2cAddrResults_t busAddrResults[ARRAYLEN(i2cHardwareMap)]; - case I2C_STATE_R_TRANSFER_EQ2: - if (I2C_GetFlagStatus(I2Cx, I2C_FLAG_BTF) != RESET) { - ATOMIC_BLOCK(NVIC_PRIO_MAX) { - I2C_GenerateSTOP(I2Cx,ENABLE); - *i2cBusState->buf++ = I2C_ReceiveData(I2Cx); - } - - *i2cBusState->buf++ = I2C_ReceiveData(I2Cx); - i2cBusState->len =- 2; +static void i2cUnstick(IO_t scl, IO_t sda); +static void i2cEventHandler(I2CDevice device); +static void i2cErrorHandler(I2CDevice device); - // This was the last successful byte - i2cBusState->txnOk = true; - i2cBusState->timeout = currentTicksUs; - i2cBusState->state = I2C_STATE_STOPPING; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; +static bool i2cIsValidDevice(I2CDevice device) +{ + return device != I2CINVALID && (unsigned)device < ARRAYLEN(i2cHardwareMap); +} - case I2C_STATE_R_TRANSFER_GE2: - if (I2C_GetFlagStatus(I2Cx, I2C_FLAG_BTF) != RESET) { - if (i2cBusState->len == 3) { - I2C_AcknowledgeConfig(I2Cx, DISABLE); // clear ack bit +void I2C1_ER_IRQHandler(void) +{ + i2cErrorHandler(I2CDEV_1); +} - ATOMIC_BLOCK(NVIC_PRIO_MAX) { - *i2cBusState->buf++ = I2C_ReceiveData(I2Cx); - I2C_GenerateSTOP(I2Cx,ENABLE); - } +void I2C1_EV_IRQHandler(void) +{ + i2cEventHandler(I2CDEV_1); +} - *i2cBusState->buf++ = I2C_ReceiveData(I2Cx); - i2cBusState->len -= 2; +void I2C2_ER_IRQHandler(void) +{ + i2cErrorHandler(I2CDEV_2); +} - // Last byte remaining - i2cBusState->state = I2C_STATE_R_TRANSFER_EQ1; - i2cBusState->timeout = currentTicksUs; - } - else if (i2cBusState->len < 3) { - // Shouldn't happen - abort - I2C_AcknowledgeConfig(I2Cx, DISABLE); - I2C_GenerateSTOP(I2Cx,ENABLE); - I2C_ReceiveData(I2Cx); - - i2cBusState->txnOk = false; - i2cBusState->timeout = currentTicksUs; - i2cBusState->state = I2C_STATE_STOPPING; - } - else { - // 4 or more extra bytes remaining - *i2cBusState->buf++ = I2C_ReceiveData(I2Cx); - i2cBusState->len--; +void I2C2_EV_IRQHandler(void) +{ + i2cEventHandler(I2CDEV_2); +} - // Restart timeout and stay in this state - i2cBusState->timeout = currentTicksUs; - } - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; +void I2C3_ER_IRQHandler(void) +{ + i2cErrorHandler(I2CDEV_3); +} - case I2C_STATE_W_ADDR: - I2C_AcknowledgeConfig(I2Cx, DISABLE); - I2C_Send7bitAddress(I2Cx, i2cBusState->addr, I2C_Direction_Transmitter); - i2cBusState->state = I2C_STATE_W_ADDR_WAIT; - i2cBusState->timeout = currentTicksUs; - FALLTHROUGH; - - case I2C_STATE_W_ADDR_WAIT: - if (I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED) != ERROR) { - // Special no-address case, skip address byte transmission - if (i2cBusState->reg == 0xFF && i2cBusState->allowRawAccess) { - i2cBusState->state = I2C_STATE_W_TRANSFER; - } - else { - i2cBusState->state = I2C_STATE_W_REGISTER; - } - } - else if (I2C_GetFlagStatus(I2Cx, I2C_FLAG_AF) != RESET) { - i2cBusState->state = I2C_STATE_NACK; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; +void I2C3_EV_IRQHandler(void) +{ + i2cEventHandler(I2CDEV_3); +} - case I2C_STATE_W_REGISTER: /* Send Register address */ - I2C_SendData(I2Cx, i2cBusState->reg); - i2cBusState->state = I2C_STATE_W_TRANSFER_WAIT; - i2cBusState->timeout = currentTicksUs; - FALLTHROUGH; +// Reinitialise the peripheral and clock the bus free. Always returns false so it can be used as the failure result. +static bool i2cHandleHardwareFailure(I2CDevice device) +{ + i2cErrorCount++; + i2cInit(device); + return false; +} - case I2C_STATE_W_TRANSFER_WAIT: - if (I2C_CheckEvent(I2Cx, I2C_EVENT_MASTER_BYTE_TRANSMITTED) != ERROR) { - i2cBusState->state = I2C_STATE_W_TRANSFER; - } - else if (I2C_GetFlagStatus(I2Cx, I2C_FLAG_AF) != RESET) { - i2cBusState->state = I2C_STATE_NACK; - } - else if ((currentTicksUs - i2cBusState->timeout) >= I2C_TIMEOUT) { - i2cBusState->state = I2C_STATE_BUS_ERROR; - } - break; +// Wait for the hardware to release a CR1 control bit (START / STOP). Safe to call from the handlers. +static bool i2cWaitBitRelease(I2C_TypeDef *I2Cx, uint32_t cr1Mask) +{ + const timeUs_t startUs = microsISR(); - case I2C_STATE_W_TRANSFER: - if (i2cBusState->len > 0) { - I2C_SendData(I2Cx, *i2cBusState->buf); - i2cBusState->buf++; - i2cBusState->len--; - i2cBusState->timeout = currentTicksUs; - i2cBusState->state = I2C_STATE_W_TRANSFER_WAIT; - } - else { - I2C_GenerateSTOP(I2Cx, ENABLE); - i2cBusState->timeout = currentTicksUs; - i2cBusState->txnOk = true; - i2cBusState->state = I2C_STATE_STOPPING; - } - break; + while (I2Cx->CR1 & cr1Mask) { + if (cmpTimeUs(microsISR(), startUs) >= I2C_BIT_RELEASE_TIMEOUT_US) { + return false; + } + } - case I2C_STATE_NACK: - I2C_GenerateSTOP(I2Cx, ENABLE); - I2C_ClearFlag(I2Cx, I2C_FLAG_AF); - i2cBusState->timeout = currentTicksUs; - i2cBusState->state = I2C_STATE_STOPPING; - break; + const timeUs_t waitedUs = microsISR() - startUs; + if (waitedUs > i2cStats.maxBitWaitUs) { + i2cStats.maxBitWaitUs = waitedUs; } + + return true; } void i2cSetSpeed(uint8_t speed) @@ -463,34 +215,30 @@ void i2cSetSpeed(uint8_t speed) } } -uint32_t i2cTimeoutUserCallback(void) -{ - i2cErrorCount++; - return false; -} - void i2cInit(I2CDevice device) { - if (device == I2CINVALID) + if (!i2cIsValidDevice(device)) { return; + } i2cDevice_t *i2c = &(i2cHardwareMap[device]); + i2cBusState_t *state = &busState[device]; IO_t scl = IOGetByTag(i2c->scl); IO_t sda = IOGetByTag(i2c->sda); RCC_ClockCmd(i2c->rcc, ENABLE); + I2C_ITConfig(i2c->dev, I2C_IT_EVT | I2C_IT_ERR | I2C_IT_BUF, DISABLE); + IOInit(scl, OWNER_I2C, RESOURCE_I2C_SCL, RESOURCE_INDEX(device)); IOInit(sda, OWNER_I2C, RESOURCE_I2C_SDA, RESOURCE_INDEX(device)); -#ifdef STM32F4 + // Release a slave that may still be driving SDA after a reset in the middle of a transfer + i2cUnstick(scl, sda); + IOConfigGPIOAF(scl, IOCFG_I2C, GPIO_AF_I2C); IOConfigGPIOAF(sda, IOCFG_I2C, GPIO_AF_I2C); -#else - IOConfigGPIO(scl, IOCFG_I2C); - IOConfigGPIO(sda, IOCFG_I2C); -#endif I2C_DeInit(i2c->dev); @@ -526,9 +274,14 @@ void i2cInit(I2CDevice device) I2C_StretchClockCmd(i2c->dev, ENABLE); I2C_Cmd(i2c->dev, ENABLE); - busState[device].device = device; - busState[device].initialized = true; - busState[device].state = I2C_STATE_STOPPED; + // Event and error interrupts are enabled in the peripheral per transfer, the NVIC side stays on + NVIC_SetPriority((IRQn_Type)i2c->er_irq, NVIC_PRIO_I2C_ER); + NVIC_EnableIRQ((IRQn_Type)i2c->er_irq); + NVIC_SetPriority((IRQn_Type)i2c->ev_irq, NVIC_PRIO_I2C_EV); + NVIC_EnableIRQ((IRQn_Type)i2c->ev_irq); + + memset(state, 0, sizeof(*state)); + state->initialized = true; } uint16_t i2cGetErrorCounter(void) @@ -536,60 +289,381 @@ uint16_t i2cGetErrorCounter(void) return i2cErrorCount; } -static void i2cWaitForCompletion(I2CDevice device) +// A transfer is stuck when it made no progress for I2C_TIMEOUT while being looked at. A gap between two looks longer +// than I2C_STUCK_LOOK_GAP_US counts as that much only: a main loop that was busy elsewhere for a while (a settings save) +// does not make the transfer stuck, the interrupts carry it on however seldom somebody looks +#define I2C_STUCK_LOOK_GAP_US 1000 + +static uint16_t i2cTransferProgress(const i2cBusState_t *state) +{ + // The byte index and the subaddress phase are all the handlers move between START and STOP + return (uint16_t)(state->index + 1) | (state->subaddressSent ? 0x8000 : 0); +} + +static bool i2cTransferStuck(i2cBusState_t *state) +{ + const timeUs_t now = micros(); + const uint16_t progress = i2cTransferProgress(state); + + if (progress != state->lastProgress) { + state->lastProgress = progress; + state->stuckUs = 0; + } + else { + state->stuckUs += MIN((uint32_t)cmpTimeUs(now, state->lookUs), (uint32_t)I2C_STUCK_LOOK_GAP_US); + } + state->lookUs = now; + + return state->stuckUs >= I2C_TIMEOUT; +} + +// Set up and start a transfer. Returns false if the bus is busy or the peripheral failed to start. +static bool i2cStartTransfer(I2CDevice device, uint8_t addr, uint8_t reg, bool allowRawAccess, bool reading, uint8_t len, uint8_t *readBuf, const uint8_t *writeBuf) +{ + if (!i2cIsValidDevice(device)) { + return false; + } + + i2cBusState_t *state = &busState[device]; + I2C_TypeDef *I2Cx = i2cHardwareMap[device].dev; + + if (!state->initialized || state->busy) { + return false; + } + + if (reading && len == 0) { + return false; // nothing to receive, the engine would run past the buffer + } + + const timeUs_t callStartUs = micros(); + i2cStats.startCr2 = I2Cx->CR2 & (I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR); + i2cStats.eventIrqs = 0; + i2cStats.startUs = callStartUs; + + state->addr = addr << 1; + state->reg = reg; + state->rawAccess = (reg == 0xFF) && allowRawAccess; + state->reading = reading; + state->bytes = len; + state->readBuf = readBuf; + state->writeBuf = writeBuf; + state->subaddressSent = false; + state->index = 0; + state->lastProgress = i2cTransferProgress(state); + state->stuckUs = 0; + state->lookUs = callStartUs; + state->error = false; + state->busy = true; + + if (!(I2Cx->CR2 & I2C_IT_EVT)) { // interrupts are off between transfers + if (!(I2Cx->CR1 & I2C_CR1_START)) { // ensure sending a start + const timeUs_t startUs = micros(); + while (I2Cx->CR1 & I2C_CR1_STOP) { // wait for any stop to finish sending + if (cmpTimeUs(micros(), startUs) >= I2C_TIMEOUT) { + return i2cHandleHardwareFailure(device); + } + } + I2C_GenerateSTART(I2Cx, ENABLE); // send the start for the new job + } + I2C_ITConfig(I2Cx, I2C_IT_EVT | I2C_IT_ERR, ENABLE); // the handlers take it from here + } + + i2cStats.startCallUs = micros() - callStartUs; + i2cDebugPublish(); + + return true; +} + +// Reset the peripheral after a transfer that did not complete and record the failure for the transfer's owner +static void i2cRecoverStuckTransfer(I2CDevice device) +{ + const uint8_t stuckAddr = busState[device].addr >> 1; // i2cInit() clears the state + + i2cHandleHardwareFailure(device); + busState[device].error = true; + i2cAddrResultSet(&busAddrResults[device], stuckAddr, true); +} + +// Block until the bus is idle. Returns false if the transfer in progress had to be aborted. +static bool i2cWaitForIdle(I2CDevice device) { - do { - i2cStateMachine(&busState[device], micros()); - } while (busState[device].state != I2C_STATE_STOPPED); + i2cBusState_t *state = &busState[device]; + + while (state->busy) { + if (i2cTransferStuck(state)) { + i2cRecoverStuckTransfer(device); + return false; + } + } + + return true; +} + +bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) +{ + if (!i2cIsValidDevice(device)) { + if (error) { + *error = true; + } + return false; + } + + i2cBusState_t *state = &busState[device]; + + if (state->busy && i2cTransferStuck(state)) { + // No progress within the timeout, the transfer is stuck - reset the peripheral + i2cRecoverStuckTransfer(device); + } + + // Only the owner of the transfer on the bus is pending, everybody else gets the outcome of their own last transfer + const bool pending = state->busy && (state->addr >> 1) == addr_; + + if (error) { + *error = !pending && i2cAddrResultFailed(&busAddrResults[device], addr_); + } + + i2cDebugPublish(); + + return pending; +} + +bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t* buf, bool allowRawAccess) +{ + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, true, len, buf, NULL); +} + +bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) +{ + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, len_, NULL, data); +} + +bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t data, bool allowRawAccess) +{ + if (!i2cIsValidDevice(device) || busState[device].busy) { + return false; // don't touch txByte while it may still be going out + } + + busState[device].txByte = data; + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, 1, NULL, &busState[device].txByte); } -bool i2cWriteBuffer(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, const uint8_t * data, bool allowRawAccess) +bool i2cWriteBuffer(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) { - // Don't try to access the non-initialized device - if (!busState[device].initialized) + if (!i2cIsValidDevice(device) || !busState[device].initialized) { return false; + } - // Set up write transaction - busState[device].addr = addr << 1; - busState[device].reg = reg; - busState[device].rw = I2C_TXN_WRITE; - busState[device].len = len; - busState[device].buf = CONST_CAST(uint8_t*, data); - busState[device].txnOk = false; - busState[device].state = I2C_STATE_STARTING; - busState[device].allowRawAccess = allowRawAccess; + // Let a non-blocking transfer of another device finish first + if (!i2cWaitForIdle(device)) { + return false; + } - // Inject I2C_EVENT_START - i2cWaitForCompletion(device); + if (!i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, len_, NULL, data)) { + return false; + } - return busState[device].txnOk; + return i2cWaitForIdle(device) && !busState[device].error; } -bool i2cWrite(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t data, bool allowRawAccess) +bool i2cWrite(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t data, bool allowRawAccess) { - return i2cWriteBuffer(device, addr, reg, 1, &data, allowRawAccess); + return i2cWriteBuffer(device, addr_, reg_, 1, &data, allowRawAccess); } -bool i2cRead(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, uint8_t* buf, bool allowRawAccess) +bool i2cRead(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t* buf, bool allowRawAccess) { - // Don't try to access the non-initialized device - if (!busState[device].initialized) + if (!i2cIsValidDevice(device) || !busState[device].initialized) { + return false; + } + + // Let a non-blocking transfer of another device finish first + if (!i2cWaitForIdle(device)) { return false; + } + + if (!i2cStartTransfer(device, addr_, reg_, allowRawAccess, true, len, buf, NULL)) { + return false; + } + + return i2cWaitForIdle(device) && !busState[device].error; +} + +static void i2cErrorHandler(I2CDevice device) +{ + I2C_TypeDef *I2Cx = i2cHardwareMap[device].dev; + i2cBusState_t *state = &busState[device]; + + const uint32_t SR1Register = I2Cx->SR1; + const uint8_t addr = state->addr >> 1; // the owner, a reset below would clear it + + i2cStats.errorIrqs++; + + if (SR1Register & (I2C_SR1_BERR | I2C_SR1_ARLO | I2C_SR1_AF | I2C_SR1_OVR)) { + state->error = true; + i2cErrorCount++; // keep the "I2C Errors" count of status / MSP meaningful for non-blocking transfers + } + + // If AF, BERR or ARLO, abandon the current job + if (SR1Register & (I2C_SR1_BERR | I2C_SR1_ARLO | I2C_SR1_AF)) { + (void)I2Cx->SR2; // read second status register to clear ADDR if it is set (note that BTF will not be set after a NACK) + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable the RXNE/TXE interrupt - prevent the ISR tailchaining onto the ER (hopefully) + if (!(SR1Register & I2C_SR1_ARLO) && !(I2Cx->CR1 & I2C_CR1_STOP)) { // if we dont have an ARLO error, ensure sending of a stop (after ARLO the hardware has already released the bus) + if (I2Cx->CR1 & I2C_CR1_START) { // We are currently trying to send a start, this is very bad as start, stop will hang the peripheral + i2cWaitBitRelease(I2Cx, I2C_CR1_START); // wait for any start to finish sending + I2C_GenerateSTOP(I2Cx, ENABLE); // send stop to finalise bus transaction + i2cWaitBitRelease(I2Cx, I2C_CR1_STOP); // wait for stop to finish sending + i2cHandleHardwareFailure(device); // reset and configure the hardware + state->error = true; // the reset cleared the state, the transfer still failed + } + else { + I2C_GenerateSTOP(I2Cx, ENABLE); // stop to free up the bus + } + } + } + + // The bus is idle on every path out of here. Leaving EVT enabled would make the next i2cStartTransfer() skip + // generating START and the transfer would only fail through the timeout + I2C_ITConfig(I2Cx, I2C_IT_EVT | I2C_IT_ERR | I2C_IT_BUF, DISABLE); + I2Cx->SR1 &= ~(I2C_SR1_BERR | I2C_SR1_ARLO | I2C_SR1_AF | I2C_SR1_OVR); // reset all the error bits to clear the interrupt + i2cAddrResultSet(&busAddrResults[device], addr, state->error); + state->busy = false; +} + +static void i2cEventHandlerBody(I2CDevice device) +{ + I2C_TypeDef *I2Cx = i2cHardwareMap[device].dev; + i2cBusState_t *state = &busState[device]; + + // Only the low byte carries the event flags, the error flags in the high byte are handled by the error handler + const uint8_t SReg_1 = I2Cx->SR1; + + if (SReg_1 & I2C_SR1_SB) { // we just sent a start - EV5 in ref manual + I2Cx->CR1 &= ~I2C_CR1_POS; // reset the POS bit so ACK/NACK applied to the current byte + I2C_AcknowledgeConfig(I2Cx, ENABLE); // make sure ACK is on + state->index = 0; // reset the index + if (state->reading && (state->subaddressSent || state->rawAccess)) { // we have sent the subaddr + state->subaddressSent = true; // make sure this is set in case of no subaddress, so following code runs correctly + if (state->bytes == 2) { + I2Cx->CR1 |= I2C_CR1_POS; // set the POS bit so NACK applied to the final byte in the two byte read + } + I2C_Send7bitAddress(I2Cx, state->addr, I2C_Direction_Receiver); // send the address and set hardware mode + } + else { // direction is Tx, or we havent sent the sub and rep start + I2C_Send7bitAddress(I2Cx, state->addr, I2C_Direction_Transmitter); // send the address and set hardware mode + if (!state->rawAccess) { + state->index = -1; // send a subaddress + } + } + } + else if (SReg_1 & I2C_SR1_ADDR) { // we just sent the address - EV6 in ref manual + // Read SR1,2 to clear ADDR + __DMB(); // memory fence to control hardware + if (state->bytes == 1 && state->reading && state->subaddressSent) { // we are receiving 1 byte - EV6_3 + I2C_AcknowledgeConfig(I2Cx, DISABLE); // turn off ACK + __DMB(); + (void)I2Cx->SR2; // clear ADDR after ACK is turned off + I2C_GenerateSTOP(I2Cx, ENABLE); // program the stop + I2C_ITConfig(I2Cx, I2C_IT_BUF, ENABLE); // allow us to have an EV7 + } + else { // EV6 and EV6_1 + (void)I2Cx->SR2; // clear the ADDR here + __DMB(); + if (state->bytes == 2 && state->reading && state->subaddressSent) { // rx 2 bytes - EV6_1 + I2C_AcknowledgeConfig(I2Cx, DISABLE); // turn off ACK + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable TXE to allow the buffer to fill + } + else if (state->bytes == 3 && state->reading && state->subaddressSent) { // rx 3 bytes + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // make sure RXNE disabled so we get a BTF in two bytes time + } + else { // receiving greater than three bytes, sending subaddress, or transmitting + I2C_ITConfig(I2Cx, I2C_IT_BUF, ENABLE); + } + } + } + else if (SReg_1 & I2C_SR1_BTF) { // Byte transfer finished - EV7_2, EV7_3 or EV8_2 + if (state->reading && state->subaddressSent) { // EV7_2, EV7_3 + if (state->bytes > 2) { // EV7_2 + I2C_AcknowledgeConfig(I2Cx, DISABLE); // turn off ACK + state->readBuf[state->index++] = (uint8_t)I2Cx->DR; // read data N-2 + I2C_GenerateSTOP(I2Cx, ENABLE); // program the Stop + state->readBuf[state->index++] = (uint8_t)I2Cx->DR; // read data N-1 + I2C_ITConfig(I2Cx, I2C_IT_BUF, ENABLE); // enable TXE to allow the final EV7 + } + else { // EV7_3 + I2C_GenerateSTOP(I2Cx, ENABLE); // program the Stop + state->readBuf[state->index++] = (uint8_t)I2Cx->DR; // read data N-1 + state->readBuf[state->index++] = (uint8_t)I2Cx->DR; // read data N + state->index++; // to show job completed + } + } + else { // EV8_2, which may be due to a subaddress sent or a write completion + if (state->subaddressSent || !state->reading) { + I2C_GenerateSTOP(I2Cx, ENABLE); // program the Stop + state->index++; // to show that the job is complete + } + else { // We need to send a subaddress + I2C_GenerateSTART(I2Cx, ENABLE); // program the repeated Start + state->subaddressSent = true; // this is set back to zero upon completion of the current task + } + } + // we must wait for the start to clear, otherwise we get constant BTF + if (!i2cWaitBitRelease(I2Cx, I2C_CR1_START)) { + i2cRecoverStuckTransfer(device); + return; + } + } + else if (SReg_1 & I2C_SR1_RXNE) { // Byte received - EV7 + state->readBuf[state->index++] = (uint8_t)I2Cx->DR; + if (state->bytes == (state->index + 3)) { + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable TXE to allow the buffer to flush so we can get an EV7_2 + } + if (state->bytes == state->index) { // We have completed a final EV7 + state->index++; // to show job is complete + } + } + else if (SReg_1 & I2C_SR1_TXE) { // Byte transmitted EV8 / EV8_1 + if (state->index != -1) { // we dont have a subaddress to send + if (state->index < state->bytes) { + I2Cx->DR = state->writeBuf[state->index++]; + if (state->bytes == state->index) { // we have sent all the data + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable TXE to allow the buffer to flush + } + } + else { // raw write without data - nothing to send, end the transfer + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); + I2C_GenerateSTOP(I2Cx, ENABLE); + state->index = state->bytes + 1; // to show that the job is complete + } + } + else { + state->index++; + I2Cx->DR = state->reg; // send the subaddress + if (state->reading || !(state->bytes)) { // if receiving or sending 0 bytes, flush now + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable TXE to allow the buffer to flush + } + } + } + + if (state->index == state->bytes + 1) { // we have completed the current job + state->subaddressSent = false; // reset this here + I2C_ITConfig(I2Cx, I2C_IT_EVT | I2C_IT_ERR, DISABLE); // bus is inactive, disable interrupts to prevent BTF + i2cStats.lastTransferUs = microsISR() - i2cStats.startUs; + i2cAddrResultSet(&busAddrResults[device], state->addr >> 1, false); + state->busy = false; + } +} - // Set up read transaction - busState[device].addr = addr << 1; - busState[device].reg = reg; - busState[device].rw = I2C_TXN_READ; - busState[device].len = len; - busState[device].buf = buf; - busState[device].txnOk = false; - busState[device].state = I2C_STATE_STARTING; - busState[device].allowRawAccess = allowRawAccess; +static void i2cEventHandler(I2CDevice device) +{ + const timeUs_t entryUs = microsISR(); - // Inject I2C_EVENT_START - i2cWaitForCompletion(device); + i2cStats.eventIrqs++; + i2cEventHandlerBody(device); - return busState[device].txnOk; + const timeUs_t spentUs = microsISR() - entryUs; + if (spentUs > i2cStats.maxIrqUs) { + i2cStats.maxIrqUs = spentUs; + } } static void i2cUnstick(IO_t scl, IO_t sda) diff --git a/src/main/drivers/compass/compass.h b/src/main/drivers/compass/compass.h index 655021c7709..dd3fe52a13d 100644 --- a/src/main/drivers/compass/compass.h +++ b/src/main/drivers/compass/compass.h @@ -21,10 +21,14 @@ #include "drivers/sensor.h" +// Non-blocking read step, see busReadStepResult_e in drivers/bus.h +typedef busReadStepResult_e (*sensorMagReadStartFuncPtr)(struct magDev_s *mag, bool firstStep); + typedef struct magDev_s { busDevice_t * busDev; sensorMagInitFuncPtr init; // initialize function - sensorMagReadFuncPtr read; // read 3 axis data function + sensorMagReadStartFuncPtr readStart; // optional: start the next non-blocking transfer of a sample, read() then only parses + sensorMagReadFuncPtr read; // read 3 axis data function (blocking when readStart is NULL) struct { bool useExternal; union { diff --git a/src/main/drivers/compass/compass_qmc5883l.c b/src/main/drivers/compass/compass_qmc5883l.c index aca7b1ef995..12d746eb720 100644 --- a/src/main/drivers/compass/compass_qmc5883l.c +++ b/src/main/drivers/compass/compass_qmc5883l.c @@ -76,6 +76,7 @@ #define QMC5883L_REG_DATA_OUTPUT_X 0x00 #define QMC5883L_REG_STATUS 0x06 +#define QMC5883L_STATUS_DRDY 0x01 #define QMC5883L_REG_ID 0x0D #define QMC5883_ID_VAL 0xFF @@ -92,29 +93,52 @@ static bool qmc5883Init(magDev_t * mag) return ack; } -static bool qmc5883Read(magDev_t * mag) +// Targets of the non-blocking reads, filled by the bus driver in the background +static uint8_t qmc5883Status; +static uint8_t qmc5883Data[6]; + +// Two transfers per sample: the status byte first, the data only when DRDY confirms a fresh sample +static busReadStepResult_e qmc5883ReadStart(magDev_t * mag, bool firstStep) { - uint8_t status; - uint8_t buf[6]; + static bool statusStarted = false; - // set magData to zero for case of failed read - mag->magADCRaw[X] = 0; - mag->magADCRaw[Y] = 0; - mag->magADCRaw[Z] = 0; + if (firstStep) { + statusStarted = false; + qmc5883Status = 0; + } - bool ack = busRead(mag->busDev, QMC5883L_REG_STATUS, &status); - if (!ack || (status & 0x01) == 0) { - return false; + if (!statusStarted) { + if (!busReadBufStart(mag->busDev, QMC5883L_REG_STATUS, &qmc5883Status, 1)) { + return BUS_READ_STEP_BUSY; + } + statusStarted = true; + return BUS_READ_STEP_NEXT; + } + + if ((qmc5883Status & QMC5883L_STATUS_DRDY) == 0) { + return BUS_READ_STEP_LAST; // nothing new to fetch, qmc5883Read() reports the miss } - ack = busReadBuf(mag->busDev, QMC5883L_REG_DATA_OUTPUT_X, buf, 6); - if (!ack) { + if (!busReadBufStart(mag->busDev, QMC5883L_REG_DATA_OUTPUT_X, qmc5883Data, sizeof(qmc5883Data))) { + return BUS_READ_STEP_BUSY; + } + + return BUS_READ_STEP_LAST; +} + +static bool qmc5883Read(magDev_t * mag) +{ + if ((qmc5883Status & QMC5883L_STATUS_DRDY) == 0) { + // set magData to zero for case of failed read + mag->magADCRaw[X] = 0; + mag->magADCRaw[Y] = 0; + mag->magADCRaw[Z] = 0; return false; } - mag->magADCRaw[X] = (int16_t)(buf[1] << 8 | buf[0]); - mag->magADCRaw[Y] = (int16_t)(buf[3] << 8 | buf[2]); - mag->magADCRaw[Z] = (int16_t)(buf[5] << 8 | buf[4]); + mag->magADCRaw[X] = (int16_t)(qmc5883Data[1] << 8 | qmc5883Data[0]); + mag->magADCRaw[Y] = (int16_t)(qmc5883Data[3] << 8 | qmc5883Data[2]); + mag->magADCRaw[Z] = (int16_t)(qmc5883Data[5] << 8 | qmc5883Data[4]); return true; } @@ -157,6 +181,7 @@ bool qmc5883Detect(magDev_t * mag) } mag->init = qmc5883Init; + mag->readStart = qmc5883ReadStart; mag->read = qmc5883Read; return true; diff --git a/src/main/drivers/compass/compass_qmc5883p.c b/src/main/drivers/compass/compass_qmc5883p.c index e5c21afb74a..e4a93d4b7e7 100644 --- a/src/main/drivers/compass/compass_qmc5883p.c +++ b/src/main/drivers/compass/compass_qmc5883p.c @@ -123,23 +123,48 @@ static bool qmc5883pInit(magDev_t * mag) return ack; } -static bool qmc5883pRead(magDev_t * mag) +// Targets of the non-blocking reads, filled by the bus driver in the background +static uint8_t qmc5883pStatus; +static uint8_t qmc5883pData[QMC5883P_DATA_BYTES]; + +// Two transfers per sample: the status byte first, the data only when DRDY confirms a fresh sample +static busReadStepResult_e qmc5883pReadStart(magDev_t * mag, bool firstStep) { - uint8_t status; - uint8_t buf[QMC5883P_DATA_BYTES]; + static bool statusStarted = false; - // set magData to zero for case of failed read - mag->magADCRaw[X] = 0; - mag->magADCRaw[Y] = 0; - mag->magADCRaw[Z] = 0; + if (firstStep) { + statusStarted = false; + qmc5883pStatus = 0; + } - bool ack = busRead(mag->busDev, QMC5883P_REG_STATUS, &status); - if (!ack || (status & QMC5883P_STATUS_DRDY_MASK) == 0) { - return false; + if (!statusStarted) { + if (!busReadBufStart(mag->busDev, QMC5883P_REG_STATUS, &qmc5883pStatus, 1)) { + return BUS_READ_STEP_BUSY; + } + statusStarted = true; + return BUS_READ_STEP_NEXT; + } + + if ((qmc5883pStatus & QMC5883P_STATUS_DRDY_MASK) == 0) { + return BUS_READ_STEP_LAST; // nothing new to fetch, qmc5883pRead() reports the miss } - ack = busReadBuf(mag->busDev, QMC5883P_REG_DATA_OUTPUT_X, buf, QMC5883P_DATA_BYTES); - if (!ack) { + if (!busReadBufStart(mag->busDev, QMC5883P_REG_DATA_OUTPUT_X, qmc5883pData, sizeof(qmc5883pData))) { + return BUS_READ_STEP_BUSY; + } + + return BUS_READ_STEP_LAST; +} + +static bool qmc5883pRead(magDev_t * mag) +{ + const uint8_t *buf = qmc5883pData; + + if ((qmc5883pStatus & QMC5883P_STATUS_DRDY_MASK) == 0) { + // set magData to zero for case of failed read + mag->magADCRaw[X] = 0; + mag->magADCRaw[Y] = 0; + mag->magADCRaw[Z] = 0; return false; } @@ -196,6 +221,7 @@ bool qmc5883pDetect(magDev_t * mag) } mag->init = qmc5883pInit; + mag->readStart = qmc5883pReadStart; mag->read = qmc5883pRead; return true; diff --git a/src/main/drivers/sdcard/sdcard_spi.c b/src/main/drivers/sdcard/sdcard_spi.c index 6446ec09164..58c6040c4b2 100644 --- a/src/main/drivers/sdcard/sdcard_spi.c +++ b/src/main/drivers/sdcard/sdcard_spi.c @@ -63,7 +63,7 @@ static void sdcardSpi_deselect(void) //spiTransferByte(SDCARD_SPI_INSTANCE, 0xFF); int timeout = 100000; - while (busIsBusy(sdcard.dev)) { + while (busIsBusy(sdcard.dev, NULL)) { if (timeout-- == 0) { sdcard.failureCount++; if (sdcard.failureCount >= SDCARD_MAX_CONSECUTIVE_FAILURES) { @@ -872,7 +872,7 @@ void sdcardSpi_init(void) // Wait for that transmission to finish before we enable the SDCard, so it receives the required number of cycles: int time = 100000; - while (busIsBusy(sdcard.dev)) { + while (busIsBusy(sdcard.dev, NULL)) { if (time-- == 0) { busSetSpeed(sdcard.dev, BUS_SPEED_STANDARD); busDeviceDeInit(sdcard.dev); diff --git a/src/main/fc/cli.c b/src/main/fc/cli.c index 15339c4f39e..54fea0fc076 100644 --- a/src/main/fc/cli.c +++ b/src/main/fc/cli.c @@ -238,7 +238,8 @@ static const char *debugModeNames[DEBUG_COUNT] = { "TERRAIN_NAV", "ESC", "FW_TURN", - "MAG" + "MAG", + "I2C" }; /* Sensor names (used in lookup tables for *_hardware settings and in status diff --git a/src/main/fc/fc_tasks.c b/src/main/fc/fc_tasks.c index 31143e92706..b8716b076ee 100755 --- a/src/main/fc/fc_tasks.c +++ b/src/main/fc/fc_tasks.c @@ -188,7 +188,11 @@ void taskProcessGPS(timeUs_t currentTimeUs) void taskUpdateCompass(timeUs_t currentTimeUs) { if (sensors(SENSOR_MAG)) { - compassUpdate(currentTimeUs); + // A non-blocking read asks to be revisited shortly, otherwise the regular period is restored + const uint32_t newDeadline = compassUpdate(currentTimeUs); + if (newDeadline != 0) { + rescheduleTask(TASK_SELF, newDeadline); + } } } #endif @@ -200,12 +204,16 @@ void taskUpdateBaro(timeUs_t currentTimeUs) return; } - const uint32_t newDeadline = baroUpdate(); + bool newSampleReady = false; + const uint32_t newDeadline = baroUpdate(&newSampleReady); if (newDeadline != 0) { rescheduleTask(TASK_SELF, newDeadline); } - updatePositionEstimator_BaroTopic(currentTimeUs); + // The estimator derives the climb rate from consecutive samples, feed it only when there is a new one + if (newSampleReady) { + updatePositionEstimator_BaroTopic(currentTimeUs); + } } #endif @@ -595,7 +603,7 @@ cfTask_t cfTasks[TASK_COUNT] = { [TASK_COMPASS] = { .taskName = "COMPASS", .taskFunc = taskUpdateCompass, - .desiredPeriod = TASK_PERIOD_HZ(10), // Compass is updated at 10 Hz + .desiredPeriod = TASK_PERIOD_HZ(COMPASS_UPDATE_RATE_HZ), .staticPriority = TASK_PRIORITY_MEDIUM, }, #endif diff --git a/src/main/fc/settings.yaml b/src/main/fc/settings.yaml index 142f5f06c9b..e0c92770042 100644 --- a/src/main/fc/settings.yaml +++ b/src/main/fc/settings.yaml @@ -93,7 +93,7 @@ tables: "AUTOTRIM", "AUTOTUNE", "RATE_DYNAMICS", "LANDING", "POS_EST", "ADAPTIVE_FILTER", "HEADTRACKER", "GPS", "LULU", "SBUS2", "OSD_REFRESH", "MAG_CALIB", "VTOL_TRANSITION", "VTOL_MC_PROTECT", "TERRAIN_NAV", "ESC", - "FW_TURN", "MAG"] + "FW_TURN", "MAG", "I2C"] - name: vtol_mc_protection_mode values: ["OFF", "NAV", "NAV_AND_STABILIZED"] - name: aux_operator diff --git a/src/main/sensors/barometer.c b/src/main/sensors/barometer.c index aaea9dda501..fb9f9737110 100644 --- a/src/main/sensors/barometer.c +++ b/src/main/sensors/barometer.c @@ -262,45 +262,114 @@ bool baroInit(void) } typedef enum { - BAROMETER_NEEDS_SAMPLES = 0, - BAROMETER_NEEDS_CALCULATION + BARO_STATE_TEMPERATURE_START = 0, + BARO_STATE_TEMPERATURE_READ, + BARO_STATE_TEMPERATURE_SAMPLE, + BARO_STATE_PRESSURE_START, + BARO_STATE_PRESSURE_READ, + BARO_STATE_PRESSURE_SAMPLE, } barometerState_e; -uint32_t baroUpdate(void) +// Delay before looking at a non-blocking bus transfer again +#define BARO_STATE_STEP_DELAY_US 1000 + +/* + * Runs the measurement cycle described in drivers/barometer/barometer.h. + * Returns the delay until the next call (0 keeps the current task period). *newSampleReady is set when + * baro.baroPressure / baro.baroTemperature were updated in this call. + */ +uint32_t baroUpdate(bool *newSampleReady) { - static barometerState_e state = BAROMETER_NEEDS_SAMPLES; + static barometerState_e state = BARO_STATE_TEMPERATURE_START; + baroDev_t *dev = &baro.dev; + bool busError = false; + + *newSampleReady = false; #ifdef USE_SIMULATOR if (ARMING_FLAG(SIMULATOR_MODE_HITL)) { - return 0; + // Pressure and temperature are injected over MSP, keep publishing them at the sensor's pace + *newSampleReady = true; + return dev->up_delay; } #endif - switch (state) { - default: - case BAROMETER_NEEDS_SAMPLES: - if (baro.dev.get_ut) { - baro.dev.get_ut(&baro.dev); - } - if (baro.dev.start_up) { - baro.dev.start_up(&baro.dev); - } - state = BAROMETER_NEEDS_CALCULATION; - return baro.dev.up_delay; - break; - - case BAROMETER_NEEDS_CALCULATION: - if (baro.dev.get_up) { - baro.dev.get_up(&baro.dev); - } - if (baro.dev.start_ut) { - baro.dev.start_ut(&baro.dev); - } - //output: baro.baroPressure, baro.baroTemperature - baro.dev.calculate(&baro.dev, &baro.baroPressure, &baro.baroTemperature); - state = BAROMETER_NEEDS_SAMPLES; - return baro.dev.ut_delay; - break; + // States that need no wait on the bus run back to back within one call + for (;;) { + switch (state) { + default: + case BARO_STATE_TEMPERATURE_START: + if (dev->start_ut && !dev->start_ut(dev) && dev->read_ut) { + return BARO_STATE_STEP_DELAY_US; // non-blocking start refused, bus is busy + } + state = BARO_STATE_TEMPERATURE_READ; + return dev->ut_delay; + + case BARO_STATE_TEMPERATURE_READ: + if (dev->read_ut) { + if (!dev->read_ut(dev)) { + return BARO_STATE_STEP_DELAY_US; // bus is busy, try again shortly + } + state = BARO_STATE_TEMPERATURE_SAMPLE; + return BARO_STATE_STEP_DELAY_US; + } + state = BARO_STATE_TEMPERATURE_SAMPLE; // blocking driver, sample right away + break; + + case BARO_STATE_TEMPERATURE_SAMPLE: + if (dev->read_ut) { + if (dev->busDev && busIsBusy(dev->busDev, &busError) && !busError) { + return BARO_STATE_STEP_DELAY_US; // transfer still in progress + } + if (busError || (dev->get_ut && !dev->get_ut(dev))) { + state = BARO_STATE_TEMPERATURE_START; // transfer failed or sample unusable, redo the phase + break; + } + } + else if (dev->get_ut) { + dev->get_ut(dev); + } + state = BARO_STATE_PRESSURE_START; + break; + + case BARO_STATE_PRESSURE_START: + if (dev->start_up && !dev->start_up(dev) && dev->read_up) { + return BARO_STATE_STEP_DELAY_US; // non-blocking start refused, bus is busy + } + state = BARO_STATE_PRESSURE_READ; + return dev->up_delay; + + case BARO_STATE_PRESSURE_READ: + if (dev->read_up) { + if (!dev->read_up(dev)) { + return BARO_STATE_STEP_DELAY_US; // bus is busy, try again shortly + } + state = BARO_STATE_PRESSURE_SAMPLE; + return BARO_STATE_STEP_DELAY_US; + } + state = BARO_STATE_PRESSURE_SAMPLE; // blocking driver, sample right away + break; + + case BARO_STATE_PRESSURE_SAMPLE: + if (dev->read_up) { + if (dev->busDev && busIsBusy(dev->busDev, &busError) && !busError) { + return BARO_STATE_STEP_DELAY_US; // transfer still in progress + } + if (busError || (dev->get_up && !dev->get_up(dev))) { + state = BARO_STATE_PRESSURE_START; // transfer failed or sample unusable, redo the phase + break; + } + } + else if (dev->get_up) { + dev->get_up(dev); + } + + //output: baro.baroPressure, baro.baroTemperature + dev->calculate(dev, &baro.baroPressure, &baro.baroTemperature); + *newSampleReady = true; + state = dev->combined_read ? BARO_STATE_PRESSURE_START : BARO_STATE_TEMPERATURE_START; + break; + } } } diff --git a/src/main/sensors/barometer.h b/src/main/sensors/barometer.h index 091b3f26a4f..3d20e7151fb 100644 --- a/src/main/sensors/barometer.h +++ b/src/main/sensors/barometer.h @@ -61,7 +61,7 @@ PG_DECLARE(barometerConfig_t, barometerConfig); bool baroInit(void); bool baroIsCalibrationComplete(void); void baroStartCalibration(void); -uint32_t baroUpdate(void); +uint32_t baroUpdate(bool *newSampleReady); int32_t baroCalculateAltitude(void); int32_t baroGetLatestAltitude(void); int16_t baroGetTemperature(void); diff --git a/src/main/sensors/compass.c b/src/main/sensors/compass.c index 79bcf167bbc..540cbc12bf6 100644 --- a/src/main/sensors/compass.c +++ b/src/main/sensors/compass.c @@ -430,13 +430,20 @@ static void compassApplyDetectedOrientation(int16_t rollDD, int16_t pitchDD, int compassRefreshAlignment(); } -void compassUpdate(timeUs_t currentTimeUs) +// Delay before looking at a non-blocking bus transfer again +#define COMPASS_READ_RETRY_US 1000 + +/* + * Reads the magnetometer and processes the sample. Returns the delay until the next call: the regular period once + * a sample was handled, a short retry while a non-blocking read is in progress. + */ +uint32_t compassUpdate(timeUs_t currentTimeUs) { #ifdef USE_SIMULATOR - if (ARMING_FLAG(SIMULATOR_MODE_HITL)) { - magUpdatedAtLeastOnce = true; - return; - } + if (ARMING_FLAG(SIMULATOR_MODE_HITL)) { + magUpdatedAtLeastOnce = true; + return COMPASS_UPDATE_PERIOD_US; + } #endif static sensorCalibrationState_t calState; static int16_t magPrev[XYZ_AXIS_COUNT]; @@ -458,11 +465,45 @@ void compassUpdate(timeUs_t currentTimeUs) } #endif + // Non-blocking drivers deliver a sample over one or more bus transfers spread across calls + static bool transferPending = false; // a transfer started by readStart() is on the bus + static bool lastTransferStarted = false; // the transfer in flight is the last one of the sample + + if (mag.dev.readStart) { + bool busError = false; + + if (transferPending && mag.dev.busDev && busIsBusy(mag.dev.busDev, &busError) && !busError) { + return COMPASS_READ_RETRY_US; // still on the bus + } + + if (busError) { + transferPending = false; + lastTransferStarted = false; + mag.magADC[X] = 0; + mag.magADC[Y] = 0; + mag.magADC[Z] = 0; + return COMPASS_UPDATE_PERIOD_US; + } + + if (!lastTransferStarted) { + const busReadStepResult_e result = mag.dev.readStart(&mag.dev, !transferPending); + if (result != BUS_READ_STEP_BUSY) { + transferPending = true; + lastTransferStarted = (result == BUS_READ_STEP_LAST); + } + return COMPASS_READ_RETRY_US; // wait for the transfer, or for the bus to free up + } + + // The last transfer of the sample is complete, read() only parses it + transferPending = false; + lastTransferStarted = false; + } + if (!mag.dev.read(&mag.dev)) { mag.magADC[X] = 0; mag.magADC[Y] = 0; mag.magADC[Z] = 0; - return; + return COMPASS_UPDATE_PERIOD_US; } for (int axis = 0; axis < XYZ_AXIS_COUNT; axis++) { @@ -590,6 +631,8 @@ void compassUpdate(timeUs_t currentTimeUs) } magUpdatedAtLeastOnce = true; + + return COMPASS_UPDATE_PERIOD_US; } #endif diff --git a/src/main/sensors/compass.h b/src/main/sensors/compass.h index b277f6b919a..0ac33964048 100644 --- a/src/main/sensors/compass.h +++ b/src/main/sensors/compass.h @@ -77,9 +77,13 @@ typedef struct compassConfig_s { PG_DECLARE(compassConfig_t, compassConfig); +// Regular sample rate of the compass task +#define COMPASS_UPDATE_RATE_HZ 10 +#define COMPASS_UPDATE_PERIOD_US (1000000 / COMPASS_UPDATE_RATE_HZ) + bool compassDetect(magDev_t *dev, magSensor_e magHardwareToUse); bool compassInit(void); -void compassUpdate(timeUs_t currentTimeUs); +uint32_t compassUpdate(timeUs_t currentTimeUs); bool compassIsReady(void); bool compassIsHealthy(void); bool compassIsCalibrationComplete(void); From a4eaeec4e56c50b2b46944a83d317462e76155d8 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 8 Oct 2026 19:17:26 +0200 Subject: [PATCH 02/14] I2C CORE - fix for F4 and AT32 --- docs/development/non-blocking-i2c.md | 27 ++++++++++++--- src/main/drivers/bus_i2c_at32f43x.c | 50 ++++++++++++++++++++++++++-- src/main/drivers/bus_i2c_hal.c | 30 ++++++++++++++++- src/main/drivers/bus_i2c_stm32f40x.c | 46 +++++++++++++++++++++---- 4 files changed, 139 insertions(+), 14 deletions(-) diff --git a/docs/development/non-blocking-i2c.md b/docs/development/non-blocking-i2c.md index 3bc10d95bdf..2968c93ed3f 100644 --- a/docs/development/non-blocking-i2c.md +++ b/docs/development/non-blocking-i2c.md @@ -33,7 +33,7 @@ Every platform implements the same `drivers/bus_i2c.h` API: |---|---| | STM32F4 | Own interrupt-driven engine in `bus_i2c_stm32f40x.c`, ported from the Betaflight `bus_i2c_stm32f4xx.c` driver. Blocking calls use the same engine and wait for it. | | STM32F7/H7 | `HAL_I2C_Mem_Read_IT()` and friends, completion through the `HAL_I2C_*CpltCallback()` / `HAL_I2C_ErrorCallback()` hooks. | -| AT32F43x | `i2c_memory_read_int()` and friends from `i2c_application`. The library sends the slave and register address synchronously (tens of µs, bounded by the library timeout), only the data phase runs in the interrupt. | +| AT32F43x | `i2c_memory_read_int()` and friends from `i2c_application`. The library sends the slave and register address synchronously (tens of µs, bounded by the library timeout), only the data phase runs in the interrupt. A NACK in that address phase is reported like any other failed transfer: the start call returns `true` and `i2cBusy()` reports the error at once. | | RP2350, software I2C, SITL | Synchronous: the start call completes the transfer, `i2cBusy()` is always `false`. | `i2cWriteStart()` copies the data byte into driver-owned storage, the caller @@ -75,9 +75,28 @@ phase on the F4), not the time since the start: A NACK or a bus error ends a non-blocking transfer at once: the error is recorded for its owner and the counter shown by `status` goes up. The -peripheral is not reinitialised for that, it is fine after a NACK. The F4 -driver never did that for blocking calls either; the HAL and AT32 blocking -calls keep reinitialising on failure, as before. +peripheral is not reinitialised for that, it is fine after a NACK. This +includes the AT32 address phase, which runs inside the start call: the call +returns `true` and `i2cBusy()` reports the failure, so an unplugged sensor +costs one short failed start per attempt and nothing more. The F4 driver +never reinitialised on a NACK for blocking calls either; the HAL and AT32 +blocking calls keep reinitialising on failure, as before. + +The F4 handlers never reinitialise the peripheral themselves. The I2C +interrupts sit above the motor timers and an unstick clocks the bus for up +to a few ms, so a transfer the handler has to give up on (a bus error with a +START still pending, a repeated START that does not go out within 1 ms) only +flags the bus: the next `i2cBusy()` or start call on that bus finishes the +cycle with a STOP and reinitialises the peripheral from task context. + +A bus that refuses every start as busy with no transfer of ours in flight +(`HAL_BUSY` on F7/H7, `BUSYF` on the AT32) is a fault the stuck detection +cannot see, since nothing is in progress. The drivers count the refused +starts the same way as the stuck looks and reinitialise the peripheral after +`I2C_TIMEOUT` of them; the error counter goes up and the failure is recorded +for the address that asked, so the owner sees it on its next `busIsBusy()`. +The F4 engine does not check the busy flag before a start, a held bus shows +up there as a stuck transfer. A blocking call issued while a non-blocking transfer is on the bus waits for it with the same stuck detection, then runs as before. diff --git a/src/main/drivers/bus_i2c_at32f43x.c b/src/main/drivers/bus_i2c_at32f43x.c index 74e8f8e42b7..6db48cf3667 100644 --- a/src/main/drivers/bus_i2c_at32f43x.c +++ b/src/main/drivers/bus_i2c_at32f43x.c @@ -100,6 +100,8 @@ typedef struct { uint16_t lastPcount; // bytes left at the previous look, a change means the transfer moves uint32_t stuckUs; // time looked at without progress, a long gap between looks counts as I2C_STUCK_LOOK_GAP_US timeUs_t lookUs; // time of the previous look + uint32_t heldUs; // time starts were refused with the bus busy and nothing of ours in flight + timeUs_t heldLookUs; // time of the previous refused start uint8_t txByte; // data of a non-blocking single byte write, must outlive the call i2cAddrResults_t addrResults; // outcome per slave address, survives i2cInit() } i2cState_t; @@ -204,6 +206,24 @@ static bool i2cTransferStuck(i2cState_t * state) return state->stuckUs >= I2C_TIMEOUT; } +// The bus is held when starts keep being refused as busy for I2C_TIMEOUT with no transfer of ours in flight: a slave +// holding a line, or a BUSYF flag that stayed set. Measured like a stuck transfer, a long gap between two refused starts +// counts as I2C_STUCK_LOOK_GAP_US only +static bool i2cBusHeld(i2cState_t * state) +{ + const timeUs_t now = micros(); + + state->heldUs += MIN((uint32_t)cmpTimeUs(now, state->heldLookUs), (uint32_t)I2C_STUCK_LOOK_GAP_US); + state->heldLookUs = now; + + if (state->heldUs < I2C_TIMEOUT) { + return false; + } + + state->heldUs = 0; + return true; +} + // Pick up the outcome of a pending interrupt driven transfer and reset a stuck one static void i2cPollPending(I2CDevice device) { @@ -242,7 +262,8 @@ static void i2cWaitForIdle(I2CDevice device) /* * Start an interrupt driven transfer. The i2c_application layer sends the slave and register address synchronously * (a few tens of microseconds), the data phase runs from the interrupt handlers. - * Returns false if the bus is busy or the transfer could not be started. + * Returns false if the bus is busy or the transfer could not be started. A NACK during the address phase is a finished, + * failed transfer: true is returned and i2cBusy() reports the failure, like for a NACK in the data phase. */ static bool i2cStartTransfer(I2CDevice device, uint8_t addr_, uint8_t reg_, bool allowRawAccess, bool reading, uint8_t len, uint8_t *buf) { @@ -292,16 +313,38 @@ static bool i2cStartTransfer(I2CDevice device, uint8_t addr_, uint8_t reg_, bool } if (status == I2C_ERR_STEP_1) { - return false; // bus still busy, try again later + // Bus busy with nothing of ours in flight: the previous STOP may still be going out. A bus that stays busy is + // held by a slave or a confused peripheral and only a reset clears it, the stuck check never sees it + if (i2cBusHeld(state)) { + i2cHandleHardwareFailure(device); + i2cAddrResultSet(&state->addrResults, addr_, true); + } + return false; // try again later } if (status != I2C_OK) { - /* wait for the stop flag to be set and clear it */ + /* the hardware has sent a STOP, wait for the stop flag and clear it */ i2c_wait_flag(&state->handle, I2C_STOPF_FLAG, I2C_EVENT_CHECK_NONE, I2C_DEFAULT_TIMEOUT); i2c_flag_clear(state->handle.i2cx, I2C_STOPF_FLAG); + + if (state->handle.error_code == I2C_ERR_ACKFAIL) { + // The slave did not answer its address or the register byte. The peripheral is fine after a NACK, so no + // reset: record the failure for the owner and let it find out from i2cBusy(). An unplugged sensor would + // otherwise cost a reinit and an unstick on every retry + i2c_reset_ctrl2_register(&state->handle); + i2cErrorCount++; + i2cStats.lastTransferUs = micros() - callStartUs; + i2cAddrResultSet(&state->addrResults, addr_, true); + state->heldUs = 0; + state->heldLookUs = callStartUs; + return true; + } + return i2cHandleHardwareFailure(device); } + state->heldUs = 0; + state->heldLookUs = callStartUs; state->addr = addr_; state->startUs = callStartUs; state->lastPcount = state->handle.pcount; @@ -649,6 +692,7 @@ void i2cInit(I2CDevice device) i2c_enable(pHandle->i2cx, TRUE); state->pending = false; + state->heldUs = 0; state->initialised = true; } diff --git a/src/main/drivers/bus_i2c_hal.c b/src/main/drivers/bus_i2c_hal.c index cfedbc211f0..0f737967286 100644 --- a/src/main/drivers/bus_i2c_hal.c +++ b/src/main/drivers/bus_i2c_hal.c @@ -115,6 +115,8 @@ typedef struct { uint16_t lastXferCount; // bytes left at the previous look, a change means the transfer moves uint32_t stuckUs; // time looked at without progress, a long gap between looks counts as I2C_STUCK_LOOK_GAP_US timeUs_t lookUs; // time of the previous look + uint32_t heldUs; // time starts were refused with the bus busy and nothing of ours in flight + timeUs_t heldLookUs; // time of the previous refused start uint8_t txByte; // data of a non-blocking single byte write, must outlive the call i2cAddrResults_t addrResults; // outcome per slave address, survives i2cInit() } i2cState_t; @@ -298,6 +300,24 @@ static bool i2cTransferStuck(i2cState_t * state) return state->stuckUs >= I2C_TIMEOUT; } +// The bus is held when starts keep being refused as busy for I2C_TIMEOUT with no transfer of ours in flight: a slave +// holding a line, or a BUSY flag that stayed set. Measured like a stuck transfer, a long gap between two refused starts +// counts as I2C_STUCK_LOOK_GAP_US only +static bool i2cBusHeld(i2cState_t * state) +{ + const timeUs_t now = micros(); + + state->heldUs += MIN((uint32_t)cmpTimeUs(now, state->heldLookUs), (uint32_t)I2C_STUCK_LOOK_GAP_US); + state->heldLookUs = now; + + if (state->heldUs < I2C_TIMEOUT) { + return false; + } + + state->heldUs = 0; + return true; +} + // Block until no interrupt driven transfer is in progress. Returns false if a stuck transfer had to be aborted. static bool i2cWaitForIdle(I2CDevice device) { @@ -366,11 +386,19 @@ static bool i2cStartTransfer(I2CDevice device, uint8_t addr_, uint8_t reg_, bool if (status != HAL_OK) { state->busy = false; if (status == HAL_BUSY) { - return false; // HAL is still finishing the previous transfer (STOP in progress), try again later + // The HAL is still finishing the previous transfer (STOP in progress), or the bus is held: a BUSY flag that + // stays set with nothing of ours in flight is cleared by a reset only, the stuck check never sees it + if (i2cBusHeld(state)) { + i2cHandleHardwareFailure(device); + i2cAddrResultSet(&state->addrResults, addr_, true); + } + return false; // try again later } return i2cHandleHardwareFailure(device); } + state->heldUs = 0; + state->heldLookUs = callStartUs; state->lastXferCount = state->handle.XferCount; state->stuckUs = 0; state->lookUs = callStartUs; diff --git a/src/main/drivers/bus_i2c_stm32f40x.c b/src/main/drivers/bus_i2c_stm32f40x.c index 434a14fb34a..c982029e774 100644 --- a/src/main/drivers/bus_i2c_stm32f40x.c +++ b/src/main/drivers/bus_i2c_stm32f40x.c @@ -22,6 +22,11 @@ * i2cReadStart()/i2cWriteStart() return immediately and the caller polls * i2cBusy(). A blocking call issued while a non-blocking transfer is in * progress waits for it to finish first, so the two can share a bus. + * + * The handlers never reinitialise the peripheral: an unstick clocks the bus + * for up to a few ms and the I2C interrupts sit above the motor timers. A + * transfer the handlers have to give up on flags the bus for a reset that + * the next i2cBusy() or start call performs from task context. */ #include @@ -83,6 +88,7 @@ typedef struct i2cBusState_s { bool initialized; volatile bool busy; // transfer in progress volatile bool error; // last transfer failed (NACK, bus error, arbitration lost, overrun or timeout) + volatile bool needsReset; // a handler gave up on a transfer, i2cServiceReset() has to reinitialise the peripheral uint16_t lastProgress; // byte index and subaddress phase at the previous look, a change means the transfer moves uint32_t stuckUs; // time looked at without progress, a long gap between looks counts as I2C_STUCK_LOOK_GAP_US timeUs_t lookUs; // time of the previous look @@ -208,6 +214,27 @@ static bool i2cWaitBitRelease(I2C_TypeDef *I2Cx, uint32_t cr1Mask) return true; } +// Reinitialise the peripheral after a handler gave up on a transfer. Runs from task context before the bus is looked +// at or used again, so the waits and the unstick never hold off the higher priority interrupts +static void i2cServiceReset(I2CDevice device) +{ + i2cBusState_t *state = &busState[device]; + + if (!state->needsReset) { + return; + } + + I2C_TypeDef *I2Cx = i2cHardwareMap[device].dev; + + // Finish the bus cycle the handler left behind: a pending START must go out before a STOP is requested, both set at + // once hang the peripheral. On a held bus the waits time out and the reset below sorts the peripheral out anyway + i2cWaitBitRelease(I2Cx, I2C_CR1_START); + I2C_GenerateSTOP(I2Cx, ENABLE); + i2cWaitBitRelease(I2Cx, I2C_CR1_STOP); + + i2cHandleHardwareFailure(device); // i2cInit() clears needsReset with the rest of the state +} + void i2cSetSpeed(uint8_t speed) { for (unsigned int i = 0; i < ARRAYLEN(i2cHardwareMap); i++) { @@ -327,6 +354,8 @@ static bool i2cStartTransfer(I2CDevice device, uint8_t addr, uint8_t reg, bool a i2cBusState_t *state = &busState[device]; I2C_TypeDef *I2Cx = i2cHardwareMap[device].dev; + i2cServiceReset(device); + if (!state->initialized || state->busy) { return false; } @@ -410,6 +439,8 @@ bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) i2cBusState_t *state = &busState[device]; + i2cServiceReset(device); + if (state->busy && i2cTransferStuck(state)) { // No progress within the timeout, the transfer is stuck - reset the peripheral i2cRecoverStuckTransfer(device); @@ -509,11 +540,7 @@ static void i2cErrorHandler(I2CDevice device) I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable the RXNE/TXE interrupt - prevent the ISR tailchaining onto the ER (hopefully) if (!(SR1Register & I2C_SR1_ARLO) && !(I2Cx->CR1 & I2C_CR1_STOP)) { // if we dont have an ARLO error, ensure sending of a stop (after ARLO the hardware has already released the bus) if (I2Cx->CR1 & I2C_CR1_START) { // We are currently trying to send a start, this is very bad as start, stop will hang the peripheral - i2cWaitBitRelease(I2Cx, I2C_CR1_START); // wait for any start to finish sending - I2C_GenerateSTOP(I2Cx, ENABLE); // send stop to finalise bus transaction - i2cWaitBitRelease(I2Cx, I2C_CR1_STOP); // wait for stop to finish sending - i2cHandleHardwareFailure(device); // reset and configure the hardware - state->error = true; // the reset cleared the state, the transfer still failed + state->needsReset = true; // waiting for the START here can take a while on a held bus: i2cServiceReset() finishes the cycle and resets the peripheral from task context } else { I2C_GenerateSTOP(I2Cx, ENABLE); // stop to free up the bus @@ -608,7 +635,14 @@ static void i2cEventHandlerBody(I2CDevice device) } // we must wait for the start to clear, otherwise we get constant BTF if (!i2cWaitBitRelease(I2Cx, I2C_CR1_START)) { - i2cRecoverStuckTransfer(device); + // The repeated START did not go out, the bus is held. Give the transfer up here and leave the reset to + // i2cServiceReset(), an unstick is too long for a handler + I2C_ITConfig(I2Cx, I2C_IT_EVT | I2C_IT_ERR | I2C_IT_BUF, DISABLE); + i2cErrorCount++; + state->error = true; + state->needsReset = true; + i2cAddrResultSet(&busAddrResults[device], state->addr >> 1, true); + state->busy = false; return; } } From 542dde43d3d4f4622546f951ec6b028fdd521c89 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 8 Oct 2026 20:48:21 +0200 Subject: [PATCH 03/14] I2C CORE - fix "A held bus can delay motor frames" --- docs/development/non-blocking-i2c.md | 17 +++++++++----- src/main/drivers/bus_i2c_stm32f40x.c | 35 ++++++++++++---------------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/development/non-blocking-i2c.md b/docs/development/non-blocking-i2c.md index 2968c93ed3f..1e4d1d78d80 100644 --- a/docs/development/non-blocking-i2c.md +++ b/docs/development/non-blocking-i2c.md @@ -82,12 +82,17 @@ costs one short failed start per attempt and nothing more. The F4 driver never reinitialised on a NACK for blocking calls either; the HAL and AT32 blocking calls keep reinitialising on failure, as before. -The F4 handlers never reinitialise the peripheral themselves. The I2C -interrupts sit above the motor timers and an unstick clocks the bus for up -to a few ms, so a transfer the handler has to give up on (a bus error with a -START still pending, a repeated START that does not go out within 1 ms) only -flags the bus: the next `i2cBusy()` or start call on that bus finishes the -cycle with a STOP and reinitialises the peripheral from task context. +The F4 handlers never wait on the bus or reinitialise the peripheral +themselves. The I2C interrupts sit above the motor timers and an unstick +clocks the bus for up to a few ms, so a transfer the handler has to give up +on (a bus error with a START still pending) only flags the bus: the next +`i2cBusy()` or start call on that bus finishes the cycle with a STOP and +reinitialises the peripheral from task context. The repeated START after the +register address is programmed without waiting for it to go out: the handler +clears BTF with a DR read (the ChibiOS I2Cv1 sequence) so the event interrupt +does not re-enter until the START is on the bus and EV5 fires. A repeated +START that never goes out on a held bus shows up as a stuck transfer through +the progress timeout, like any other stalled phase. A bus that refuses every start as busy with no transfer of ours in flight (`HAL_BUSY` on F7/H7, `BUSYF` on the AT32) is a fault the stuck detection diff --git a/src/main/drivers/bus_i2c_stm32f40x.c b/src/main/drivers/bus_i2c_stm32f40x.c index c982029e774..29c1a147f54 100644 --- a/src/main/drivers/bus_i2c_stm32f40x.c +++ b/src/main/drivers/bus_i2c_stm32f40x.c @@ -23,10 +23,12 @@ * i2cBusy(). A blocking call issued while a non-blocking transfer is in * progress waits for it to finish first, so the two can share a bus. * - * The handlers never reinitialise the peripheral: an unstick clocks the bus - * for up to a few ms and the I2C interrupts sit above the motor timers. A - * transfer the handlers have to give up on flags the bus for a reset that - * the next i2cBusy() or start call performs from task context. + * The handlers never wait on the bus or reinitialise the peripheral: the + * I2C interrupts sit above the motor timers and an unstick clocks the bus + * for up to a few ms. A transfer the handlers have to give up on flags the + * bus for a reset that the next i2cBusy() or start call performs from task + * context, a transfer that stops making progress is caught by the same + * calls through the progress timeout. */ #include @@ -51,8 +53,8 @@ #ifndef SOFT_I2C -// Upper bound for the short waits on START/STOP bit release inside the handlers. -// Normally these clear within one SCL period; a longer wait means a stuck bus. +// Upper bound for the START/STOP bit release waits in i2cServiceReset(). +// Normally these clear within one SCL period; a longer wait means a held bus. #define I2C_BIT_RELEASE_TIMEOUT_US 1000 #define GPIO_AF_I2C GPIO_AF_I2C1 @@ -117,7 +119,7 @@ typedef struct { uint16_t errorIrqs; // error interrupts since boot uint16_t lastTransferUs; // start to completion of the last transfer uint16_t maxIrqUs; // longest single event handler run - uint16_t maxBitWaitUs; // longest wait for a START / STOP bit release + uint16_t maxBitWaitUs; // longest wait for a START / STOP bit release in i2cServiceReset() uint16_t startCr2; // interrupt enables found in CR2 when a transfer was started, should be 0 uint16_t startCallUs; // time spent in the last i2cStartTransfer() call } i2cDebugStats_t; @@ -195,7 +197,7 @@ static bool i2cHandleHardwareFailure(I2CDevice device) return false; } -// Wait for the hardware to release a CR1 control bit (START / STOP). Safe to call from the handlers. +// Wait for the hardware to release a CR1 control bit (START / STOP). Task context only, the handlers never wait on the bus. static bool i2cWaitBitRelease(I2C_TypeDef *I2Cx, uint32_t cr1Mask) { const timeUs_t startUs = microsISR(); @@ -629,22 +631,15 @@ static void i2cEventHandlerBody(I2CDevice device) state->index++; // to show that the job is complete } else { // We need to send a subaddress + // BTF stays set until the repeated START is out on the bus and EVT would re-enter the handler until + // then. SR1 was read above, so a DR read clears BTF now (RM0090 I2C_SR1.BTF) and in transmitter mode + // touches nothing else; the handler returns without waiting for the START. EV5 picks the transfer up + // when the START goes out, a START that never goes out (held bus) is caught by i2cTransferStuck() + (void)I2Cx->DR; I2C_GenerateSTART(I2Cx, ENABLE); // program the repeated Start state->subaddressSent = true; // this is set back to zero upon completion of the current task } } - // we must wait for the start to clear, otherwise we get constant BTF - if (!i2cWaitBitRelease(I2Cx, I2C_CR1_START)) { - // The repeated START did not go out, the bus is held. Give the transfer up here and leave the reset to - // i2cServiceReset(), an unstick is too long for a handler - I2C_ITConfig(I2Cx, I2C_IT_EVT | I2C_IT_ERR | I2C_IT_BUF, DISABLE); - i2cErrorCount++; - state->error = true; - state->needsReset = true; - i2cAddrResultSet(&busAddrResults[device], state->addr >> 1, true); - state->busy = false; - return; - } } else if (SReg_1 & I2C_SR1_RXNE) { // Byte received - EV7 state->readBuf[state->index++] = (uint8_t)I2Cx->DR; From 8a021d400c279826acf4f141d27dce3b14e5f221 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 8 Oct 2026 21:20:46 +0200 Subject: [PATCH 04/14] I2C CORE - fix HITL Baro driver --- docs/development/non-blocking-i2c.md | 5 ++++- src/main/drivers/barometer/barometer.h | 5 +++-- src/main/sensors/barometer.c | 26 ++++++++++++++++++++++++-- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/docs/development/non-blocking-i2c.md b/docs/development/non-blocking-i2c.md index 1e4d1d78d80..1c7aeacb84a 100644 --- a/docs/development/non-blocking-i2c.md +++ b/docs/development/non-blocking-i2c.md @@ -112,7 +112,10 @@ it with the same stuck detection, then runs as before. start_ut -> (ut_delay) -> read_ut -> get_ut -> start_up -> (up_delay) -> read_up -> get_up -> calculate ``` -* `start_*` triggers a measurement, usually a `busWriteStart()`. +* `start_*` triggers a measurement, usually a `busWriteStart()`. The + matching `read_*` is only called once that write is over; a write that + failed (NACK, bus error) restarts the phase, since the sensor's data + registers would still hold the previous conversion. * `read_*` starts the data transfer with `busReadBufStart()` and returns `false` when the bus is busy. * `get_*` only parses the static buffer and returns `false` when the sample diff --git a/src/main/drivers/barometer/barometer.h b/src/main/drivers/barometer/barometer.h index cb7c3ad63e7..e70ac66e82e 100644 --- a/src/main/drivers/barometer/barometer.h +++ b/src/main/drivers/barometer/barometer.h @@ -28,8 +28,9 @@ typedef bool (*baroCalculateFuncPtr)(struct baroDev_s * baro, int32_t *pressure, * * A driver may leave any hook NULL. The optional read_* hooks start a non-blocking bus transfer and must return false * when the bus is busy; the matching get_* then only parses the received buffer once the bus reports idle and returns - * false if the sample is not usable (the phase is restarted). Drivers without read_* hooks do their blocking bus access - * inside get_*. A delay of 0 keeps the current task period. + * false if the sample is not usable (the phase is restarted). A start_* hook paired with a read_* hook may start a + * non-blocking write: read_* is only called once that write is over and the phase is restarted if it failed. Drivers + * without read_* hooks do their blocking bus access inside get_*. A delay of 0 keeps the current task period. */ typedef struct baroDev_s { busDevice_t * busDev; diff --git a/src/main/sensors/barometer.c b/src/main/sensors/barometer.c index fb9f9737110..3b8c638a080 100644 --- a/src/main/sensors/barometer.c +++ b/src/main/sensors/barometer.c @@ -288,9 +288,11 @@ uint32_t baroUpdate(bool *newSampleReady) #ifdef USE_SIMULATOR if (ARMING_FLAG(SIMULATOR_MODE_HITL)) { - // Pressure and temperature are injected over MSP, keep publishing them at the sensor's pace + // Pressure and temperature are injected over MSP, keep publishing them at the sensor's pace. The two delays + // together are one measurement cycle; up_delay alone is a 1 ms scheduler step for some drivers (DPS310). + // Without a physical sensor both are 0 and the task keeps its default period *newSampleReady = true; - return dev->up_delay; + return dev->ut_delay + dev->up_delay; } #endif @@ -307,6 +309,17 @@ uint32_t baroUpdate(bool *newSampleReady) case BARO_STATE_TEMPERATURE_READ: if (dev->read_ut) { + // The start_ut write has to have reached the sensor, otherwise the data registers still hold the + // previous conversion and a successful read would publish it as a new sample + if (dev->start_ut && dev->busDev) { + if (busIsBusy(dev->busDev, &busError)) { + return BARO_STATE_STEP_DELAY_US; // trigger write still in progress + } + if (busError) { + state = BARO_STATE_TEMPERATURE_START; // trigger write failed, redo the phase + break; + } + } if (!dev->read_ut(dev)) { return BARO_STATE_STEP_DELAY_US; // bus is busy, try again shortly } @@ -341,6 +354,15 @@ uint32_t baroUpdate(bool *newSampleReady) case BARO_STATE_PRESSURE_READ: if (dev->read_up) { + if (dev->start_up && dev->busDev) { + if (busIsBusy(dev->busDev, &busError)) { + return BARO_STATE_STEP_DELAY_US; // trigger write still in progress + } + if (busError) { + state = BARO_STATE_PRESSURE_START; // trigger write failed, redo the phase + break; + } + } if (!dev->read_up(dev)) { return BARO_STATE_STEP_DELAY_US; // bus is busy, try again shortly } From db554366f4c8838d077984fb4a73dbea3f77ac23 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 8 Oct 2026 21:25:10 +0200 Subject: [PATCH 05/14] I2C CORE - fix rp2350 error handling --- docs/development/non-blocking-i2c.md | 2 +- src/main/drivers/bus_i2c.h | 2 +- src/main/drivers/bus_i2c_rp2350.c | 35 ++++++++++++++++++++++------ src/main/drivers/bus_i2c_soft.c | 20 +++++++++++----- 4 files changed, 44 insertions(+), 15 deletions(-) diff --git a/docs/development/non-blocking-i2c.md b/docs/development/non-blocking-i2c.md index 1c7aeacb84a..6816b9cfe74 100644 --- a/docs/development/non-blocking-i2c.md +++ b/docs/development/non-blocking-i2c.md @@ -34,7 +34,7 @@ Every platform implements the same `drivers/bus_i2c.h` API: | STM32F4 | Own interrupt-driven engine in `bus_i2c_stm32f40x.c`, ported from the Betaflight `bus_i2c_stm32f4xx.c` driver. Blocking calls use the same engine and wait for it. | | STM32F7/H7 | `HAL_I2C_Mem_Read_IT()` and friends, completion through the `HAL_I2C_*CpltCallback()` / `HAL_I2C_ErrorCallback()` hooks. | | AT32F43x | `i2c_memory_read_int()` and friends from `i2c_application`. The library sends the slave and register address synchronously (tens of µs, bounded by the library timeout), only the data phase runs in the interrupt. A NACK in that address phase is reported like any other failed transfer: the start call returns `true` and `i2cBusy()` reports the error at once. | -| RP2350, software I2C, SITL | Synchronous: the start call completes the transfer, `i2cBusy()` is always `false`. | +| RP2350, software I2C, SITL | Synchronous: the start call completes the transfer and returns `true`, `i2cBusy()` is always `false` and carries the outcome. A NACK is a failed transfer, not a refused start. | `i2cWriteStart()` copies the data byte into driver-owned storage, the caller does not have to keep it alive. Buffers given to `i2cReadStart()` and diff --git a/src/main/drivers/bus_i2c.h b/src/main/drivers/bus_i2c.h index cd6f6578ebe..f7d33b14406 100644 --- a/src/main/drivers/bus_i2c.h +++ b/src/main/drivers/bus_i2c.h @@ -71,7 +71,7 @@ bool i2cRead(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, uint8_t* // Non-blocking transfers: start returns immediately (false if the bus is busy or the transfer could not be started), // completion and the result are polled with i2cBusy(). Platforms without an asynchronous driver complete the -// transfer synchronously inside the start call and report the bus as idle. +// transfer synchronously inside the start call, return true and let i2cBusy() report the bus as idle with the outcome. bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, uint8_t* buf, bool allowRawAccess); bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t data, bool allowRawAccess); bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, const uint8_t *data, bool allowRawAccess); // data must stay valid until i2cBusy() reports idle diff --git a/src/main/drivers/bus_i2c_rp2350.c b/src/main/drivers/bus_i2c_rp2350.c index b3714b28501..a66016c7b43 100644 --- a/src/main/drivers/bus_i2c_rp2350.c +++ b/src/main/drivers/bus_i2c_rp2350.c @@ -78,6 +78,7 @@ static uint16_t i2cErrorCount = 0; typedef struct { i2c_inst_t *hw; bool initialised; + i2cAddrResults_t addrResults; // outcome of the last start call per slave, reported by i2cBusy() } rp2350_i2c_state_t; static rp2350_i2c_state_t i2cState[I2CDEV_COUNT]; @@ -216,28 +217,48 @@ bool i2cRead(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, return true; } -// Non-blocking transfers are not implemented for this platform yet - complete them synchronously +// Non-blocking transfers are not implemented for this platform yet - complete them synchronously. The start call +// returns false only when nothing could be started (unusable device); a NACK or bus error is a finished, failed +// transfer that i2cBusy() reports, the same as the interrupt driven drivers once the transfer is over +static bool i2cStartUsable(I2CDevice device) +{ + return device >= 0 && device < I2CDEV_COUNT && i2cState[device].initialised; +} + +static bool i2cTransferDone(I2CDevice device, uint8_t addr_, bool ok) +{ + i2cAddrResultSet(&i2cState[device].addrResults, addr_, !ok); + return true; +} + bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t len, uint8_t* buf, bool allowRawAccess) { - return i2cRead(device, addr_, reg, len, buf, allowRawAccess); + if (!i2cStartUsable(device)) { + return false; + } + return i2cTransferDone(device, addr_, i2cRead(device, addr_, reg, len, buf, allowRawAccess)); } bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) { - return i2cWriteBuffer(device, addr_, reg_, len_, data, allowRawAccess); + if (!i2cStartUsable(device)) { + return false; + } + return i2cTransferDone(device, addr_, i2cWriteBuffer(device, addr_, reg_, len_, data, allowRawAccess)); } bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg, uint8_t data, bool allowRawAccess) { - return i2cWrite(device, addr_, reg, data, allowRawAccess); + if (!i2cStartUsable(device)) { + return false; + } + return i2cTransferDone(device, addr_, i2cWrite(device, addr_, reg, data, allowRawAccess)); } bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) { - UNUSED(device); - UNUSED(addr_); if (error) { - *error = false; + *error = i2cStartUsable(device) ? i2cAddrResultFailed(&i2cState[device].addrResults, addr_) : true; } /* Blocking implementation - transfers complete before returning */ return false; diff --git a/src/main/drivers/bus_i2c_soft.c b/src/main/drivers/bus_i2c_soft.c index aa6f13c30a7..ea209dd35b3 100644 --- a/src/main/drivers/bus_i2c_soft.c +++ b/src/main/drivers/bus_i2c_soft.c @@ -34,6 +34,7 @@ static IO_t scl; static IO_t sda; static volatile uint16_t i2cErrorCount = 0; +static i2cAddrResults_t addrResults; // outcome of the last start call per slave, reported by i2cBusy(); one bus only #define SCL_H IOHi(scl) #define SCL_L IOLo(scl) @@ -290,28 +291,35 @@ bool i2cRead(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, uint8_t * return true; } -// Non-blocking transfers are not implemented for this platform yet - complete them synchronously +// Non-blocking transfers are not implemented for this platform yet - complete them synchronously. A NACK or bus +// error is a finished, failed transfer that i2cBusy() reports, the same as the interrupt driven drivers once the +// transfer is over; the start call itself always succeeds +static bool i2cTransferDone(uint8_t addr_, bool ok) +{ + i2cAddrResultSet(&addrResults, addr_, !ok); + return true; +} + bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t* buf, bool allowRawAccess) { - return i2cRead(device, addr_, reg_, len, buf, allowRawAccess); + return i2cTransferDone(addr_, i2cRead(device, addr_, reg_, len, buf, allowRawAccess)); } bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) { - return i2cWriteBuffer(device, addr_, reg_, len_, data, allowRawAccess); + return i2cTransferDone(addr_, i2cWriteBuffer(device, addr_, reg_, len_, data, allowRawAccess)); } bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t data, bool allowRawAccess) { - return i2cWrite(device, addr_, reg_, data, allowRawAccess); + return i2cTransferDone(addr_, i2cWrite(device, addr_, reg_, data, allowRawAccess)); } bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) { UNUSED(device); - UNUSED(addr_); if (error) { - *error = false; + *error = i2cAddrResultFailed(&addrResults, addr_); } // Blocking driver - a transfer is finished when the start call returns return false; From 4ca2c35fe11ff4655d9c49f32ae3fd144fd2ddd7 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 8 Oct 2026 21:53:34 +0200 Subject: [PATCH 06/14] I2C CORE - update doc --- docs/development/non-blocking-i2c.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development/non-blocking-i2c.md b/docs/development/non-blocking-i2c.md index 6816b9cfe74..bfb5aaa387c 100644 --- a/docs/development/non-blocking-i2c.md +++ b/docs/development/non-blocking-i2c.md @@ -181,7 +181,7 @@ Drivers for other buses (SPI gyros, MSP, fake sensors) need no change. ## Debugging -`set debug_mode = I2C`, then `debug` in the CLI: +`set debug_mode = I2C`, then `showdebug` in the CLI: | Field | Meaning | |---|---| From 76bd08a14ac9d0912586500e30f7250655b85b34 Mon Sep 17 00:00:00 2001 From: Error414 Date: Sun, 11 Oct 2026 12:54:28 +0200 Subject: [PATCH 07/14] I2C CORE - fix code review --- src/main/drivers/bus.h | 2 +- src/main/drivers/bus_busdev_i2c.c | 1 + src/main/drivers/bus_i2c_at32f43x.c | 7 +++++-- src/main/drivers/bus_i2c_hal.c | 15 ++++++++------- src/main/drivers/bus_i2c_stm32f40x.c | 13 +++++-------- 5 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/main/drivers/bus.h b/src/main/drivers/bus.h index fe2a9fd2e00..2cb86ff2260 100644 --- a/src/main/drivers/bus.h +++ b/src/main/drivers/bus.h @@ -283,7 +283,6 @@ extern const busDeviceDescriptor_t __busdev_registry_end[]; #define BUSDEV_REGISTER_I2C_TAG(_name, _devHw, _i2cBus, _devAddr, _irqPin, _tag, _flags, _param) // NO-OP #endif -// busTransfer and busTransferMultiple are supported only on full-duplex SPI bus /* * Result of one step of a sensor read made of several non-blocking transfers (status poll, trigger, data). * The sensor layer calls the driver's readStart(dev, firstStep) with firstStep set for the first transfer and @@ -295,6 +294,7 @@ typedef enum { BUS_READ_STEP_LAST, // the final transfer was started, call read() once it is done } busReadStepResult_e; +// busTransfer and busTransferMultiple are supported only on full-duplex SPI bus typedef struct busTransferDescriptor_s { uint8_t * rxBuf; const uint8_t * txBuf; diff --git a/src/main/drivers/bus_busdev_i2c.c b/src/main/drivers/bus_busdev_i2c.c index 370d7f308dc..da043d6e894 100644 --- a/src/main/drivers/bus_busdev_i2c.c +++ b/src/main/drivers/bus_busdev_i2c.c @@ -53,6 +53,7 @@ bool i2cBusReadRegister(const busDevice_t * dev, uint8_t reg, uint8_t * data) const bool allowRawAccess = (dev->flags & DEVFLAGS_USE_RAW_REGISTERS); return i2cRead(dev->busdev.i2c.i2cBus, dev->busdev.i2c.address, reg, 1, data, allowRawAccess); } + bool i2cBusReadBufferStart(const busDevice_t * dev, uint8_t reg, uint8_t * data, uint8_t length) { const bool allowRawAccess = (dev->flags & DEVFLAGS_USE_RAW_REGISTERS); diff --git a/src/main/drivers/bus_i2c_at32f43x.c b/src/main/drivers/bus_i2c_at32f43x.c index 6db48cf3667..327cef2eeb0 100644 --- a/src/main/drivers/bus_i2c_at32f43x.c +++ b/src/main/drivers/bus_i2c_at32f43x.c @@ -234,8 +234,11 @@ static void i2cPollPending(I2CDevice device) } // The end-of-transfer status is private to i2c_application.c, i2c_wait_end() with a zero timeout only probes it: - // I2C_ERR_TIMEOUT means the transfer is still running, anything else means it finished - if (state->handle.error_code != I2C_OK || i2c_wait_end(&state->handle, 0) != I2C_ERR_TIMEOUT) { + // I2C_ERR_TIMEOUT means the transfer is still running, anything else means it finished. error_code alone is not + // the end: after a NACK the library sets it from the interrupt and finishes with the STOP interrupt later, a new + // start in between would have its status overwritten with I2C_END by that STOP. A transfer that never reaches the + // end after an error interrupt is caught by the stuck check below + if (i2c_wait_end(&state->handle, 0) != I2C_ERR_TIMEOUT) { i2cStats.lastTransferUs = micros() - state->startUs; if (state->handle.error_code != I2C_OK) { i2cErrorCount++; // keep the "I2C Errors" count of status / MSP meaningful for non-blocking transfers diff --git a/src/main/drivers/bus_i2c_hal.c b/src/main/drivers/bus_i2c_hal.c index 0f737967286..2d2425e5eae 100644 --- a/src/main/drivers/bus_i2c_hal.c +++ b/src/main/drivers/bus_i2c_hal.c @@ -628,6 +628,14 @@ void i2cInit(I2CDevice device) // Enable RCC RCC_ClockCmd(hardware->rcc, ENABLE); + if (state->initialised) { + // Re-initialisation after a failure: drop whatever transfer the HAL still thinks is running. Done before the + // unstick so that the peripheral and its interrupts do not react to the bus being clocked by hand + HAL_I2C_DeInit(pHandle); + } + state->busy = false; + state->error = false; + IO_t scl = IOGetByTag(hardware->scl); IO_t sda = IOGetByTag(hardware->sda); @@ -641,13 +649,6 @@ void i2cInit(I2CDevice device) IOConfigGPIOAF(sda, IOCFG_I2C, hardware->af); // Init I2C peripheral - if (state->initialised) { - // Re-initialisation after a failure: drop whatever transfer the HAL still thinks is running - HAL_I2C_DeInit(pHandle); - } - state->busy = false; - state->error = false; - pHandle->Instance = hardware->dev; /* diff --git a/src/main/drivers/bus_i2c_stm32f40x.c b/src/main/drivers/bus_i2c_stm32f40x.c index 29c1a147f54..e5c40b89723 100644 --- a/src/main/drivers/bus_i2c_stm32f40x.c +++ b/src/main/drivers/bus_i2c_stm32f40x.c @@ -53,7 +53,7 @@ #ifndef SOFT_I2C -// Upper bound for the START/STOP bit release waits in i2cServiceReset(). +// Upper bound for the START/STOP bit release waits in task context (i2cServiceReset(), transfer start). // Normally these clear within one SCL period; a longer wait means a held bus. #define I2C_BIT_RELEASE_TIMEOUT_US 1000 @@ -119,8 +119,8 @@ typedef struct { uint16_t errorIrqs; // error interrupts since boot uint16_t lastTransferUs; // start to completion of the last transfer uint16_t maxIrqUs; // longest single event handler run - uint16_t maxBitWaitUs; // longest wait for a START / STOP bit release in i2cServiceReset() - uint16_t startCr2; // interrupt enables found in CR2 when a transfer was started, should be 0 + uint16_t maxBitWaitUs; // longest wait for a START / STOP bit release in task context + uint16_t startCr2; // interrupt enables found in CR2 when a transfer was started: EVT and ERR off, BUF may be left on (1024) uint16_t startCallUs; // time spent in the last i2cStartTransfer() call } i2cDebugStats_t; @@ -388,11 +388,8 @@ static bool i2cStartTransfer(I2CDevice device, uint8_t addr, uint8_t reg, bool a if (!(I2Cx->CR2 & I2C_IT_EVT)) { // interrupts are off between transfers if (!(I2Cx->CR1 & I2C_CR1_START)) { // ensure sending a start - const timeUs_t startUs = micros(); - while (I2Cx->CR1 & I2C_CR1_STOP) { // wait for any stop to finish sending - if (cmpTimeUs(micros(), startUs) >= I2C_TIMEOUT) { - return i2cHandleHardwareFailure(device); - } + if (!i2cWaitBitRelease(I2Cx, I2C_CR1_STOP)) { // wait for any stop to finish sending + return i2cHandleHardwareFailure(device); } I2C_GenerateSTART(I2Cx, ENABLE); // send the start for the new job } From 90310fffb1256402455698293bd6241c98db863a Mon Sep 17 00:00:00 2001 From: Error414 Date: Sat, 17 Oct 2026 20:17:15 +0200 Subject: [PATCH 08/14] I2C CORE - apply PR fix #12113 --- src/main/drivers/barometer/barometer_spl06.c | 9 ++++++++- src/main/drivers/barometer/barometer_spl06.h | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/drivers/barometer/barometer_spl06.c b/src/main/drivers/barometer/barometer_spl06.c index e463ee1ea27..58bd20c5104 100644 --- a/src/main/drivers/barometer/barometer_spl06.c +++ b/src/main/drivers/barometer/barometer_spl06.c @@ -207,7 +207,14 @@ static bool spl06_configure_measurements(baroDev_t *baro) { uint8_t reg_value; - reg_value = SPL06_TEMP_USE_EXT_SENSOR | spl06_samples_to_cfg_reg_value(SPL06_TEMPERATURE_OVERSAMPLING); + // COEF_SRCE tells which sensor the coefficients were made for; some parts with this chip ID use the internal one + uint8_t coef_source; + if (!busRead(baro->busDev, SPL06_COEF_SRCE_REG, &coef_source)) { + coef_source = SPL06_TEMP_USE_EXT_SENSOR; // the SPL06-001 datasheet does not list the register + } + + reg_value = (coef_source & SPL06_TEMP_USE_EXT_SENSOR) | + spl06_samples_to_cfg_reg_value(SPL06_TEMPERATURE_OVERSAMPLING); if (!busWrite(baro->busDev, SPL06_TEMPERATURE_CFG_REG, reg_value)) { return false; } diff --git a/src/main/drivers/barometer/barometer_spl06.h b/src/main/drivers/barometer/barometer_spl06.h index a92f1c57ece..9118106ff6a 100644 --- a/src/main/drivers/barometer/barometer_spl06.h +++ b/src/main/drivers/barometer/barometer_spl06.h @@ -42,6 +42,7 @@ #define SPL06_CHIP_ID_REG 0x0D // Chip ID Register #define SPL06_CALIB_COEFFS_START 0x10 #define SPL06_CALIB_COEFFS_END 0x21 +#define SPL06_COEF_SRCE_REG 0x28 // Sensor the temperature coefficients were made for #define SPL06_CALIB_COEFFS_LEN (SPL06_CALIB_COEFFS_END - SPL06_CALIB_COEFFS_START + 1) From 71f1e292e1de48e22d4df920bdf04f8a531a76f9 Mon Sep 17 00:00:00 2001 From: Error414 Date: Mon, 2 Nov 2026 19:26:58 +0100 Subject: [PATCH 09/14] I2C CORE - fix IRQ handling for AT32, add state machine instead of waiting to start transfer --- docs/development/non-blocking-i2c.md | 12 +- src/main/drivers/bus_i2c_at32f43x.c | 167 ++++++++++++++++++--------- src/main/drivers/i2c_application.h | 1 + 3 files changed, 120 insertions(+), 60 deletions(-) diff --git a/docs/development/non-blocking-i2c.md b/docs/development/non-blocking-i2c.md index bfb5aaa387c..5eae1dbf230 100644 --- a/docs/development/non-blocking-i2c.md +++ b/docs/development/non-blocking-i2c.md @@ -33,7 +33,7 @@ Every platform implements the same `drivers/bus_i2c.h` API: |---|---| | STM32F4 | Own interrupt-driven engine in `bus_i2c_stm32f40x.c`, ported from the Betaflight `bus_i2c_stm32f4xx.c` driver. Blocking calls use the same engine and wait for it. | | STM32F7/H7 | `HAL_I2C_Mem_Read_IT()` and friends, completion through the `HAL_I2C_*CpltCallback()` / `HAL_I2C_ErrorCallback()` hooks. | -| AT32F43x | `i2c_memory_read_int()` and friends from `i2c_application`. The library sends the slave and register address synchronously (tens of µs, bounded by the library timeout), only the data phase runs in the interrupt. A NACK in that address phase is reported like any other failed transfer: the start call returns `true` and `i2cBusy()` reports the error at once. | +| AT32F43x | The `i2c_application` interrupt handler for the data phase. Its `i2c_memory_*_int()` calls busy-wait for the slave and register address, so the driver does not use them: it sends the register byte from its own event interrupt wrapper and, for a read, issues the repeated START there at TDC (the register byte goes out with a software STOP). The start call only programs the peripheral and checks BUSYF once. | | RP2350, software I2C, SITL | Synchronous: the start call completes the transfer and returns `true`, `i2cBusy()` is always `false` and carries the outcome. A NACK is a failed transfer, not a refused start. | `i2cWriteStart()` copies the data byte into driver-owned storage, the caller @@ -75,10 +75,9 @@ phase on the F4), not the time since the start: A NACK or a bus error ends a non-blocking transfer at once: the error is recorded for its owner and the counter shown by `status` goes up. The -peripheral is not reinitialised for that, it is fine after a NACK. This -includes the AT32 address phase, which runs inside the start call: the call -returns `true` and `i2cBusy()` reports the failure, so an unplugged sensor -costs one short failed start per attempt and nothing more. The F4 driver +peripheral is not reinitialised for that, it is fine after a NACK, so an +unplugged sensor costs one short failed transfer per attempt and nothing +more. The F4 driver never reinitialised on a NACK for blocking calls either; the HAL and AT32 blocking calls keep reinitialising on failure, as before. @@ -192,12 +191,11 @@ Drivers for other buses (SPI gyros, MSP, fake sensors) need no change. | `debug[4]` | longest wait for a START / STOP bit release in µs (F4 only) | | `debug[5]` | I2C error counter, also shown by `status` | | `debug[6]` | interrupt enables found at transfer start (F4 only, 1024 is normal) | -| `debug[7]` | time spent in the start call in µs, should be a few µs on F4/F7/H7 | +| `debug[7]` | time spent in the start call in µs, should be a few µs | ## Known limitations * No bus arbitration queue: a device that finds the bus busy retries later. Fine at the 10 to 60 Hz rates the sensors use. -* On the AT32 the start call blocks for the address phase of the transfer. * The RP2350 driver is still blocking. * SPI stays synchronous. diff --git a/src/main/drivers/bus_i2c_at32f43x.c b/src/main/drivers/bus_i2c_at32f43x.c index 327cef2eeb0..ebd561a4b8c 100644 --- a/src/main/drivers/bus_i2c_at32f43x.c +++ b/src/main/drivers/bus_i2c_at32f43x.c @@ -97,12 +97,18 @@ typedef struct { bool pending; uint8_t addr; // 7-bit address of the current / last non-blocking transfer timeUs_t startUs; // start time of the transfer, for the debug statistics + volatile timeUs_t endUs; // time of the STOPF interrupt that ended it uint16_t lastPcount; // bytes left at the previous look, a change means the transfer moves uint32_t stuckUs; // time looked at without progress, a long gap between looks counts as I2C_STUCK_LOOK_GAP_US timeUs_t lookUs; // time of the previous look uint32_t heldUs; // time starts were refused with the bus busy and nothing of ours in flight timeUs_t heldLookUs; // time of the previous refused start uint8_t txByte; // data of a non-blocking single byte write, must outlive the call + // Register phase of a non-blocking register transfer, run by i2cEventIrq() ahead of the i2c_application handler + volatile bool sendReg; // regByte goes out at the first TDIS + uint8_t regByte; + uint8_t * volatile rxBuf; // a read follows: at TDC after the register byte a repeated START switches to receive + volatile uint8_t rxLen; // length of that read, 0 when no read follows i2cAddrResults_t addrResults; // outcome per slave address, survives i2cInit() } i2cState_t; @@ -127,10 +133,88 @@ static void i2cDebugPublish(void) DEBUG_SET(DEBUG_I2C, 7, i2cStats.startCallUs); } +/* + * The i2c_application library only puts the data phase of a register transfer in the interrupt, its *_memory_*_int() + * functions busy-wait for the address and register byte. The register phase is done here instead, everything else is + * left to the library handler. + */ static void i2cEventIrq(I2CDevice device) { + i2cState_t * state = &i2cState[device]; + i2c_handle_type * handle = &state->handle; + i2cStats.eventIrqs++; - i2c_evt_irq_handler(&i2cState[device].handle); + + if (state->sendReg || state->rxLen) { + if (i2c_flag_get(handle->i2cx, I2C_ACKFAIL_FLAG) != RESET) { + // Address or register byte not acknowledged. The hardware sends the STOP, the library handler clears the + // flag and ends the transfer at STOPF. It flags the error only while pcount is non-zero, which is no + // longer the case once the register byte of a read is out + handle->error_code = I2C_ERR_ACKFAIL; + state->sendReg = false; + state->rxLen = 0; + } + else if (state->sendReg && i2c_flag_get(handle->i2cx, I2C_TDIS_FLAG) != RESET) { + i2c_data_send(handle->i2cx, state->regByte); + handle->pcount--; + handle->psize--; + state->sendReg = false; + return; + } + else if (state->rxLen && i2c_flag_get(handle->i2cx, I2C_TDC_FLAG) != RESET) { + // Register byte is out, repeated START for the read. Setting START clears TDC + handle->mode = I2C_INT_MA_RX; + handle->pbuff = state->rxBuf; + handle->pcount = state->rxLen; + state->rxLen = 0; + i2c_interrupt_enable(handle->i2cx, I2C_TD_INT, FALSE); + i2c_interrupt_enable(handle->i2cx, I2C_RD_INT, TRUE); + i2c_start_transfer(handle, state->addr << 1, I2C_GEN_START_READ); + return; + } + } + + // STOPF ends every interrupt driven transfer, also a NACKed one + const bool stop = (i2c_flag_get(handle->i2cx, I2C_STOPF_FLAG) != RESET); + + i2c_evt_irq_handler(handle); + + if (stop) { + state->endUs = micros(); + } +} + +// Kick off a transfer whose register byte is sent by i2cEventIrq(). With rxLen != 0 a read of rxLen bytes into rxBuf +// follows, otherwise the len bytes of buf are written after the register byte. Nothing waits on the bus here +static void i2cStartRegisterTransfer(i2cState_t * state, uint8_t reg, uint8_t *buf, uint8_t len, bool reading) +{ + i2c_handle_type * handle = &state->handle; + + handle->status = 0; // I2C_START, private to i2c_application.c like I2C_END + handle->error_code = I2C_OK; + handle->mode = I2C_INT_MA_TX; + + state->regByte = reg; + state->sendReg = true; + + if (reading) { + // Register byte alone with a software STOP, so TDC fires after it instead of a STOP going out + state->rxBuf = buf; + state->rxLen = len; + handle->pbuff = NULL; + handle->pcount = 1; + handle->psize = 1; + i2c_transmit_set(handle->i2cx, state->addr << 1, 1, I2C_SOFT_STOP_MODE, I2C_GEN_START_WRITE); + } + else { + // Register byte and data in one transfer, the library handler sends the data from TDIS + state->rxLen = 0; + handle->pbuff = buf; + handle->pcount = len + 1; + i2c_start_transfer(handle, state->addr << 1, I2C_GEN_START_WRITE); + } + + i2c_interrupt_enable(handle->i2cx, I2C_ERR_INT | I2C_TDC_INT | I2C_STOP_INT | I2C_ACKFIAL_INT | I2C_TD_INT, TRUE); } static void i2cErrorIrq(I2CDevice device) @@ -239,7 +323,7 @@ static void i2cPollPending(I2CDevice device) // start in between would have its status overwritten with I2C_END by that STOP. A transfer that never reaches the // end after an error interrupt is caught by the stuck check below if (i2c_wait_end(&state->handle, 0) != I2C_ERR_TIMEOUT) { - i2cStats.lastTransferUs = micros() - state->startUs; + i2cStats.lastTransferUs = state->endUs - state->startUs; if (state->handle.error_code != I2C_OK) { i2cErrorCount++; // keep the "I2C Errors" count of status / MSP meaningful for non-blocking transfers } @@ -263,10 +347,10 @@ static void i2cWaitForIdle(I2CDevice device) } /* - * Start an interrupt driven transfer. The i2c_application layer sends the slave and register address synchronously - * (a few tens of microseconds), the data phase runs from the interrupt handlers. - * Returns false if the bus is busy or the transfer could not be started. A NACK during the address phase is a finished, - * failed transfer: true is returned and i2cBusy() reports the failure, like for a NACK in the data phase. + * Start an interrupt driven transfer. Only the peripheral registers are set up here, the whole transfer including the + * slave and register address runs from the interrupt handlers. + * Returns false if the bus is busy or the transfer could not be started. A NACK is reported by i2cBusy() like any other + * failed transfer. */ static bool i2cStartTransfer(I2CDevice device, uint8_t addr_, uint8_t reg_, bool allowRawAccess, bool reading, uint8_t len, uint8_t *buf) { @@ -285,37 +369,15 @@ static bool i2cStartTransfer(I2CDevice device, uint8_t addr_, uint8_t reg_, bool if (state->pending) return false; - const timeUs_t callStartUs = micros(); - i2cStats.eventIrqs = 0; + const bool raw = (reg_ == 0xFF && allowRawAccess); - i2c_status_type status; + if (!reading && len == 0 && raw) + return false; // nothing to send - if (reading) { - if (reg_ == 0xFF && allowRawAccess) { - status = i2c_master_receive_int(&state->handle, addr_ << 1, buf, len, I2C_DEFAULT_TIMEOUT); - } - else { - status = i2c_memory_read_int(&state->handle, I2C_MEM_ADDR_WIDIH_8, addr_ << 1, reg_, buf, len, I2C_DEFAULT_TIMEOUT); - } - } - else if (len == 0) { - if (reg_ == 0xFF && allowRawAccess) { - return false; // nothing to send - } - // Register byte alone, sent as a plain one byte transfer - state->txByte = reg_; - status = i2c_master_transmit_int(&state->handle, addr_ << 1, &state->txByte, 1, I2C_DEFAULT_TIMEOUT); - } - else { - if (reg_ == 0xFF && allowRawAccess) { - status = i2c_master_transmit_int(&state->handle, addr_ << 1, buf, len, I2C_DEFAULT_TIMEOUT); - } - else { - status = i2c_memory_write_int(&state->handle, I2C_MEM_ADDR_WIDIH_8, addr_ << 1, reg_, buf, len, I2C_DEFAULT_TIMEOUT); - } - } + const timeUs_t callStartUs = micros(); - if (status == I2C_ERR_STEP_1) { + // Checked once instead of the library's busy-wait on BUSYF + if (i2c_flag_get(state->handle.i2cx, I2C_BUSYF_FLAG) != RESET) { // Bus busy with nothing of ours in flight: the previous STOP may still be going out. A bus that stays busy is // held by a slave or a confused peripheral and only a reset clears it, the stuck check never sees it if (i2cBusHeld(state)) { @@ -325,30 +387,29 @@ static bool i2cStartTransfer(I2CDevice device, uint8_t addr_, uint8_t reg_, bool return false; // try again later } - if (status != I2C_OK) { - /* the hardware has sent a STOP, wait for the stop flag and clear it */ - i2c_wait_flag(&state->handle, I2C_STOPF_FLAG, I2C_EVENT_CHECK_NONE, I2C_DEFAULT_TIMEOUT); - i2c_flag_clear(state->handle.i2cx, I2C_STOPF_FLAG); - - if (state->handle.error_code == I2C_ERR_ACKFAIL) { - // The slave did not answer its address or the register byte. The peripheral is fine after a NACK, so no - // reset: record the failure for the owner and let it find out from i2cBusy(). An unplugged sensor would - // otherwise cost a reinit and an unstick on every retry - i2c_reset_ctrl2_register(&state->handle); - i2cErrorCount++; - i2cStats.lastTransferUs = micros() - callStartUs; - i2cAddrResultSet(&state->addrResults, addr_, true); - state->heldUs = 0; - state->heldLookUs = callStartUs; - return true; - } + i2cStats.eventIrqs = 0; + state->addr = addr_; // the interrupt handler addresses the repeated START with it + state->sendReg = false; // left over by a transfer that was aborted by a reset + state->rxLen = 0; - return i2cHandleHardwareFailure(device); + // With BUSYF clear the library *_int() calls below return at once, their own BUSYF wait does not loop + if (reading && raw) { + i2c_master_receive_int(&state->handle, addr_ << 1, buf, len, I2C_DEFAULT_TIMEOUT); + } + else if (!reading && len == 0) { + // Register byte alone, sent as a plain one byte transfer + state->txByte = reg_; + i2c_master_transmit_int(&state->handle, addr_ << 1, &state->txByte, 1, I2C_DEFAULT_TIMEOUT); + } + else if (raw) { + i2c_master_transmit_int(&state->handle, addr_ << 1, buf, len, I2C_DEFAULT_TIMEOUT); + } + else { + i2cStartRegisterTransfer(state, reg_, buf, len, reading); } state->heldUs = 0; state->heldLookUs = callStartUs; - state->addr = addr_; state->startUs = callStartUs; state->lastPcount = state->handle.pcount; state->stuckUs = 0; diff --git a/src/main/drivers/i2c_application.h b/src/main/drivers/i2c_application.h index d63abaa4a46..c2fb570297f 100644 --- a/src/main/drivers/i2c_application.h +++ b/src/main/drivers/i2c_application.h @@ -147,6 +147,7 @@ typedef struct void i2c_config (i2c_handle_type* hi2c); void i2c_lowlevel_init (i2c_handle_type* hi2c); void i2c_reset_ctrl2_register (i2c_handle_type* hi2c); +void i2c_start_transfer (i2c_handle_type* hi2c, uint16_t address, i2c_start_mode_type start); i2c_status_type i2c_wait_end (i2c_handle_type* hi2c, uint32_t timeout); i2c_status_type i2c_wait_flag (i2c_handle_type* hi2c, uint32_t flag, uint32_t event_check, uint32_t timeout); From 7a3af1a63c61dab71a17e9e45baf43284caf1d25 Mon Sep 17 00:00:00 2001 From: Error414 Date: Thu, 5 Nov 2026 21:16:09 +0100 Subject: [PATCH 10/14] I2C CORE - for F7 change I2C HAL to direct register access to reduce memory. Idea from #12157 --- cmake/stm32f7.cmake | 4 +- docs/development/non-blocking-i2c.md | 35 +- src/main/drivers/bus_i2c_stm32f7xx.c | 664 +++++++++++++++++++++++++++ src/main/target/stm32f7xx_hal_conf.h | 2 +- 4 files changed, 689 insertions(+), 16 deletions(-) create mode 100644 src/main/drivers/bus_i2c_stm32f7xx.c diff --git a/cmake/stm32f7.cmake b/cmake/stm32f7.cmake index d8f52de333f..121c8dbf097 100644 --- a/cmake/stm32f7.cmake +++ b/cmake/stm32f7.cmake @@ -16,8 +16,6 @@ set(STM32F7_HAL_SRC stm32f7xx_hal_flash.c stm32f7xx_hal_flash_ex.c stm32f7xx_hal_gpio.c - stm32f7xx_hal_i2c.c - stm32f7xx_hal_i2c_ex.c stm32f7xx_hal_pcd.c stm32f7xx_hal_pcd_ex.c stm32f7xx_hal_pwr.c @@ -68,7 +66,7 @@ main_sources(STM32F7_SRC config/config_streamer_extflash.c drivers/adc_stm32f7xx.c - drivers/bus_i2c_hal.c + drivers/bus_i2c_stm32f7xx.c drivers/dma_stm32f7xx.c drivers/bus_spi_hal_ll.c drivers/timer.c diff --git a/docs/development/non-blocking-i2c.md b/docs/development/non-blocking-i2c.md index 5eae1dbf230..f9c4ae5449f 100644 --- a/docs/development/non-blocking-i2c.md +++ b/docs/development/non-blocking-i2c.md @@ -32,7 +32,8 @@ Every platform implements the same `drivers/bus_i2c.h` API: | Platform | Implementation | |---|---| | STM32F4 | Own interrupt-driven engine in `bus_i2c_stm32f40x.c`, ported from the Betaflight `bus_i2c_stm32f4xx.c` driver. Blocking calls use the same engine and wait for it. | -| STM32F7/H7 | `HAL_I2C_Mem_Read_IT()` and friends, completion through the `HAL_I2C_*CpltCallback()` / `HAL_I2C_ErrorCallback()` hooks. | +| STM32F7 | Own interrupt-driven engine on the I2C registers in `bus_i2c_stm32f7xx.c`, the ST HAL I2C module is not built. One CR2 write starts a transfer, the handler feeds TXDR / drains RXDR, issues the repeated START of a register read at TC and finishes at STOPF. Blocking calls use the same engine and wait for it. | +| STM32H7 | `HAL_I2C_Mem_Read_IT()` and friends in `bus_i2c_hal.c`, completion through the `HAL_I2C_*CpltCallback()` / `HAL_I2C_ErrorCallback()` hooks. | | AT32F43x | The `i2c_application` interrupt handler for the data phase. Its `i2c_memory_*_int()` calls busy-wait for the slave and register address, so the driver does not use them: it sends the register byte from its own event interrupt wrapper and, for a read, issues the repeated START there at TDC (the register byte goes out with a software STOP). The start call only programs the peripheral and checks BUSYF once. | | RP2350, software I2C, SITL | Synchronous: the start call completes the transfer and returns `true`, `i2cBusy()` is always `false` and carries the outcome. A NACK is a failed transfer, not a refused start. | @@ -42,7 +43,9 @@ does not have to keep it alive. Buffers given to `i2cReadStart()` and drivers use static buffers. A write with a zero length sends the register byte alone (the HAL and AT32 -blocking paths refuse zero-length transfers, the drivers wrap that). +blocking paths refuse zero-length transfers, the drivers wrap that). The F7 +refuses a register write of 255 data bytes: with the register byte that is +256, one more than its NBYTES field holds. ## Bus layer (`drivers/bus.h`) @@ -63,8 +66,8 @@ A non-blocking transfer is abandoned when it makes no progress for `I2C_TIMEOUT` (10 ms) while somebody looks at it: the peripheral is reinitialised with `i2cInit()`, the error counter goes up and the failure is recorded for the transfer's owner. Progress is the number of bytes still to -go (`XferCount` on the HAL, `pcount` on the AT32, byte index and subaddress -phase on the F4), not the time since the start: +go (`XferCount` on the H7 HAL, `pcount` on the AT32, byte index and register +phase on the F4 and F7), not the time since the start: * A gap between two looks longer than 1 ms counts as 1 ms. A main loop that was busy elsewhere for a while (a settings save) does not get a transfer @@ -77,8 +80,8 @@ A NACK or a bus error ends a non-blocking transfer at once: the error is recorded for its owner and the counter shown by `status` goes up. The peripheral is not reinitialised for that, it is fine after a NACK, so an unplugged sensor costs one short failed transfer per attempt and nothing -more. The F4 driver -never reinitialised on a NACK for blocking calls either; the HAL and AT32 +more. The F4 and F7 drivers +do not reinitialise on a NACK for blocking calls either; the H7 HAL and AT32 blocking calls keep reinitialising on failure, as before. The F4 handlers never wait on the bus or reinitialise the peripheral @@ -93,14 +96,22 @@ does not re-enter until the START is on the bus and EV5 fires. A repeated START that never goes out on a held bus shows up as a stuck transfer through the progress timeout, like any other stalled phase. +The F7 handler follows the same rule. A NACK needs nothing from it: the +hardware sends the STOP itself and the transfer ends at STOPF with the error +recorded. A bus error or an arbitration loss leaves the peripheral anywhere +in the transfer, so the handler gives up on it and flags the bus; the next +`i2cBusy()` or start call reinitialises the peripheral from task context, +like on the F4. + A bus that refuses every start as busy with no transfer of ours in flight -(`HAL_BUSY` on F7/H7, `BUSYF` on the AT32) is a fault the stuck detection +(`HAL_BUSY` on the H7, `BUSYF` on the AT32) is a fault the stuck detection cannot see, since nothing is in progress. The drivers count the refused starts the same way as the stuck looks and reinitialise the peripheral after `I2C_TIMEOUT` of them; the error counter goes up and the failure is recorded for the address that asked, so the owner sees it on its next `busIsBusy()`. -The F4 engine does not check the busy flag before a start, a held bus shows -up there as a stuck transfer. +The F4 and F7 engines do not check the busy flag before a start: the F7 +peripheral sends the START once the bus is free, so a held bus shows up on +both as a stuck transfer. A blocking call issued while a non-blocking transfer is on the bus waits for it with the same stuck detection, then runs as before. @@ -184,13 +195,13 @@ Drivers for other buses (SPI gyros, MSP, fake sensors) need no change. | Field | Meaning | |---|---| -| `debug[0]` | interrupts during the last transfer (about 10 for a 6 byte read on F4) | +| `debug[0]` | interrupts during the last transfer (about 10 for a 6 byte read on F4, 8 or 9 on F7) | | `debug[1]` | error interrupts since boot | | `debug[2]` | duration of the last transfer in µs (about 200 for 6 bytes at 400 kHz) | -| `debug[3]` | longest single interrupt handler run in µs (F4 only) | +| `debug[3]` | longest single interrupt handler run in µs (F4 and F7) | | `debug[4]` | longest wait for a START / STOP bit release in µs (F4 only) | | `debug[5]` | I2C error counter, also shown by `status` | -| `debug[6]` | interrupt enables found at transfer start (F4 only, 1024 is normal) | +| `debug[6]` | F4: interrupt enables found at transfer start (1024 is normal). F7: ISR flags at the last error (16 NACK, 256 bus error, 512 arbitration lost) | | `debug[7]` | time spent in the start call in µs, should be a few µs | ## Known limitations diff --git a/src/main/drivers/bus_i2c_stm32f7xx.c b/src/main/drivers/bus_i2c_stm32f7xx.c new file mode 100644 index 00000000000..847e39ab370 --- /dev/null +++ b/src/main/drivers/bus_i2c_stm32f7xx.c @@ -0,0 +1,664 @@ +/* + * This file is part of INAV. + * + * INAV is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * INAV is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with INAV. If not, see . + * + * Interrupt driven I2C master for STM32F7 on the peripheral registers. The + * ST HAL I2C module costs the F722 targets several KB of flash they do not + * have, and the F7 I2C peripheral (RM0385 / RM0431, chapter "I2C") is simple + * enough to drive directly: one CR2 write starts a transfer of up to 255 + * bytes and the hardware sends the STOP itself, at the end (AUTOEND) or + * after a NACK. + * + * Same structure as bus_i2c_stm32f40x.c: a transfer is started from task + * context and completed by the I2Cx_EV and I2Cx_ER interrupts. i2cRead() / + * i2cWrite() block until the transfer is done, i2cReadStart() / + * i2cWriteStart() return immediately and the caller polls i2cBusy(). A + * blocking call issued while a non-blocking transfer is in progress waits + * for it to finish first, so the two can share a bus. + * + * The handler never waits on the bus or reinitialises the peripheral. A + * transfer that stops making progress (a slave stretching SCL, a START that + * cannot go out because a slave holds SDA) is caught by the progress timeout + * in i2cBusy() and the blocking waits, from task context. A bus error or an + * arbitration loss flags the bus for a reset that the next i2cBusy() or + * start call performs from task context. + */ + +#include +#include +#include + +#include + +#include "build/debug.h" + +#include "common/utils.h" +#include "common/maths.h" + +#include "drivers/io.h" +#include "drivers/time.h" + +#include "drivers/bus_i2c.h" +#include "drivers/nvic.h" +#include "io_impl.h" +#include "rcc.h" + +#if !defined(SOFT_I2C) && defined(USE_I2C) + +#if defined(USE_I2C_PULLUP) +#define IOCFG_I2C IO_CONFIG(GPIO_MODE_AF_OD, GPIO_SPEED_FREQ_VERY_HIGH, GPIO_PULLUP) +#else +#define IOCFG_I2C IOCFG_AF_OD +#endif + +#ifndef I2C1_SCL +#define I2C1_SCL PB6 +#endif +#ifndef I2C1_SDA +#define I2C1_SDA PB7 +#endif + +#ifndef I2C2_SCL +#define I2C2_SCL PB10 +#endif +#ifndef I2C2_SDA +#define I2C2_SDA PB11 +#endif + +#ifndef I2C3_SCL +#define I2C3_SCL PA8 +#endif +#ifndef I2C3_SDA +#define I2C3_SDA PB4 +#endif + +#if defined(USE_I2C_DEVICE_4) +#ifndef I2C4_SCL +#define I2C4_SCL PD12 +#endif +#ifndef I2C4_SDA +#define I2C4_SDA PD13 +#endif +#endif + +// Interrupts the handler needs during a transfer, enabled in CR1 per transfer. ERRIE covers BERR, ARLO and OVR +#define I2C_IRQ_ENABLES (I2C_CR1_TXIE | I2C_CR1_RXIE | I2C_CR1_TCIE | I2C_CR1_STOPIE | I2C_CR1_NACKIE | I2C_CR1_ERRIE) +#define I2C_ISR_BUS_ERRORS (I2C_ISR_BERR | I2C_ISR_ARLO | I2C_ISR_OVR) + +typedef struct i2cBusState_s { + bool initialized; + volatile bool busy; // transfer in progress + volatile bool error; // last transfer failed (NACK, bus error, arbitration lost, overrun or timeout) + volatile bool needsReset; // the handler gave up on a transfer, i2cServiceReset() has to reinitialise the peripheral + uint16_t lastProgress; // byte index and register phase at the previous look, a change means the transfer moves + uint32_t stuckUs; // time looked at without progress, a long gap between looks counts as I2C_STUCK_LOOK_GAP_US + timeUs_t lookUs; // time of the previous look + + // Active transfer + uint8_t addr; // 7-bit address + uint8_t reg; + uint8_t bytes; // data bytes, the register byte not included + uint8_t * readBuf; + const uint8_t * writeBuf; + uint8_t txByte; // storage for the data of a non-blocking single byte write + + // Handler state + volatile bool regSent; // register byte phase done (or none, for raw access) + volatile uint8_t index; // next data byte +} i2cBusState_t; + +static volatile uint16_t i2cErrorCount = 0; + +// Transfer statistics shown with debug_mode = I2C, shared by all buses +typedef struct { + timeUs_t startUs; // when the current transfer was started + uint16_t eventIrqs; // interrupts during the current / last transfer + uint16_t errorIrqs; // interrupts that found an error flag, since boot + uint16_t lastTransferUs; // start to completion of the last transfer + uint16_t maxIrqUs; // longest single handler run + uint16_t lastErrorIsr; // ISR flags found by the handler at the last error: NACKF 16, BERR 256, ARLO 512, OVR 1024 + uint16_t startCallUs; // time spent in the last i2cStartTransfer() call +} i2cDebugStats_t; + +static i2cDebugStats_t i2cStats; + +static void i2cDebugPublish(void) +{ + DEBUG_SET(DEBUG_I2C, 0, i2cStats.eventIrqs); + DEBUG_SET(DEBUG_I2C, 1, i2cStats.errorIrqs); + DEBUG_SET(DEBUG_I2C, 2, i2cStats.lastTransferUs); + DEBUG_SET(DEBUG_I2C, 3, i2cStats.maxIrqUs); + DEBUG_SET(DEBUG_I2C, 5, i2cErrorCount); + DEBUG_SET(DEBUG_I2C, 6, i2cStats.lastErrorIsr); + DEBUG_SET(DEBUG_I2C, 7, i2cStats.startCallUs); +} + +static i2cDevice_t i2cHardwareMap[] = { + { .dev = I2C1, .scl = IO_TAG(I2C1_SCL), .sda = IO_TAG(I2C1_SDA), .rcc = RCC_APB1(I2C1), .speed = I2C_SPEED_400KHZ, .ev_irq = I2C1_EV_IRQn, .er_irq = I2C1_ER_IRQn, .af = GPIO_AF4_I2C1 }, + { .dev = I2C2, .scl = IO_TAG(I2C2_SCL), .sda = IO_TAG(I2C2_SDA), .rcc = RCC_APB1(I2C2), .speed = I2C_SPEED_400KHZ, .ev_irq = I2C2_EV_IRQn, .er_irq = I2C2_ER_IRQn, .af = GPIO_AF4_I2C2 }, + { .dev = I2C3, .scl = IO_TAG(I2C3_SCL), .sda = IO_TAG(I2C3_SDA), .rcc = RCC_APB1(I2C3), .speed = I2C_SPEED_400KHZ, .ev_irq = I2C3_EV_IRQn, .er_irq = I2C3_ER_IRQn, .af = GPIO_AF4_I2C3 }, +#if defined(USE_I2C_DEVICE_4) + { .dev = I2C4, .scl = IO_TAG(I2C4_SCL), .sda = IO_TAG(I2C4_SDA), .rcc = RCC_APB1(I2C4), .speed = I2C_SPEED_400KHZ, .ev_irq = I2C4_EV_IRQn, .er_irq = I2C4_ER_IRQn, .af = GPIO_AF4_I2C4 }, +#endif +}; + +static i2cBusState_t busState[ARRAYLEN(i2cHardwareMap)]; + +// Per address outcome of the last transfer. Kept outside busState so that the reset in i2cInit() does not wipe the +// results of the other devices on the bus +static i2cAddrResults_t busAddrResults[ARRAYLEN(i2cHardwareMap)]; + +static void i2cUnstick(IO_t scl, IO_t sda); +static void i2cIrqHandler(I2CDevice device); + +static bool i2cIsValidDevice(I2CDevice device) +{ + return device != I2CINVALID && (unsigned)device < ARRAYLEN(i2cHardwareMap); +} + +// The event and the error vector share one handler: all flags are in ISR and one pass handles whatever is set +void I2C1_ER_IRQHandler(void) +{ + i2cIrqHandler(I2CDEV_1); +} + +void I2C1_EV_IRQHandler(void) +{ + i2cIrqHandler(I2CDEV_1); +} + +void I2C2_ER_IRQHandler(void) +{ + i2cIrqHandler(I2CDEV_2); +} + +void I2C2_EV_IRQHandler(void) +{ + i2cIrqHandler(I2CDEV_2); +} + +void I2C3_ER_IRQHandler(void) +{ + i2cIrqHandler(I2CDEV_3); +} + +void I2C3_EV_IRQHandler(void) +{ + i2cIrqHandler(I2CDEV_3); +} + +#if defined(USE_I2C_DEVICE_4) +void I2C4_ER_IRQHandler(void) +{ + i2cIrqHandler(I2CDEV_4); +} + +void I2C4_EV_IRQHandler(void) +{ + i2cIrqHandler(I2CDEV_4); +} +#endif + +// Reinitialise the peripheral and clock the bus free. Always returns false so it can be used as the failure result. +static bool i2cHandleHardwareFailure(I2CDevice device) +{ + i2cErrorCount++; + i2cInit(device); + return false; +} + +// Reinitialise the peripheral after the handler gave up on a transfer. Runs from task context before the bus is looked +// at or used again, so the unstick never holds off the higher priority interrupts +static void i2cServiceReset(I2CDevice device) +{ + if (busState[device].needsReset) { + i2cInit(device); // the failure was counted by the handler, i2cInit() clears needsReset with the rest of the state + } +} + +void i2cSetSpeed(uint8_t speed) +{ + for (unsigned int i = 0; i < ARRAYLEN(i2cHardwareMap); i++) { + i2cHardwareMap[i].speed = speed; + } +} + +// PRESC, SCLDEL, SDADEL, SCLH and SCLL for TIMINGR (RM0385 "I2C master mode" timing): the computation of bus_i2c_hal.c +// with the analog filter on, no digital filter and the rise and fall times estimated at 100 ns +static uint32_t i2cClockTIMINGR(uint32_t pclkFreq, int i2cFreqKhz) +{ + const bool fastModePlus = i2cFreqKhz > 400; + const float trMax = fastModePlus ? 120 : 300; // ns, rise / fall time maximum of the I2C specification + const float tsuDatMin = fastModePlus ? 50 : 100; // ns, SDA setup time minimum + const float tI2cclk = 1000000000.0f / pclkFreq; // ns + const float tScl = 1000000.0f / i2cFreqKhz; // ns + // Rise or fall time 100 ns, analog filter delay 70 ns, three I2CCLK cycles of synchronisation on each SCL edge + const float tSync = 100 + 70 + 3 * tI2cclk; + + for (int presc = 1; presc < 15; presc++) { + const float tPresc = (presc + 1) * tI2cclk; + const uint32_t scldel = (trMax + tsuDatMin) / tPresc - 1; + const uint32_t sdadel = (trMax - 50 - 3 * tI2cclk) / tPresc; // fall time - analog filter minimum - 3 I2CCLK + const float sclhl = (tScl - 2 * tSync) / tPresc - 1; + const uint32_t sclh = sclhl / 4.75f; // STM32CubeMX seems to use a value like this + const uint32_t scll = (uint32_t)(sclhl + 0.5f) - sclh; + + // All fields have to fit, otherwise increase the prescaler and try again + if (scldel < 16 && sdadel < 16 && sclh - 1 < 256 && scll - 1 < 256) { + return (presc << 28) | (scldel << 20) | (sdadel << 16) | ((sclh - 1) << 8) | (scll - 1); + } + } + return 0; // not reached for the supported clocks +} + +void i2cInit(I2CDevice device) +{ + if (!i2cIsValidDevice(device)) { + return; + } + + i2cDevice_t *i2c = &(i2cHardwareMap[device]); + i2cBusState_t *state = &busState[device]; + I2C_TypeDef *I2Cx = i2c->dev; + + RCC_ClockCmd(i2c->rcc, ENABLE); + + // No handler run in the middle of this: one could put PE back while the lines are clocked by hand below + HAL_NVIC_DisableIRQ(i2c->er_irq); + HAL_NVIC_DisableIRQ(i2c->ev_irq); + + // PE=0 is the software reset (RM0385 "Software reset"): it drops the transfer in flight, clears the flags and BUSY + // and takes the peripheral off the lines while the unstick clocks them. It has to stay low for at least three APB + // clocks, the pin setup below takes far longer. The interrupt enables go with it + I2Cx->CR1 = 0; + HAL_NVIC_ClearPendingIRQ(i2c->er_irq); + HAL_NVIC_ClearPendingIRQ(i2c->ev_irq); + + IO_t scl = IOGetByTag(i2c->scl); + IO_t sda = IOGetByTag(i2c->sda); + + IOInit(scl, OWNER_I2C, RESOURCE_I2C_SCL, RESOURCE_INDEX(device)); + IOInit(sda, OWNER_I2C, RESOURCE_I2C_SDA, RESOURCE_INDEX(device)); + + // Release a slave that may still be driving SDA after a reset in the middle of a transfer + i2cUnstick(scl, sda); + + IOConfigGPIOAF(scl, IOCFG_I2C, i2c->af); + IOConfigGPIOAF(sda, IOCFG_I2C, i2c->af); + + int speedKhz; + switch (i2c->speed) { + case I2C_SPEED_400KHZ: + default: + speedKhz = 400; + break; + + case I2C_SPEED_800KHZ: + speedKhz = 800; + break; + + case I2C_SPEED_100KHZ: + speedKhz = 100; + break; + + case I2C_SPEED_200KHZ: + speedKhz = 200; + break; + } + + // I2C1-4 are clocked from PCLK1 (target/system_stm32f7xx.c). The analog filter is on and the digital one off, the + // CR1 reset values TIMINGR assumes. OAR1 and OAR2 keep their reset value: no own address, the peripheral never + // answers as a slave + I2Cx->TIMINGR = i2cClockTIMINGR(HAL_RCC_GetPCLK1Freq(), speedKhz); + I2Cx->CR1 = I2C_CR1_PE; + + // The interrupts are enabled in the peripheral per transfer, the NVIC side stays on + HAL_NVIC_SetPriority(i2c->er_irq, NVIC_PRIO_I2C_ER, 0); + HAL_NVIC_EnableIRQ(i2c->er_irq); + HAL_NVIC_SetPriority(i2c->ev_irq, NVIC_PRIO_I2C_EV, 0); + HAL_NVIC_EnableIRQ(i2c->ev_irq); + + memset(state, 0, sizeof(*state)); + state->initialized = true; +} + +uint16_t i2cGetErrorCounter(void) +{ + return i2cErrorCount; +} + +// A transfer is stuck when it made no progress for I2C_TIMEOUT while being looked at. A gap between two looks longer +// than I2C_STUCK_LOOK_GAP_US counts as that much only: a main loop that was busy elsewhere for a while (a settings save) +// does not make the transfer stuck, the interrupts carry it on however seldom somebody looks +#define I2C_STUCK_LOOK_GAP_US 1000 + +static uint16_t i2cTransferProgress(const i2cBusState_t *state) +{ + // The data byte index and the register phase are all the handler moves between START and STOP + return state->index | (state->regSent ? 0x100 : 0); +} + +static bool i2cTransferStuck(i2cBusState_t *state) +{ + const timeUs_t now = micros(); + const uint16_t progress = i2cTransferProgress(state); + + if (progress != state->lastProgress) { + state->lastProgress = progress; + state->stuckUs = 0; + } + else { + state->stuckUs += MIN((uint32_t)cmpTimeUs(now, state->lookUs), (uint32_t)I2C_STUCK_LOOK_GAP_US); + } + state->lookUs = now; + + return state->stuckUs >= I2C_TIMEOUT; +} + +// Set up and start a transfer. Returns false if the bus is busy or the transfer cannot be done. +static bool i2cStartTransfer(I2CDevice device, uint8_t addr, uint8_t reg, bool allowRawAccess, bool reading, uint8_t len, uint8_t *readBuf, const uint8_t *writeBuf) +{ + if (!i2cIsValidDevice(device)) { + return false; + } + + i2cBusState_t *state = &busState[device]; + I2C_TypeDef *I2Cx = i2cHardwareMap[device].dev; + + i2cServiceReset(device); + + if (!state->initialized || state->busy) { + return false; + } + + const bool rawAccess = (reg == 0xFF) && allowRawAccess; + + if (len == 0 && (reading || rawAccess)) { + return false; // nothing to receive or send, only the register byte alone is a transfer of no data + } + if (len == 255 && !reading && !rawAccess) { + return false; // the register byte would make 256, one more than NBYTES holds + } + + const timeUs_t callStartUs = micros(); + i2cStats.eventIrqs = 0; + i2cStats.startUs = callStartUs; + + state->addr = addr; + state->reg = reg; + state->bytes = len; + state->readBuf = readBuf; + state->writeBuf = writeBuf; + state->regSent = rawAccess; + state->index = 0; + state->lastProgress = i2cTransferProgress(state); + state->stuckUs = 0; + state->lookUs = callStartUs; + state->error = false; + state->busy = true; + + // One CR2 write starts the transfer: address, direction, length and the STOP at its end (AUTOEND). A register read + // first sends the register byte alone without AUTOEND, the handler issues the repeated START at TC. The START goes + // out once the bus is free, a bus that never frees shows up as a stuck transfer + uint32_t cr2 = ((uint32_t)addr << 1) | I2C_CR2_START; + if (reading && !rawAccess) { + cr2 |= 1U << I2C_CR2_NBYTES_Pos; + } + else { + cr2 |= ((uint32_t)(rawAccess ? len : len + 1) << I2C_CR2_NBYTES_Pos) | I2C_CR2_AUTOEND | (reading ? I2C_CR2_RD_WRN : 0); + } + + __DMB(); // the handler reads the state above, it is stored before the start goes out + I2Cx->CR1 |= I2C_IRQ_ENABLES; + I2Cx->CR2 = cr2; + + i2cStats.startCallUs = micros() - callStartUs; + i2cDebugPublish(); + + return true; +} + +// Reset the peripheral after a transfer that did not complete and record the failure for the transfer's owner +static void i2cRecoverStuckTransfer(I2CDevice device) +{ + const uint8_t stuckAddr = busState[device].addr; // i2cInit() clears the state + + i2cHandleHardwareFailure(device); + busState[device].error = true; + i2cAddrResultSet(&busAddrResults[device], stuckAddr, true); +} + +// Block until the bus is idle. Returns false if the transfer in progress had to be aborted. +static bool i2cWaitForIdle(I2CDevice device) +{ + i2cBusState_t *state = &busState[device]; + + while (state->busy) { + if (i2cTransferStuck(state)) { + i2cRecoverStuckTransfer(device); + return false; + } + } + + return true; +} + +bool i2cBusy(I2CDevice device, uint8_t addr_, bool *error) +{ + if (!i2cIsValidDevice(device)) { + if (error) { + *error = true; + } + return false; + } + + i2cBusState_t *state = &busState[device]; + + i2cServiceReset(device); + + if (state->busy && i2cTransferStuck(state)) { + // No progress within the timeout, the transfer is stuck - reset the peripheral + i2cRecoverStuckTransfer(device); + } + + // Only the owner of the transfer on the bus is pending, everybody else gets the outcome of their own last transfer + const bool pending = state->busy && state->addr == addr_; + + if (error) { + *error = !pending && i2cAddrResultFailed(&busAddrResults[device], addr_); + } + + i2cDebugPublish(); + + return pending; +} + +bool i2cReadStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t* buf, bool allowRawAccess) +{ + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, true, len, buf, NULL); +} + +bool i2cWriteBufferStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) +{ + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, len_, NULL, data); +} + +bool i2cWriteStart(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t data, bool allowRawAccess) +{ + if (!i2cIsValidDevice(device) || busState[device].busy) { + return false; // don't touch txByte while it may still be going out + } + + busState[device].txByte = data; + return i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, 1, NULL, &busState[device].txByte); +} + +bool i2cWriteBuffer(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len_, const uint8_t *data, bool allowRawAccess) +{ + if (!i2cIsValidDevice(device) || !busState[device].initialized) { + return false; + } + + // Let a non-blocking transfer of another device finish first + if (!i2cWaitForIdle(device)) { + return false; + } + + if (!i2cStartTransfer(device, addr_, reg_, allowRawAccess, false, len_, NULL, data)) { + return false; + } + + return i2cWaitForIdle(device) && !busState[device].error; +} + +bool i2cWrite(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t data, bool allowRawAccess) +{ + return i2cWriteBuffer(device, addr_, reg_, 1, &data, allowRawAccess); +} + +bool i2cRead(I2CDevice device, uint8_t addr_, uint8_t reg_, uint8_t len, uint8_t* buf, bool allowRawAccess) +{ + if (!i2cIsValidDevice(device) || !busState[device].initialized) { + return false; + } + + // Let a non-blocking transfer of another device finish first + if (!i2cWaitForIdle(device)) { + return false; + } + + if (!i2cStartTransfer(device, addr_, reg_, allowRawAccess, true, len, buf, NULL)) { + return false; + } + + return i2cWaitForIdle(device) && !busState[device].error; +} + +// The transfer is over and the bus idle: hand the outcome to the owner and silence the peripheral until the next start +static void i2cTransferDone(I2CDevice device, bool error) +{ + i2cBusState_t *state = &busState[device]; + + i2cHardwareMap[device].dev->CR1 &= ~I2C_IRQ_ENABLES; + i2cStats.lastTransferUs = microsISR() - i2cStats.startUs; + if (error) { + i2cErrorCount++; // keep the "I2C Errors" count of status / MSP meaningful for non-blocking transfers + } + state->error = error; + i2cAddrResultSet(&busAddrResults[device], state->addr, error); + state->busy = false; +} + +static void i2cIrqHandlerBody(I2CDevice device) +{ + I2C_TypeDef *I2Cx = i2cHardwareMap[device].dev; + i2cBusState_t *state = &busState[device]; + const uint32_t isr = I2Cx->ISR; + + if (isr & I2C_ISR_BUS_ERRORS) { + // A misplaced START or STOP, SDA taken away from under the master (ARLO) or an overrun leaves the peripheral + // anywhere in the transfer: give up on it and let i2cServiceReset() reinitialise the peripheral and clock the + // bus free from task context, the unstick takes too long for here + I2Cx->ICR = I2C_ICR_BERRCF | I2C_ICR_ARLOCF | I2C_ICR_OVRCF | I2C_ICR_NACKCF | I2C_ICR_STOPCF; + i2cStats.errorIrqs++; + i2cStats.lastErrorIsr = isr; + state->needsReset = true; + i2cTransferDone(device, true); + return; + } + + if (isr & I2C_ISR_NACKF) { + // The slave did not answer. The hardware sends the STOP itself, the transfer ends at STOPF below, usually in + // this same run + I2Cx->ICR = I2C_ICR_NACKCF; + i2cStats.errorIrqs++; + i2cStats.lastErrorIsr = isr; + state->error = true; + } + + if (isr & I2C_ISR_TXIS) { // the hardware wants the next byte to send + if (state->regSent) { + I2Cx->TXDR = state->writeBuf[state->index++]; + } + else { + I2Cx->TXDR = state->reg; + state->regSent = true; + } + } + else if (isr & I2C_ISR_RXNE) { // a byte came in + state->readBuf[state->index++] = (uint8_t)I2Cx->RXDR; + } + else if (isr & I2C_ISR_TC) { // the register byte of a read is out: repeated START, read the data + I2Cx->CR2 = ((uint32_t)state->addr << 1) | I2C_CR2_RD_WRN | ((uint32_t)state->bytes << I2C_CR2_NBYTES_Pos) | I2C_CR2_AUTOEND | I2C_CR2_START; + } + + if (isr & I2C_ISR_STOPF) { // the STOP is out, after the last byte or after a NACK + I2Cx->ICR = I2C_ICR_STOPCF; + i2cTransferDone(device, state->error); + } +} + +static void i2cIrqHandler(I2CDevice device) +{ + const timeUs_t entryUs = microsISR(); + + i2cStats.eventIrqs++; + i2cIrqHandlerBody(device); + + const timeUs_t spentUs = microsISR() - entryUs; + if (spentUs > i2cStats.maxIrqUs) { + i2cStats.maxIrqUs = spentUs; + } +} + +static void i2cUnstick(IO_t scl, IO_t sda) +{ + int i; + + IOHi(scl); + IOHi(sda); + + IOConfigGPIO(scl, IOCFG_OUT_OD); + IOConfigGPIO(sda, IOCFG_OUT_OD); + + // Analog Devices AN-686 + // We need 9 clock pulses + STOP condition + for (i = 0; i < 9; i++) { + // Wait for any clock stretching to finish + int timeout = 100; + while (!IORead(scl) && timeout) { + delayMicroseconds(5); + timeout--; + } + + // Pull low + IOLo(scl); // Set bus low + delayMicroseconds(5); + IOHi(scl); // Set bus high + delayMicroseconds(5); + } + + // Generate a stop condition in case there was none + IOLo(scl); + delayMicroseconds(5); + IOLo(sda); + delayMicroseconds(5); + + IOHi(scl); // Set bus scl high + delayMicroseconds(5); + IOHi(sda); // Set bus sda high +} + +#endif diff --git a/src/main/target/stm32f7xx_hal_conf.h b/src/main/target/stm32f7xx_hal_conf.h index 291463023c0..abc307442da 100644 --- a/src/main/target/stm32f7xx_hal_conf.h +++ b/src/main/target/stm32f7xx_hal_conf.h @@ -94,7 +94,7 @@ #define HAL_RCC_MODULE_ENABLED #define HAL_FLASH_MODULE_ENABLED #define HAL_PWR_MODULE_ENABLED -#define HAL_I2C_MODULE_ENABLED +/* #define HAL_I2C_MODULE_ENABLED */ #define HAL_CORTEX_MODULE_ENABLED /* ########################## HSE/HSI Values adaptation ##################### */ From 64091b4ee6c4a32de2cbc9cc9941010c2c9af1be Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 17 Nov 2026 15:43:06 +0100 Subject: [PATCH 11/14] =?UTF-8?q?I2C=20CORE=20-=20Delayed=20interrupts=20t?= =?UTF-8?q?runcate=20I=C2=B2C=20writes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/drivers/bus_i2c_stm32f40x.c | 54 +++++++++++++++++----------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/src/main/drivers/bus_i2c_stm32f40x.c b/src/main/drivers/bus_i2c_stm32f40x.c index e5c40b89723..3e5c65d12cf 100644 --- a/src/main/drivers/bus_i2c_stm32f40x.c +++ b/src/main/drivers/bus_i2c_stm32f40x.c @@ -555,6 +555,31 @@ static void i2cErrorHandler(I2CDevice device) state->busy = false; } +// EV8 / EV8_1: queue the subaddress or the next payload byte +static void i2cSendNextByte(I2C_TypeDef *I2Cx, i2cBusState_t *state) +{ + if (state->index != -1) { // we dont have a subaddress to send + if (state->index < state->bytes) { + I2Cx->DR = state->writeBuf[state->index++]; + if (state->bytes == state->index) { // we have sent all the data + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable TXE to allow the buffer to flush + } + } + else { // raw write without data - nothing to send, end the transfer + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); + I2C_GenerateSTOP(I2Cx, ENABLE); + state->index = state->bytes + 1; // to show that the job is complete + } + } + else { + state->index++; + I2Cx->DR = state->reg; // send the subaddress + if (state->reading || !(state->bytes)) { // if receiving or sending 0 bytes, flush now + I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable TXE to allow the buffer to flush + } + } +} + static void i2cEventHandlerBody(I2CDevice device) { I2C_TypeDef *I2Cx = i2cHardwareMap[device].dev; @@ -623,7 +648,13 @@ static void i2cEventHandlerBody(I2CDevice device) } } else { // EV8_2, which may be due to a subaddress sent or a write completion - if (state->subaddressSent || !state->reading) { + if (!state->reading && state->index < state->bytes) { + // A late interrupt: the previous byte went out before the next one was queued, so BTF is set together + // with TXE and wins the dispatch. The write is not finished - a STOP here would drop the rest of it + // and still report success. Writing DR clears BTF + i2cSendNextByte(I2Cx, state); + } + else if (state->subaddressSent || !state->reading) { I2C_GenerateSTOP(I2Cx, ENABLE); // program the Stop state->index++; // to show that the job is complete } @@ -648,26 +679,7 @@ static void i2cEventHandlerBody(I2CDevice device) } } else if (SReg_1 & I2C_SR1_TXE) { // Byte transmitted EV8 / EV8_1 - if (state->index != -1) { // we dont have a subaddress to send - if (state->index < state->bytes) { - I2Cx->DR = state->writeBuf[state->index++]; - if (state->bytes == state->index) { // we have sent all the data - I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable TXE to allow the buffer to flush - } - } - else { // raw write without data - nothing to send, end the transfer - I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); - I2C_GenerateSTOP(I2Cx, ENABLE); - state->index = state->bytes + 1; // to show that the job is complete - } - } - else { - state->index++; - I2Cx->DR = state->reg; // send the subaddress - if (state->reading || !(state->bytes)) { // if receiving or sending 0 bytes, flush now - I2C_ITConfig(I2Cx, I2C_IT_BUF, DISABLE); // disable TXE to allow the buffer to flush - } - } + i2cSendNextByte(I2Cx, state); } if (state->index == state->bytes + 1) { // we have completed the current job From 4b5ea370488066644f70a655a60e3704cbf4ef53 Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 17 Nov 2026 16:07:29 +0100 Subject: [PATCH 12/14] =?UTF-8?q?I2C=20CORE=20-=20Software=20I=C2=B2C=20re?= =?UTF-8?q?ports=20some=20NACKs=20as=20success?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/drivers/bus_i2c_soft.c | 64 +++++++++++++++------------------ 1 file changed, 28 insertions(+), 36 deletions(-) diff --git a/src/main/drivers/bus_i2c_soft.c b/src/main/drivers/bus_i2c_soft.c index ea209dd35b3..e910fc52400 100644 --- a/src/main/drivers/bus_i2c_soft.c +++ b/src/main/drivers/bus_i2c_soft.c @@ -201,6 +201,18 @@ void i2cInit(I2CDevice device) IOConfigGPIOAF(sda, IOCFG_OUT_OD, 0); } +// Send a byte and take the slave's answer. A NACK ends the transfer: the bus is released and the error counted +static bool I2C_SendByteAcked(uint8_t byte) +{ + I2C_SendByte(byte); + if (!I2C_WaitAck()) { + I2C_Stop(); + i2cErrorCount++; + return false; + } + return true; +} + bool i2cWriteBuffer(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, const uint8_t * data, bool allowRawAccess) { UNUSED(device); @@ -210,20 +222,14 @@ bool i2cWriteBuffer(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, co i2cErrorCount++; return false; } - I2C_SendByte(addr << 1 | I2C_Direction_Transmitter); - if (!I2C_WaitAck()) { - I2C_Stop(); + if (!I2C_SendByteAcked(addr << 1 | I2C_Direction_Transmitter)) { return false; } - if (!allowRawAccess || reg != 0xFF) { - I2C_SendByte(reg); - I2C_WaitAck(); + if ((!allowRawAccess || reg != 0xFF) && !I2C_SendByteAcked(reg)) { + return false; } for (i = 0; i < len; i++) { - I2C_SendByte(data[i]); - if (!I2C_WaitAck()) { - I2C_Stop(); - i2cErrorCount++; + if (!I2C_SendByteAcked(data[i])) { return false; } } @@ -233,25 +239,7 @@ bool i2cWriteBuffer(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, co bool i2cWrite(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t data, bool allowRawAccess) { - UNUSED(device); - - if (!I2C_Start()) { - return false; - } - I2C_SendByte(addr << 1 | I2C_Direction_Transmitter); - if (!I2C_WaitAck()) { - I2C_Stop(); - i2cErrorCount++; - return false; - } - if (!allowRawAccess || reg != 0xFF) { - I2C_SendByte(reg); - I2C_WaitAck(); - } - I2C_SendByte(data); - I2C_WaitAck(); - I2C_Stop(); - return true; + return i2cWriteBuffer(device, addr, reg, 1, &data, allowRawAccess); } bool i2cRead(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, uint8_t *buf, bool allowRawAccess) @@ -259,23 +247,27 @@ bool i2cRead(I2CDevice device, uint8_t addr, uint8_t reg, uint8_t len, uint8_t * UNUSED(device); if (!I2C_Start()) { + i2cErrorCount++; return false; } if (!allowRawAccess || reg != 0xFF) { - I2C_SendByte(addr << 1 | I2C_Direction_Transmitter); - if (!I2C_WaitAck()) { + if (!I2C_SendByteAcked(addr << 1 | I2C_Direction_Transmitter)) { + return false; + } + if (!I2C_SendByteAcked(reg)) { + return false; + } + if (!I2C_Start()) { // repeated start I2C_Stop(); i2cErrorCount++; return false; } - I2C_SendByte(reg); - I2C_WaitAck(); - I2C_Start(); } - I2C_SendByte(addr << 1 | I2C_Direction_Receiver); - I2C_WaitAck(); + if (!I2C_SendByteAcked(addr << 1 | I2C_Direction_Receiver)) { + return false; + } while (len) { *buf = I2C_ReceiveByte(); if (len == 1) { From b071da2e500374f21e06351109db9a0c9f09ca0e Mon Sep 17 00:00:00 2001 From: Error414 Date: Tue, 17 Nov 2026 16:15:22 +0100 Subject: [PATCH 13/14] I2C CORE - MPU9250 compass drops from 40 Hz to 10 Hz --- src/main/fc/fc_tasks.c | 4 ---- src/main/sensors/compass.h | 8 +++++++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/fc/fc_tasks.c b/src/main/fc/fc_tasks.c index b8716b076ee..f63731f9690 100755 --- a/src/main/fc/fc_tasks.c +++ b/src/main/fc/fc_tasks.c @@ -418,10 +418,6 @@ void fcTasksInit(void) #endif #ifdef USE_MAG setTaskEnabled(TASK_COMPASS, sensors(SENSOR_MAG)); -#if defined(USE_MAG_MPU9250) - // fixme temporary solution for AK6983 via slave I2C on MPU9250 - rescheduleTask(TASK_COMPASS, TASK_PERIOD_HZ(40)); -#endif #endif #ifdef USE_BARO setTaskEnabled(TASK_BARO, sensors(SENSOR_BARO)); diff --git a/src/main/sensors/compass.h b/src/main/sensors/compass.h index 0ac33964048..6de9336600b 100644 --- a/src/main/sensors/compass.h +++ b/src/main/sensors/compass.h @@ -77,8 +77,14 @@ typedef struct compassConfig_s { PG_DECLARE(compassConfig_t, compassConfig); -// Regular sample rate of the compass task +// Regular sample rate of the compass task. compassUpdate() returns it after every sample, so it is the only place +// the rate can be set +#if defined(USE_MAG_MPU9250) +// fixme temporary solution for AK6983 via slave I2C on MPU9250 +#define COMPASS_UPDATE_RATE_HZ 40 +#else #define COMPASS_UPDATE_RATE_HZ 10 +#endif #define COMPASS_UPDATE_PERIOD_US (1000000 / COMPASS_UPDATE_RATE_HZ) bool compassDetect(magDev_t *dev, magSensor_e magHardwareToUse); From c992957588c83c8beb45d964db642c2cb727d2a9 Mon Sep 17 00:00:00 2001 From: breadoven <56191411+breadoven@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:09:36 +0000 Subject: [PATCH 14/14] Update navigation.c --- src/main/navigation/navigation.c | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/main/navigation/navigation.c b/src/main/navigation/navigation.c index 169b07ff677..50028cc7eae 100644 --- a/src/main/navigation/navigation.c +++ b/src/main/navigation/navigation.c @@ -396,17 +396,9 @@ void calculateFarAwayTarget(fpVector3_t * farAwayPos, int32_t bearing, int32_t d bool isWaypointReached(const fpVector3_t *waypointPos, const int32_t *waypointBearing); bool isWaypointAltitudeReached(void); static void mapWaypointToLocalPosition(fpVector3_t * localPos, const navWaypoint_t * waypoint, geoAltitudeConversionMode_e altConv); -static navigationFSMEvent_t nextForNonGeoStates(void); -static bool isWaypointMissionValid(void); #ifdef USE_AUTO_TRANSITION static void clearMissionVTOLTransitionState(void); -static navMissionVtolTransitionDisposition_e prepareMissionVTOLTransition(const navWaypoint_t *waypoint); -static void updateMissionTransitionGuidance(void); static bool isTransitionRetryToFixedWingRequest(const mixerProfileATRequest_e request); -static bool hasAirspeedSensorForTransitionRetry(void); -static bool canRetryTransitionAfterAirspeedTimeout(const mixerProfileATRequest_e request); -static void beginMissionTransitionRetryScan(const mixerProfileATRequest_e request); -static navMixerATRetryScanResult_e updateMissionTransitionRetryScan(void); #endif void missionPlannerSetWaypoint(void); @@ -2370,7 +2362,7 @@ static bool missionVTOLTransitionPointReady(const bool transitionToFixedWing, co bool hasUsableTransitionAirspeed(float *airspeedCmS) { #ifdef USE_PITOT - if (pitotIsValidForAirspeed(false)) { + if (pitotIsValidForAirspeed(true)) { const float measuredAirspeedCmS = getAirspeedEstimate(); if (isnan(measuredAirspeedCmS) || isinf(measuredAirspeedCmS)) { // why ??