[应用相关] HAL STM32F1硬件I2C扫描从设备地址

[复制链接]
1389|2
 楼主| tpgf 发表于 2024-4-9 09:26 | 显示全部楼层 |阅读模式
本帖最后由 tpgf 于 2024-4-9 09:32 编辑

利用硬件I2C接口扫描从设备地址是否在线,可以有效的帮助检测从设备是否在线,以及诊断从设备是否工作正常,以及用在快速查找设备I2C地址上。
扫描ssd1306 I2C oled屏幕地址:(0x78 = 0x3c << 1)
6713266149a8aa549d.png

扫描挂载的MPU6050地址:

8356366149a9140541.png

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

STM32CubeMX工程配置
指定一个12C接口,具体参数如下:

9332066149a98adae6.png

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
————————————————

                            本文为Perseverance52博主原创文章,未经博主允许,不得转载!

原文链接:https://blog.csdn.net/weixin_42880082/article/details/131869827


好几遍vh 发表于 2024-8-31 18:07 | 显示全部楼层
在STM32F1系列微控制器中,可以通过I2C扫描从设备的地址来确定I2C总线上的所有从设备。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

2384

主题

17635

帖子

21

粉丝
快速回复 在线客服 返回列表 返回顶部