CH552 Drivers: Software I2C Driver
(If you have not done so already, you will need to setup a toolchain for CH552 programming to follow this tutorial. Tutorials 0 and 1 in the CH552 Assembly series provide instructions for setting up and testing the C programming toolchain.)
The QT Py CH552 has a very convenient STEMMA QT port, that makes it easy to connect I2C devices. Dequing Sun has provided a nice little Arduino library for it, but looking through the code, I really don't like the dependence it has on Arduino's GPIO libraries. There's just a lot of indirection and generic code going on, and indirection and generic code means a lot of extra bytes and cycles in the process. For example, I2CSend()
toggles the I2C pins by calling digitalWrite()
three times for each byte being sent (once for the data pin, twice for the clock pin). digitalWrite()
calls some lookup code to translate the Arduino pin numbering into the hardware port and pin number. It has to use some conditionals to switch the pin off or on, based on an argument given to digitalWrite()
. Now, there's a good reason it does this. Arduino wants to be very flexible in the minimum amount of code possible, so it has to cover every possible use case. It doesn't know what pins you might want to do I2C on, so it has to allow any combination of pins to be used. The cost of this level of flexibility, however, is that instead of directly setting a pin to low or high (or setting a pin mode) in just a single instruction, it has to go through around 60 instructions each and every time. On a 16MHz processor, this may not always be a disaster in terms of performance cost, but it does make I2C much slower, and when you only have 14KB of available program memory, it uses a lot of valuable space. Unless we really need the flexibility of using digitalWrite()
, it's not really worth the space, especially if there's a chance we could end up constrained by limited program memory or by processor or I2C speed.
Keep reading with a 7-day free trial
Subscribe to Technium Adeptus to keep reading this post and get 7 days of free access to the full post archives.