HAL STM32F1硬件I1C扫描从设备地址

HAL STM32F1硬件I1C扫描从设备地址


  • ✨利用硬件I2C接口扫描从设备地址是否在线,可以有效的帮助检测从设备是否在线,以及诊断从设备是否工作正常,以及用在快速查找设备I2C地址上。
  • 扫描ssd1306 I2C oled屏幕地址:(0x78 = 0x3c << 1)
    HAL STM32F1硬件I1C扫描从设备地址_第1张图片
  • 扫描挂载的MPU6050地址:
    HAL STM32F1硬件I1C扫描从设备地址_第2张图片

⚡需要注意的是,扫描到的地址,需要左移一位才是从设备的真正I2C地址。

STM32CubeMX工程配置

  • 指定一个12C接口,具体参数如下:
    HAL STM32F1硬件I1C扫描从设备地址_第3张图片
  • Hal库主要功能实现函数:HAL_I2C_IsDeviceReady

main函数代码

int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
	printf("Scanning I2C bus:\r\n");
	HAL_StatusTypeDef result;
 	uint8_t i;
 	for (i=1; i<128; i++)
 	{
 	  /*
 	   * the HAL wants a left aligned i2c address
 	   * &hi2c1 is the handle
 	   * (uint16_t)(i<<1) is the i2c address left aligned
 	   * retries 2
 	   * timeout 2
		i2c address:(0x78 = 0x3c << 1)
 	   */
 	  result = HAL_I2C_IsDeviceReady(&hi2c1, (uint16_t)(i<<1), 2, 2);
 	  if (result != HAL_OK) // HAL_ERROR or HAL_BUSY or HAL_TIMEOUT
 	  {
 		  printf("."); // No ACK received at that address
 	  }
 	  if (result == HAL_OK)
 	  {
 		  printf("0x%X", i); // Received an ACK at that address
 	  }
 	}
 	printf("\r\n");
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		HAL_GPIO_TogglePin(GPIOE,GPIO_PIN_5);
		HAL_Delay(500);		
		HAL_GPIO_TogglePin(GPIOB,GPIO_PIN_5);
		
  }
  /* USER CODE END 3 */
}

工程源码

链接:https://pan.baidu.com/s/1ZsTskQ7EbXN0vHNeHYa-sQ 
提取码:vtgg

你可能感兴趣的:(stm32,stm32,12C扫描)