What’s the problem with I2C of STM32?
The STM32 chips are all really good designed, coming with a really nice price - for a normal, wide-used STM32F1, the price is around 1-2 bucks in some small scale order. If take the fact that ST is really nice to small order and always willing to give a good price, everything about STM32 seems so perfect.
However, such bargain has its own weakness - its own I2C peripheral has some really serious hardware bug, that it is really sensitive to the time sequence, even interrupted by a small function, the peripheral would fail. An application engineering of STMicroelectronics has mention their concern in an offline meeting. She said the I2C peripheral is designed like this on purposely, just to avoid some strict patent of NXP. Check here
Checking their errata in chapter 2.13, would give you more idea about their problem.
I don’t want to comment too much on their design, you could find a lot of posts complaining about the BUSY-LOCK issue everywhere.
Here comes to my solution:
Here is my final solution to this problem:use the interrupt and simulate with GPIO, after all, I2C is a low-speed time-triggered protocol, using while(x)
to wait (just like what the CPAL library do)is a waste on a such high frequency MCU.
These code has the following benefit:
- the interrupt would be set at an 100kHz speed, but don’t need to occupy the highest priority of interrupts, after all, the I2C is a really slow bus under its normal mode, the STM32F1 could actually spend 720 cycle on some more urgent issues.
- only consumes a timer inside STM32, even the internal one work (those don’t have GPIO assigned would also be acceptable)
Code is attached at the end, here I illustrate how to use the code:
- Add
#include "i2c_sim.h"
in your main file. - Modify the
I2C_SCL_GPIO_PORT
,I2C_SCL_GPIO_PIN
andI2C_SDA_GPIO_PORT
,I2C_SDA_GPIO_PIN
in thei2c_sim.c
, any GPIO would do the job. - Modify all
htim6
to the handle of your own preferred timer. - Add a line
include "i2c_sim.h"
between/* USER CODE BEGIN 0 */
and/* USER CODE END 0 */
intim.c
. - Add the following code to
tim.c
, between/* USER CODE BEGIN 1 */
and/* USER CODE END 1*/
:
1 | void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){ |
Change the TIM6 to your preferred timer.
- Use the
IIC_SetCallback()
to setup all callback function you need in your ownmain.c
, and all the other function likeI2C_Write7()
andI2C_Read7()
could be used to communicate with the I2C device. - Set up your own TIM6_Init with the help of STM32CubeMX. Remember to configure the Prescaler and Period so that it reach your desired frequency.
The following code is tested under STM32F103 series, it’s mainly a time triggered deterministic finite automation.
Comment below if you need further help:
i2c_sim.h
:
1 |
|
i2c_sim.c
:
1 |
|