Skip to content

I2C asyn calling -- CORE - #12133

Open
error414 wants to merge 23 commits into
iNavFlight:next-10.1from
error414:error414/feature/ic_async/core
Open

error414 wants to merge 23 commits into
iNavFlight:next-10.1from
error414:error414/feature/ic_async/core

Conversation

@error414

@error414 error414 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

this PR is first step for #12100 rewiting I2C from sync calling to async calling.

Why:
Sync calling takes much time and CPU does not do nothing, just waiting to response. For 16bit register 200khz i2c it takes 200us. For OLED display CPU can wait up to 10ms!!!

How:
In this PR is core of async functions for all CPUs and rewritten drivers

  • bmp280
  • dps310
  • spll06

To be possible to test all scenarios, like two devices on same bus, Two devide on same bus, one disconect, etc......

Need to be tested

Platforms:

  • F7/H7 (hal)
  • F4
  • AT32
  • RPI (no target so far)
  • HITL
  • SITL (i2c is not compiled)

Device:

  • bmp280
  • dps310
  • spll06

Related PRs:

Raphael Hunziker and others added 7 commits September 10, 2026 20:14
SBUS servo output is resolved with findSerialPortConfig(), which returns
the first port that carries FUNCTION_SERVO_SERIAL. Assigning the function
to a second port was accepted and reported back by the serial command,
but that port was never opened.

Reject such an assignment in the CLI instead of ignoring it silently.

Fixes iNavFlight#11430
The mixer switch carry over loop ended at the first
INPUT_MIXER_SWITCH_HELPER rule. Switching a mixer profile back before
the carry over of the previous switch had decayed therefore dropped its
remaining filter state, the newly loaded rule restarted from zero and
the servo jumped towards its mid position.

Only the carry capacity ends the loop now, helper rules are carried over
like any other speed limited rule.

Fixes iNavFlight#11503
The constraints list already covers the analogous telemetry rule. Adds
the SERVO_SERIAL case, including that the second assignment used to be
accepted silently without the port ever being opened.
Rename serialDuplicatedSinglePortFunctions() to
serialGetDuplicatedSinglePortFunctions() so the helper has a verb name
like the other serialGet*/serialFind* functions (Development.md iNavFlight#5).

Cut the three-line comment above SERIAL_SINGLE_PORT_FUNCTIONS to one line
that states why the list exists.

docs/Serial.md: drop the "previously it was accepted" history from the
constraint and say what happens to a saved configuration that already
has SBUS output on several ports: only the first port in the serial list
is used, the configuration is not reset.

No functional change.
Development.md asks for comments that explain why, not what. No
functional change.
@qodo-code-review

Copy link
Copy Markdown
Contributor

ⓘ Qodo reviews are paused because the subscription is no longer active. Ask your workspace admin to reactivate the subscription to resume reviews. Manage billing

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Add non-blocking I2C transfers for barometers and compasses

✨ Enhancement 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Add a start-and-poll I2C API to reduce sensor-task time spent waiting for transfers.
• Convert three barometers and two compasses to staged reads while retaining blocking-driver
 compatibility.
• Document platform behavior, recovery, and debugging; hardware testing remains outstanding.
Diagram

graph TD
  T["Sensor tasks"] --> B["Barometer cycle"] --> A["Bus start and poll"] --> P["MCU I2C engines"] --> H["I2C sensors"]
  T --> C["Compass cycle"] --> A
  A --> F["Synchronous fallbacks"] --> H
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Queue transfers in a central bus manager
  • ➕ Could arbitrate shared-bus requests without sensor-level busy retries.
  • ➖ Adds queue ownership, buffer-lifetime, and cancellation complexity across every platform.
2. Use DMA for sensor transfers
  • ➕ Could further reduce CPU work during larger transfers.
  • ➖ Adds platform-specific setup and buffer constraints for mostly short sensor reads.

Recommendation: The one-transfer-per-bus, start-and-poll approach is a reasonable incremental step for these low-rate sensors and preserves existing blocking callers. Prefer it over a queue or DMA for this first conversion, but require shared-bus, disconnect, timeout, and recovery testing across the affected platforms before relying on it.

Files changed (28) +1893 / -620

Enhancement (24) +1695 / -619
debug.hDefine the I2C debug mode +1/-0

Define the I2C debug mode

• Adds DEBUG_I2C for transfer and error diagnostics.

src/main/build/debug.h

barometer.hExtend barometer measurement hooks +11/-0

Extend barometer measurement hooks

• Adds optional non-blocking read phases and a flag for sensors that return temperature and pressure together.

src/main/drivers/barometer/barometer.h

barometer_bmp280.cStage BMP280 forced-mode reads +20/-36

Stage BMP280 forced-mode reads

• Starts the measurement and frame read separately, then parses a persistent buffer. Marks the pressure and temperature frame as a combined read.

src/main/drivers/barometer/barometer_bmp280.c

barometer_dps310.cStage DPS310 status and result reads +37/-16

Stage DPS310 status and result reads

• Separates pressure-ready polling from the six-byte result transfer and parses persistent read buffers.

src/main/drivers/barometer/barometer_dps310.c

barometer_spl06.cStage SPL06 temperature and pressure reads +34/-23

Stage SPL06 temperature and pressure reads

• Moves measurement commands and result reads into separate phases backed by persistent buffers.

src/main/drivers/barometer/barometer_spl06.c

bus.cExpose bus-level transfer starts +89/-2

Expose bus-level transfer starts

• Dispatches new read and write starts to I2C while keeping SPI synchronous. Extends busy polling to return an error.

src/main/drivers/bus.c

bus.hDeclare staged bus operations +20/-1

Declare staged bus operations

• Adds start APIs, error-aware busy polling, and a result enum for multi-transfer sensor reads.

src/main/drivers/bus.h

bus_busdev_i2c.cConnect bus devices to I2C starts +20/-7

Connect bus devices to I2C starts

• Forwards start operations with raw-register flags and polls completion by bus and slave address.

src/main/drivers/bus_busdev_i2c.c

bus_i2c.hDefine the platform I2C contract +30/-2

Define the platform I2C contract

• Declares start and per-address busy APIs, shared outcome storage, and STM32F4 interrupt metadata.

src/main/drivers/bus_i2c.h

bus_i2c_at32f43x.cAdd AT32 interrupt-driven transfer starts +286/-32

Add AT32 interrupt-driven transfer starts

• Uses the AT32 interrupt transfer functions with completion polling, per-address outcomes, diagnostics, and stuck-bus recovery. Blocking operations wait for pending transfers.

src/main/drivers/bus_i2c_at32f43x.c

bus_i2c_hal.cAdd HAL interrupt-driven I2C transfers +324/-9

Add HAL interrupt-driven I2C transfers

• Adds HAL interrupt starts and completion callbacks for STM32F7/H7. Tracks per-address errors, detects stalled or held buses, and coordinates blocking calls.

src/main/drivers/bus_i2c_hal.c

bus_i2c_rp2350.cProvide RP2350 start API fallback +19/-2

Provide RP2350 start API fallback

• Implements the new interface through existing synchronous transfers and reports idle after each call.

src/main/drivers/bus_i2c_rp2350.c

bus_i2c_soft.cProvide software I2C start API fallback +27/-0

Provide software I2C start API fallback

• Wraps existing synchronous software-I2C operations in the new interface.

src/main/drivers/bus_i2c_soft.c

bus_i2c_stm32f40x.cReplace STM32F4 polling with an interrupt engine +524/-416

Replace STM32F4 polling with an interrupt engine

• Replaces the blocking state-machine loop with event and error handlers. Adds shared blocking/non-blocking operation, per-address outcomes, diagnostics, and task-context recovery.

src/main/drivers/bus_i2c_stm32f40x.c

compass.hAdd an optional compass read-start hook +5/-1

Add an optional compass read-start hook

• Allows compass drivers to initiate staged transfers while leaving existing blocking read hooks available.

src/main/drivers/compass/compass.h

compass_qmc5883l.cStage QMC5883L compass reads +40/-15

Stage QMC5883L compass reads

• Reads status before starting a data transfer when DRDY is set, then parses the persistent result buffer.

src/main/drivers/compass/compass_qmc5883l.c

compass_qmc5883p.cStage QMC5883P compass reads +38/-12

Stage QMC5883P compass reads

• Separates status and data transfers into scheduler steps and parses the persistent result buffer.

src/main/drivers/compass/compass_qmc5883p.c

sdcard_spi.cAdapt SD-card busy polling +2/-2

Adapt SD-card busy polling

• Passes a null error pointer to the revised busIsBusy signature at both SPI wait sites.

src/main/drivers/sdcard/sdcard_spi.c

cli.cName the I2C CLI debug mode +2/-1

Name the I2C CLI debug mode

• Adds I2C to the debug-mode names shown by the CLI.

src/main/fc/cli.c

fc_tasks.cReschedule staged sensor tasks +12/-4

Reschedule staged sensor tasks

• Uses sensor-requested deadlines for compass and barometer updates. Feeds the barometer position estimator only when a new sample is ready.

src/main/fc/fc_tasks.c

barometer.cRun barometer measurements in staged phases +99/-30

Run barometer measurements in staged phases

• Replaces the two-state cycle with measurement, read, and sample phases. Retries busy or failed transfers and reports when a new pressure sample was calculated.

src/main/sensors/barometer.c

barometer.hReport barometer sample readiness +1/-1

Report barometer sample readiness

• Changes baroUpdate to expose whether its call produced a new sample.

src/main/sensors/barometer.h

compass.cAdvance compass reads across task runs +49/-6

Advance compass reads across task runs

• Polls staged transfers, handles their errors, and requests short retries before restoring the regular compass period. Drivers without a read-start hook retain their blocking read path.

src/main/sensors/compass.c

compass.hExpose the compass update interval +5/-1

Expose the compass update interval

• Defines the regular compass rate and changes compassUpdate to return its next requested delay.

src/main/sensors/compass.h

Documentation (3) +197 / -0
AGENTS.mdIndex the non-blocking I2C guide +1/-0

Index the non-blocking I2C guide

• Adds the new development guide to the documentation index.

AGENTS.md

Settings.mdList the I2C debug mode +1/-0

List the I2C debug mode

• Documents I2C among the available debug settings.

docs/Settings.md

non-blocking-i2c.mdDocument the I2C transfer model +195/-0

Document the I2C transfer model

• Explains the start-and-poll API, platform behavior, timeouts, sensor conversions, debugging fields, and remaining limitations.

docs/development/non-blocking-i2c.md

Other (1) +1 / -1
settings.yamlRegister the I2C debug setting +1/-1

Register the I2C debug setting

• Adds I2C to the configurable debug-mode values.

src/main/fc/settings.yaml

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (1) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. A held bus can delay motor frames ✓ Resolved
Description
i2cEventHandlerBody() calls i2cWaitBitRelease() from the STM32F4 I2C interrupt, where it can
spin for 1000 µs waiting for a repeated START. If the bus holds that START pending, the
higher-priority I2C interrupt delays motor-timer interrupt servicing and the task that starts the
next DShot frame.

2. Barometer publishes stale conversions ✓ Resolved
Description
baroUpdate() advances from an asynchronous measurement-trigger write to a separate read without
checking whether the write completed successfully. If a BMP280 or SPL06 trigger write is NACKed but
the later read succeeds, the read replaces the stored error and the previous conversion is
calculated and published as a new sample.


Remediation recommended

3. Pico sensor reads still stall tasks 📎 Requirement gap ➹ Performance
Description
On RP2350, i2cReadStart() calls the blocking i2cRead() instead of starting a background
transfer. When an enabled barometer or compass uses that bus, its periodic task performs the entire
register read before it can yield, including reads whose documented wire time is about 200 µs.
Code

src/main/drivers/bus_i2c_rp2350.c[R220-223]

+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);
+}
Evidence
The new RP2350 start wrapper directly invokes a blocking read, and the RP2350 target enables I2C
barometer and compass sensors. This is a documented first-step limitation, but those task calls do
not meet rule 1's non-blocking outcome on that platform.

Non-blocking I2C for compass and barometer tasks
src/main/drivers/bus_i2c_rp2350.c[188-223]
src/main/target/RP2350_PICO/target.h[105-124]
docs/development/non-blocking-i2c.md[11-18]
docs/development/non-blocking-i2c.md[189-195]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The RP2350 start methods complete I2C transfers synchronously, so supported sensor tasks still wait for the wire transfer.
## Fix Focus Areas
- src/main/drivers/bus_i2c_rp2350.c[219-243]
## Recommended Fix
Implement an interrupt-driven RP2350 transfer start and completion path, with per-address results available through `i2cBusy()`. Retain blocking calls for consumers that have not been converted.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. I2C overruns leave the bus unfinished 🐞 Bug ☼ Reliability
Description
i2cErrorHandler() records an overrun as a failure but excludes it from the branch that generates a
STOP or requests a peripheral reset. On an overrun-only interrupt, it disables the transfer
interrupts and marks the bus idle, so the next STM32F4 transfer can start while the aborted cycle
remains active.
Code

src/main/drivers/bus_i2c_stm32f40x.c[R537-538]

+    // If AF, BERR or ARLO, abandon the current job
+    if (SR1Register & (I2C_SR1_BERR | I2C_SR1_ARLO | I2C_SR1_AF)) {
Evidence
The new handler marks OVR as an error, but its STOP/reset branch covers only BERR, ARLO and AF. It
then clears the error flags and sets busy = false. The next start checks for a pending STOP, not
whether the overrun-aborted cycle was terminated, before generating START.

src/main/drivers/bus_i2c_stm32f40x.c[527-556]
src/main/drivers/bus_i2c_stm32f40x.c[387-397]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The STM32F4 overrun error path marks a transfer idle without issuing STOP or scheduling a reset, allowing another transfer to begin on an unfinished bus cycle.
## Fix Focus Areas
- src/main/drivers/bus_i2c_stm32f40x.c[532-556]
- src/main/drivers/bus_i2c_stm32f40x.c[387-397]
## Recommended Fix
Include an overrun in the transfer-abort cleanup. Generate STOP when safe, or set `needsReset` so task context finishes and reinitializes the peripheral before the next transfer starts.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. A stuck baro trigger write can hang the bus for good ✓ Resolved
Description
In baroUpdate, BARO_STATE_PRESSURE_START / BARO_STATE_TEMPERATURE_START start a non-blocking
busWriteStart() (BMP280, SPL06) and then go straight to the READ state. The READ state only calls
read_up/read_ut, and the F4 and HAL i2cStartTransfer() just return false while busy is set,
without checking whether the transfer is stuck. Stuck detection only runs from i2cBusy() or a
blocking wait, so if the write hangs and the baro is alone on the bus, nothing ever calls
busIsBusy(). The task then retries every 1 ms forever and the peripheral is never reset.

View medium (1)
6. Failed reads on synchronous I2C platforms are retried every 1 ms ✓ Resolved
Description
The RP2350 and software-I2C start wrappers return the result of the blocking
i2cRead()/i2cWrite(), so a NACK or bus error comes back as false. The API defines false as
'bus busy, nothing started', and i2cBusy() on these platforms always reports error = false. When
a baro or QMC compass is unplugged or failing, baroUpdate and compassUpdate therefore treat
every failure as busy and run a full blocking transfer every 1 ms indefinitely, instead of recording
an error and going back to the normal sensor period.


Informational

7. HITL baro runs at 1 kHz on DPS310 boards ✓ Resolved
Description
In HITL mode, baroUpdate now returns dev->up_delay as the task period and sets newSampleReady
on every call. For DPS310/SPL07 this PR changes up_delay to 1000 µs, so the baro task and
updatePositionEstimator_BaroTopic run every 1 ms instead of at the sensor's ~32 Hz rate. The
comment claims HITL publishes 'at the sensor's pace', but here the task just burns CPU feeding the
estimator duplicate simulator samples.

Grey Divider

Tip of the day
💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/main/drivers/bus_i2c_stm32f40x.c Resolved
Comment thread src/main/drivers/bus_i2c_rp2350.c Resolved
Comment thread src/main/sensors/barometer.c Resolved
Comment thread src/main/drivers/bus_i2c_stm32f40x.c Resolved
Comment thread src/main/sensors/barometer.c Resolved
Comment thread src/main/drivers/bus_i2c_rp2350.c Resolved
Comment thread src/main/sensors/barometer.c Resolved
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

RAM / Flash usage vs. base commit 01a7aa3 — commit b071da2

Using the nearest available size baseline: this build contains base commit 6cbfc64, which has no stored baseline yet, so the deltas also include what was merged to the base since 01a7aa3.

Target Flash Δ RAM Δ
MATEKF405 ⚠️ +6256 B (+0.86%) CCM: -4 B (-0.01%)
RAM: +1852 B (+1.78%)
MATEKF722 -500 B (-0.10%) ITCM_RAM: -928 B (-7.40%)
RAM: +44 B (+0.05%)
TCM: ±0 B (±0.00%)
MATEKF765 +64 B (+0.01%) DTCM_RAM: ±0 B (±0.00%)
SRAM1: +64 B (+0.05%)
MATEKH743 ⚠️ +12492 B (+1.56%) D2_RAM: +256 B (+7.84%)
DTCM_RAM: ±0 B (±0.00%)
ITCM_RAM: -888 B (-5.41%)
RAM: +2196 B (+1.54%)

See RAM/flash optimization guide for techniques to reduce usage.

@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Test firmware build ready — commit ef05e53

Download firmware for PR #12133

251 targets built. Find your board's .hex file by name on that page (e.g. MATEKF405SE.hex). Files are individually downloadable — no GitHub login required.

Development build for testing only. Use Full Chip Erase when flashing.

@error414

error414 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Tested on:

  • matek H743wlite
  • kakukate F405 AIO
  • neutronrc AT32 mini AIO

It takes more flash + RAM because this PR just add async for I2C for some devices. There are another PRs for rewriting rest of devices.

@error414

error414 commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Reduce memory for F7 CPUs, replace HAL to direct registry access. Idea and ispiration taken from #12157

@error414 error414 changed the title I2C asyn calling I2C asyn calling -- CORE Nov 5, 2026
@error414
error414 changed the base branch from maintenance-10.x to next-10.1 November 6, 2026 17:16
@sensei-hacker sensei-hacker added this to the 10.1 milestone Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants