Drivers creating their own I2C/SPI objects?

I haven’t been able to get a super straight answer on this anywhere, so I figured I should ask. Back when I used Mbed 2, it was normal to have each driver create its own SPI or I2C object from the pins passed into it. This was straightforward, and it was also nice because if, for instance, two different sensors used different SPI modes, Mbed would handle switching them depending on which SPI object was being used to access the bus.

However, since updating to Mbed 6.x, this no longer seems to work properly, at least on LPC1768. Creating two SPI or I2C objects representing the same physical bus seems to cause one of the objects to fail to send or receive data. I did some quick checking with the debugger and it looks like the I2C code is receiving errors from the chip registers inside the HAL. So it seems like creating two I2Cs somehow causes the LPC1768 I2C peripheral to be configured incorrectly.

Is this intended behavior? If so, how is one supposed to handle sharing an SPI bus between sensors that use different frequencies or modes?

Hello Jamie,

I don’t think it’s an intended behavior. For both SPI and I2C there are setup static variables holding a pointer of the current owner of the peripheral.
In case of SPI it’s the :
spi_peripheral_s *_peripheral->owner
and in case of the I2C it’s the
I2C *_owner
Whenever an object tries to get access to the bus (to perform a read or write operation) the acquire method of the given object is called. If the object doesn’t own the peripheral (the owner doesn’t point to the this object) the peripheral is reconfigured according to the object’s settings (mode and frequency in case of SPI and frequency in case of I2C) and the object is set as the new owner of the peripheral. So theoretically it should work. Does your code call the acquire method when running in the debugger?

Best regards, Zoltan

Alright, it seems to be a bug, I filed a report here (with a workaround that I found).