micropython / stm32lib

STM32 Cube library - CMSIS and HAL for F4, F7 and L4 microcontrollers
63 stars 71 forks source link

F4_HAL/i2c: Fix I2C frequency is faster than specified one. #22

Closed yn386 closed 1 year ago

yn386 commented 1 year ago

This PR fixes following issue.

The actual I2C frequency is faster than specified one and it may exceededs I2C's specification for Fast mode. Also, pyb.I2C initialize with baudrate=400000 (I2C Fast mode) by default but actual frequency of SCL is faster than 400KHz. The frequency of SCL should be less than or equal to 400KHz in Fast mode.

How to reproduce

Execute this code

>>> i2c=pyb.I2C(1, pyb.I2C.CONTROLLER)
>>> i2c
I2C(1, I2C.CONTROLLER, baudrate=420000)
>>> i2c = pyb.I2C(1, pyb.I2C.CONTROLLER, baudrate=350000)
>>> i2c
I2C(1, I2C.CONTROLLER, baudrate=420000)

MicroPython Version

v1.19.1

Environment

NUCLEO-F446RE

Detail of changes

I2C is initialized by https://github.com/micropython/micropython/blob/0e8c2204da377e95b5000a3c708891d98cdeb69c/ports/stm32/pyb_i2c.c#L254-L257 but I think current stm32lib has a bug that the frequency is faster than specified one. This bug is fixed at least v1.24.1 but I couldn't find a release note about this fix. I backport it from v1.27.1.

After applying this PR, the frequency of SCL is less than 400KHz.

>>> i2c=pyb.I2C(1)
>>> i2c
I2C(1, I2C.CONTROLLER, baudrate=336000)
>>> i2c = pyb.I2C(1, pyb.I2C.CONTROLLER, baudrate=350000)
>>> i2c
I2C(1, I2C.CONTROLLER, baudrate=336000)
dpgeorge commented 1 year ago

Thanks for the patch. Rebased and merged in 98b95448a08fb5d6720bc4aaccc6dfa25264c357