Skip to main content
Visitor II
January 23, 2021
Question

I2C doesn't work after uploading (only sometimes)

  • January 23, 2021
  • 12 replies
  • 2770 views

I wrote a little program that reads I2C values with interrupts: The Problem is that sometimes it just doesn't work after uploading. I just have to run it so many times till it works (not changing anything in the code). It seems like its just coincidence if it works or not.

Here are the Details:

Sensor: HMC 5983 or MPU-6050 (same problem)

Board: STM32F103RB (Nucleo 64)

Code (without the generated Cubemx stuff):

int main(void) {
 /*/////////////////////Setup/////////////////////////*/
	buf[0] = 0x00;
	buf[1] = 0x78;
	buf[2] = 0x80;
	buf[3] = 0x00;
	HAL_I2C_Master_Transmit(&hi2c1, Kompass_ADDR, buf, 4, 100);
	/*//////////////////////Start of IT Routine//////////////////*/
	buf[0] = 0x03;
	HAL_I2C_Master_Transmit_IT(&hi2c1, Kompass_ADDR, buf, 1);
 
	/* USER CODE END 2 */
 
	/* Infinite loop */
	/* USER CODE BEGIN WHILE */
	while (1) {
		/*/////////////////////printing the value////////////////////////*/
	 sprintf((char*) Serial_buffer, " X %i \r\n", DataX);
		HAL_UART_Transmit(&huart2, (uint8_t*) Serial_buffer, strlen((char*) Serial_buffer), 100);
		HAL_Delay(500);
		/* USER CODE END WHILE */
 
		/* USER CODE BEGIN 3 */
	}
	/* USER CODE END 3 */
}
 
 
void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) {
	HAL_I2C_Master_Receive_IT(&hi2c1, Kompass_ADDR, buf, 6);
}
void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) {
	DataX = ((int16_t) buf[0]) << 8 | buf[1];
	buf[0] = 0x03;
	HAL_I2C_Master_Transmit_IT(&hi2c1, Kompass_ADDR, buf, 1);
}
////////////////////////////I2C Init Function////////////////////////
static void MX_I2C1_Init(void) {
 
	hi2c1.Instance = I2C1;
	hi2c1.Init.ClockSpeed = 100000;
	hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
	hi2c1.Init.OwnAddress1 = 0;
	hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
	hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
	hi2c1.Init.OwnAddress2 = 0;
	hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
	hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
	if (HAL_I2C_Init(&hi2c1) != HAL_OK) {
		Error_Handler();
	}
}
 

Thank you in Advance :)

    This topic has been closed for replies.

    12 replies

    SenaxAuthor
    Visitor II
    January 23, 2021

    Nope, that didn't help.

    Visitor II
    January 7, 2024

    Hey there! I'm having the exact same issue, did you manage to find a solution? Thanks