STMCUBEMX_IIC_LL库/HAL库_扫描总线设备
前言:
在很多开发过程中,I2C总线上会挂载多个从机设备,但是又不知道设备的地址是多少,我做一个简单的小工具扫描总线,把地址打印出来就很方便
LL库实例:
void scanI2cDevice(I2C_TypeDef *I2Cx)
{
for(unsigned char dev_addr = 0; dev_addr < 0x7F; dev_addr++)//扫描I2C总线
{
volatile unsigned int overtime = 0;
LL_I2C_GenerateStartCondition(I2Cx);//起始信号
while (!LL_I2C_IsActiveFlag_SB(I2Cx) && (overtime < 10000))//起始信号发送完毕
{
overtime++;
}
if(overtime >= 10000)
{
Debug_printf("scanI2cDevice:%02x Start Error!\r\n",dev_addr << 1);
}
overtime = 0;
LL_I2C_TransmitData8(I2Cx, (dev_addr << 1) & 0xFE);//发送器件地址
while (!LL_I2C_IsActiveFlag_ADDR(I2Cx) && (overtime < 10000))//等待从机回应ACK
{
overtime++;
}
if(dev_addr%50 == 0)
{
Debug_printf("\r\n");
}
if(overtime >= 10000)
{
Debug_printf("-- ");
}
else
{
Debug_printf("%02x ",dev_addr << 1);
}
LL_I2C_ClearFlag_ADDR(I2Cx);
LL_mDelay(10);
}
Debug_printf("\r\n*************scan over***********\r\n");
}
HAL库实例:
void scanI2cDevice(I2C_HandleTypeDef* I2Cx)
{
HAL_StatusTypeDef result;
printf("\r\n*************start scan***********\r\n");
for(int addr = 0; addr < 0x7F; addr++)
{
result = HAL_I2C_IsDeviceReady(I2Cx, addr << 1, 3, 5);
if(result != HAL_OK)
{
if(addr%50 == 0)
{
printf( "--\r\n");
}
else
{
printf( "-- ");
}
}
if(result == HAL_OK)
{
printf("%02x ", addr);
}
}
printf("\r\n*************scan over***********\r\n");
}