A solution to I2C/IIC bug in STM32


What’s the problem with I2C of STM32?

The STM32 chips are all really well-designed ones, coming with a nice price - for a common, wide-used STM32F1, the price is around 1-2 bucks in 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 with a high possibility. An application engineer of STMicroelectronics has mention this concern in an offline meeting. She said the I2C peripheral is designed as 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. The commonly approach to imitigate this, namely using while(x) to wait (just like what the CPAL library do), is a waste on a such high frequency MCU.

These code comes with the following benefits:

  1. 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.
  2. 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:

  1. Add #include "i2c_sim.h" in your main file.
  2. Modify the I2C_SCL_GPIO_PORT,I2C_SCL_GPIO_PIN and I2C_SDA_GPIO_PORT,I2C_SDA_GPIO_PIN in the i2c_sim.c, any GPIO would do the job.
  3. Modify all htim6 to the handle of your own preferred timer.
  4. Add a line include "i2c_sim.h" between /* USER CODE BEGIN 0 */ and /* USER CODE END 0 */ in tim.c.
  5. Add the following code to tim.c, between /* USER CODE BEGIN 1 */ and /* USER CODE END 1*/:

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
  if (htim->Instance == TIM6) {
    Timer_CallBack();
  }
}
Change the TIM6 to your preferred timer. 5. Use the IIC_SetCallback() to setup all callback function you need in your own main.c, and all the other function like I2C_Write7() and I2C_Read7() could be used to communicate with the I2C device. 6. 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 :

#ifndef __I2C_SIM_H__
  #define __I2C_SIM_H__
  #ifdef __cplusplus
    extern "C" {
  #endif
    #include "tim.h"
    uint8_t I2C_Read7(uint8_t device, uint8_t Addr, uint8_t *Buf, uint8_t Count);
    uint8_t I2C_Read16(uint8_t device, uint16_t Addr, uint8_t *Buf, uint8_t Count);
    uint8_t I2C_Write7(uint8_t device, uint8_t Addr, uint8_t *Buf, uint8_t Count);
    uint8_t I2C_Write16(uint8_t device, uint16_t Addr, uint8_t *Buf, uint8_t Count);
    void IIC_Init(void);
    void IIC_DeInit(void);
    void IIC_SetCallback(void(*OnTx)(void), void(*OnRx)(void) ,void(*OnErr)(void));
    void Timer_CallBack(void);
  #ifdef __cplusplus
    }
  #endif
#endif

i2c_sim.c :

#include "i2c_sim.h"
#include "tim.h"
#include <string.h>
GPIO_TypeDef* I2C_SCL_GPIO_PORT = GPIOB;
const uint16_t I2C_SCL_GPIO_PIN = GPIO_PIN_6;

GPIO_TypeDef* I2C_SDA_GPIO_PORT = GPIOB;
const uint16_t I2C_SDA_GPIO_PIN = GPIO_PIN_7;

#define SDA_Clear() HAL_GPIO_WritePin(I2C_SDA_GPIO_PORT,I2C_SDA_GPIO_PIN,GPIO_PIN_RESET)
#define SDA_Set() HAL_GPIO_WritePin(I2C_SDA_GPIO_PORT,I2C_SDA_GPIO_PIN,GPIO_PIN_SET)
#define SDA_Read() HAL_GPIO_ReadPin(I2C_SDA_GPIO_PORT,I2C_SDA_GPIO_PIN)

#define SCL_Clear() HAL_GPIO_WritePin(I2C_SCL_GPIO_PORT,I2C_SCL_GPIO_PIN,GPIO_PIN_RESET)
#define SCL_Set() HAL_GPIO_WritePin(I2C_SCL_GPIO_PORT,I2C_SCL_GPIO_PIN,GPIO_PIN_SET)

void __INLINE En_SDA_Input() {
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
	GPIO_InitStructure.Mode = GPIO_MODE_INPUT;
	GPIO_InitStructure.Pull = GPIO_NOPULL; //No Pull-up or Pull-down activation
	GPIO_InitStructure.Pin = I2C_SDA_GPIO_PIN;
	HAL_GPIO_Init((GPIO_TypeDef*)I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
}
void __INLINE En_SDA_Output() {
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
	GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD;
	GPIO_InitStructure.Pull = GPIO_NOPULL; //No Pull-up or Pull-down activation
	GPIO_InitStructure.Pin = I2C_SDA_GPIO_PIN;
	HAL_GPIO_Init((GPIO_TypeDef*)I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
}


typedef struct {
	__IO uint8_t StartState;
	__IO uint8_t StopState;
	__IO int8_t ReadByteState;
	__IO uint8_t TransferByte;
	__IO uint8_t ReadStop;
	__IO uint8_t WriteByteState;
	__IO uint8_t WriteACK;
	__IO uint8_t Command;   //1-Read, 0=Write;
	__IO uint8_t Device;
	__IO uint32_t SubAddr;
	__IO uint8_t SubAddrLen;
	__IO uint8_t *TransferBuf;
	__IO uint16_t TransferCount;
	__IO uint8_t ReadState;
	__IO uint8_t WriteState;

	__IO uint8_t dat;
	__IO uint8_t bit;
	__IO uint8_t IIC_BUSY;
	__IO uint8_t ERROR;
}   IIC_State;

static IIC_State iic_state;

typedef struct {
	void(*OnTx)(void);
	void(*OnRx)(void);
	void(*OnErr)(void);
} IIC_Callback;

__IO IIC_Callback iic_callback;

#define IN            1
#define OUT           0

void SetIicSdaDir(uint8_t x) {
	if (x) En_SDA_Input();
	else En_SDA_Output();
}

void IIC_GPIOInit()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	__HAL_RCC_GPIOB_CLK_ENABLE();
	GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
	GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_OD;
	GPIO_InitStructure.Pull = GPIO_NOPULL; //No Pull-up or Pull-down activation
	GPIO_InitStructure.Pin = I2C_SCL_GPIO_PIN;
	HAL_GPIO_Init((GPIO_TypeDef*)I2C_SCL_GPIO_PORT, &GPIO_InitStructure);
	GPIO_InitStructure.Pin = I2C_SDA_GPIO_PIN;
	HAL_GPIO_Init((GPIO_TypeDef*)I2C_SDA_GPIO_PORT, &GPIO_InitStructure);
}

static void IIC_DelayTimer_Init()
{
	if (HAL_TIM_Base_Start_IT(&htim6) != HAL_OK) {
	};
	memset((void *)&iic_state, 0, sizeof(IIC_State));
	memset((void *)&iic_callback, 0, sizeof(IIC_Callback));
}

static void IIC_DelayTimer_DeInit()
{
	HAL_TIM_Base_Stop_IT(&htim6);
	HAL_TIM_Base_DeInit(&htim6);
}

void IIC_Init()
{
	IIC_GPIOInit();
	SDA_Set();
	SCL_Set();
	IIC_DelayTimer_Init();
}

void IIC_SetCallback(void(*OnTx)(void), void(*OnRx)(void), void(*OnErr)(void))
{
	iic_callback.OnErr = OnErr;
	iic_callback.OnTx = OnTx;
	iic_callback.OnRx = OnRx;
}

void IIC_DeInit()
{
	IIC_DelayTimer_DeInit();
}

static uint8_t IIC_StartStateMachine()
{
	switch (iic_state.StartState) {
	case 0:
		SDA_Set();
		SCL_Set();
		iic_state.StartState++;
		break;
	case 1:
		SDA_Clear();
		//SoftDelay(0);
		iic_state.StartState++;
		break;
	case 2:
		SCL_Clear();
		iic_state.StartState = 0;
		break;
	}
	return iic_state.StartState;
}

static uint8_t IIC_StopStateMachine()
{
	switch (iic_state.StopState) {
	case 0:
		SCL_Set();
		SDA_Clear();
		iic_state.StopState++;
		break;
	case 1:
		SDA_Set();
		iic_state.StopState = 0;
		break;
	}
	return iic_state.StopState;
}

static uint8_t IIC_ReadByteStateMachine()
{
	switch (iic_state.ReadByteState) {
	case 0:
		SetIicSdaDir(IN);
		iic_state.bit = 0;
		iic_state.ReadByteState++;
		break;
	case 1:
		iic_state.dat <<= 1;
		SCL_Set();
		iic_state.ReadByteState++;
		break;
	case 2:
		if (SDA_Read())
		{
			iic_state.dat |= 1;
		}
		SCL_Clear();
		iic_state.bit++;
		if (iic_state.bit == 8) iic_state.ReadByteState++;
		else {
			iic_state.ReadByteState--;
			break;
		}
	case 3:
		iic_state.TransferByte = iic_state.dat;
		SetIicSdaDir(OUT);
		if (iic_state.ReadStop) SDA_Set(); else SDA_Clear();     // ReadStop = 0; ask, ReadStop = 1,stop
		iic_state.ReadByteState++;
		break;
	case 4:
		SCL_Set();
		iic_state.ReadByteState++;
		break;
	case 5:
		SCL_Clear();
		iic_state.ReadByteState++;
	case 6:
		iic_state.ReadByteState = 0;
		break;
	}
	return iic_state.ReadByteState;
}

static uint8_t IIC_WriteByteStateMachine()
{
	switch (iic_state.WriteByteState) {
	case 0:
		iic_state.dat = iic_state.TransferByte;
		iic_state.bit = 8;
		iic_state.WriteByteState++;
	case 1:
		if (iic_state.dat & 0x80)
		{
			SDA_Set();
		}
		else
		{
			SDA_Clear();
		}
		iic_state.WriteByteState++;
		break;
	case 2:
		SCL_Set();
		iic_state.WriteByteState++;
		break;
	case 3:
		iic_state.dat <<= 1;
		SCL_Clear();
		iic_state.bit--;
		if (iic_state.bit) {
			iic_state.WriteByteState = 1;
			break;
		}
		else iic_state.WriteByteState++;
	case 4:
		SetIicSdaDir(IN);
		iic_state.WriteByteState++;
		break;
	case 5:
		SCL_Set();
		iic_state.WriteByteState++;
		break;
	case 6:
		iic_state.WriteACK = SDA_Read();
		SCL_Clear();
		SetIicSdaDir(OUT);
		iic_state.WriteByteState++;
		break;
	case 7:
		iic_state.WriteByteState = 0;
		break;
	}
	return iic_state.WriteByteState;
}

static uint8_t IIC_ReadStateMachine()
{
	switch (iic_state.ReadState) {
	case 0:
		iic_state.ReadState++;
	case 1:
		if (IIC_StartStateMachine() == 0) iic_state.ReadState++;
		break;
	case 2:
		iic_state.TransferByte = iic_state.Device;
		iic_state.ReadState++;
	case 3:
		if (IIC_WriteByteStateMachine() == 0) {
			if (iic_state.WriteACK == 1) {
				iic_state.ReadState = 14;     //Stop
			}
			else {
				if (iic_state.SubAddrLen)   iic_state.ReadState++;  //Send Access Address
				else iic_state.ReadState += 3;    //No Address
			}
		}
		break;
	case 4: //Send Address
		switch (iic_state.SubAddrLen) {
		case 4: iic_state.TransferByte = (iic_state.SubAddr >> 24) & 0x000000FF; break;
		case 3: iic_state.TransferByte = (iic_state.SubAddr >> 16) & 0x000000FF; break;
		case 2: iic_state.TransferByte = (iic_state.SubAddr >> 8) & 0x000000FF; break;
		case 1: iic_state.TransferByte = iic_state.SubAddr & 0x000000FF; break;
		}
		iic_state.SubAddrLen--;
		iic_state.ReadState++;
	case 5:
		if (IIC_WriteByteStateMachine() == 0) {
			if (iic_state.WriteACK == 1) {
				iic_state.ReadState = 14;     //Stop
			}
			else {
				if (iic_state.SubAddrLen == 0) iic_state.ReadState++;
				else iic_state.ReadState--;
			}
		}
		break;
	case 6:
		if (IIC_StartStateMachine() == 0) iic_state.ReadState++;
		break;
	case 7: //Send Device Read
		iic_state.TransferByte = iic_state.Device | 0x01;
		iic_state.ReadState++;
	case 8:
		if (IIC_WriteByteStateMachine() == 0) {
			if (iic_state.WriteACK == 1) {
				iic_state.ReadState = 14;
			}
			else {
				if (iic_state.TransferCount == 1) iic_state.ReadState += 3;
				else iic_state.ReadState++;
			}
		}
		break;
	case 9: //Read Bytes
		iic_state.ReadStop = 0;
		iic_state.ReadState++;
	case 10:
		if (IIC_ReadByteStateMachine() == 0) {
			*iic_state.TransferBuf = iic_state.TransferByte;
			iic_state.TransferBuf++;
			iic_state.TransferCount--;
			if (iic_state.TransferCount == 1) iic_state.ReadState++;
		}
		break;
	case 11:    //Read Last Byte
		iic_state.ReadStop = 1;
		iic_state.ReadState++;
	case 12:    //Read Last Byte
		if (IIC_ReadByteStateMachine() == 0) {
			*iic_state.TransferBuf = iic_state.TransferByte;
			iic_state.TransferCount = 0;
			iic_state.ReadState++;
		}
		break;
	case 13:
		if (IIC_StopStateMachine() == 0) {
			iic_state.ReadState = 0;
			iic_state.IIC_BUSY = 0;
			iic_state.ERROR = 0;
			if (iic_callback.OnRx) iic_callback.OnRx();
		}
		break;
	case 14:
		if (IIC_StopStateMachine() == 0) {
			iic_state.ReadState = 0;
			iic_state.IIC_BUSY = 0;
			iic_state.ERROR = 1;
			if (iic_callback.OnErr) iic_callback.OnErr();
		}
		break;
	}
	return iic_state.ReadState;
}

static uint8_t IIC_WriteStateMachine()
{
	switch (iic_state.WriteState) {
	case 0:
		iic_state.WriteState++;
	case 1:
		if (IIC_StartStateMachine() == 0) iic_state.WriteState++;
		break;
	case 2:
		iic_state.TransferByte = iic_state.Device;
		iic_state.WriteState++;
	case 3:
		if (IIC_WriteByteStateMachine() == 0) {
			if (iic_state.WriteACK == 1) {
				iic_state.WriteState = 11;        //Stop
			}
			else {
				if (iic_state.SubAddrLen)   iic_state.WriteState++; //Send Access Address
				else {
					if (iic_state.TransferCount) iic_state.WriteState += 5;   //Multi-Bytes;
					else iic_state.WriteState += 3; //Single Byte
				}
			}
		}
		break;
	case 4: //Send Address
		switch (iic_state.SubAddrLen) {
		case 4: iic_state.TransferByte = (iic_state.SubAddr >> 24) & 0x000000FF; break;
		case 3: iic_state.TransferByte = (iic_state.SubAddr >> 16) & 0x000000FF; break;
		case 2: iic_state.TransferByte = (iic_state.SubAddr >> 8) & 0x000000FF; break;
		case 1: iic_state.TransferByte = iic_state.SubAddr & 0x000000FF; break;
		}
		iic_state.SubAddrLen--;
		iic_state.WriteState++;
	case 5:
		if (IIC_WriteByteStateMachine() == 0) {
			if (iic_state.WriteACK == 1) {
				iic_state.WriteState = 11;        //Stop
			}
			else {
				if (iic_state.SubAddrLen == 0) {
					if (iic_state.TransferCount) iic_state.WriteState += 3;   //Multi-Bytes;
					else iic_state.WriteState++; //Single Byte
				}
				else iic_state.WriteState--;
			}
		}
		break;
	case 6: //Send Only One Byte
		iic_state.TransferByte = (uint32_t)iic_state.TransferBuf;
		iic_state.WriteState++;
	case 7:
		if (IIC_WriteByteStateMachine() == 0) {
			if (iic_state.WriteACK == 1) {
				iic_state.WriteState = 11;        //Stop
			}
			else {
				iic_state.WriteState += 3;
			}
		}
		break;
	case 8: //Send Multi-Bytes Data
		iic_state.TransferByte = *iic_state.TransferBuf; iic_state.TransferBuf++; iic_state.TransferCount--;
		iic_state.WriteState++;
	case 9:
		if (IIC_WriteByteStateMachine() == 0) {
			if (iic_state.WriteACK == 1) {
				iic_state.WriteState = 11;        //Stop
			}
			else {
				if (iic_state.TransferCount == 0) iic_state.WriteState++;
				else iic_state.WriteState--;
			}
		}
		break;
	case 10:
		if (IIC_StopStateMachine() == 0) {
			iic_state.WriteState = 0;
			iic_state.IIC_BUSY = 0;
			iic_state.ERROR = 0;
			if (iic_callback.OnTx) iic_callback.OnTx();
		}
		break;
	case 11:
		if (IIC_StopStateMachine() == 0) {
			iic_state.WriteState = 0;
			iic_state.IIC_BUSY = 0;
			iic_state.ERROR = 1;
			if (iic_callback.OnErr) iic_callback.OnErr();
		}
		break;
	}
	return iic_state.WriteState;
}

static uint8_t IIC_StateMachine()
{
	if (iic_state.Command) return IIC_ReadStateMachine();
	return IIC_WriteStateMachine();
}


uint8_t I2C_Read7(uint8_t device, uint8_t Addr, uint8_t *Buf, uint8_t Count)
{
	if (iic_state.IIC_BUSY == 0) {
		memset(&iic_state, 0, sizeof(IIC_State));
		iic_state.Command = 1;    //1-Read, 0=Write;
		iic_state.Device = device;
		iic_state.SubAddr = Addr;
		iic_state.SubAddrLen = 1;
		iic_state.TransferBuf = Buf;
		iic_state.TransferCount = Count;
		iic_state.IIC_BUSY = 1;
		HAL_TIM_Base_Start_IT(&htim6);
		return 1;
	}
	else return 0;
}

uint8_t I2C_Read16(uint8_t device, uint16_t Addr, uint8_t *Buf, uint8_t Count)
{
	if (iic_state.IIC_BUSY == 0) {
		memset(&iic_state, 0, sizeof(IIC_State));
		iic_state.Command = 1;    //1-Read, 0=Write;
		iic_state.Device = device;
		iic_state.SubAddr = Addr;
		iic_state.SubAddrLen = 2;
		iic_state.TransferBuf = Buf;
		iic_state.TransferCount = Count;
		iic_state.IIC_BUSY = 1;
		HAL_TIM_Base_Start_IT(&htim6);
		return 1;
	}
	else return 0;
}

uint8_t I2C_Write7(uint8_t device, uint8_t Addr, uint8_t *Buf, uint8_t Count)
{
	if (iic_state.IIC_BUSY == 0) {
		memset(&iic_state, 0, sizeof(IIC_State));
		iic_state.Command = 0;    //1-Read, 0=Write;
		iic_state.Device = device;
		iic_state.SubAddr = Addr;
		iic_state.SubAddrLen = 1;
		iic_state.TransferBuf = Buf;
		iic_state.TransferCount = Count;
		iic_state.IIC_BUSY = 1;
		HAL_TIM_Base_Start_IT(&htim6);
		return 1;
	}
	else return 0;
}
uint8_t I2C_Write16(uint8_t device, uint16_t Addr, uint8_t *Buf, uint8_t Count)
{
	if (iic_state.IIC_BUSY == 0) {
		memset(&iic_state, 0, sizeof(IIC_State));
		iic_state.Command = 0;    //1-Read, 0=Write;
		iic_state.Device = device;
		iic_state.SubAddr = Addr;
		iic_state.SubAddrLen = 2;
		iic_state.TransferBuf = Buf;
		iic_state.TransferCount = Count;
		iic_state.IIC_BUSY = 1;
		HAL_TIM_Base_Start_IT(&htim6);
		return 1;
	}
	else return 0;
}

void Timer_CallBack(void){
        if (IIC_StateMachine() == 0){
                if (iic_state.IIC_BUSY == 0)
		         HAL_TIM_Base_Stop_IT(&htim6);
        }
}
comments powered by Disqus