1 Commits

Author SHA1 Message Date
Damien George
1b578fe2c0 extmod/machine_i2c_target: Add new machine.I2CTarget class.
This commit implements a generic I2C target/peripheral/"slave" device,
called `machine.I2CTarget`.  It can work in two separate modes:

- A general device with interrupts/events/callbacks for low-level I2C
  operations like address match, read request and stop.

- A memory device that allows reading/writing a specific region of memory
  (or "registers") on the target I2C device.

To make a memory device is very simple:

    from machine import I2CTarget

    mem = bytearray(8)
    i2c = I2CTarget(addr=67, mem=mem)

That's all that's needed to start the I2C target.  From then on it will
respond to any I2C controller on the bus, allowing reads and writes to the
mem bytearray.

It's also possible to register to receive events.  For example to be
notified when the memory is read/written:

    from machine import I2CTarget

    def irq_handler(i2c_target):
        flags = i2c_target.irq().flags()
        if flags & I2CTarget.IRQ_END_READ:
            print("controller read target at addr", i2c_target.memaddr)
        if flags & I2CTarget.IRQ_END_WRITE:
            print("controller wrote target at addr", i2c_target.memaddr)

    mem = bytearray(8)
    i2c = I2CTarget(addr=67, mem=mem)
    i2c.irq(irq_handler)

Instead of a memory device, an arbitrary I2C device can be implemented
using all the events (see docs).

This is based on the discussion in #3935.

Signed-off-by: Damien George <damien@micropython.org>
2025-08-01 23:03:17 +10:00