STM32 Scan I²C bus

From Stm32World Wiki
Revision as of 04:41, 4 June 2021 by Lth (talk | contribs) (Created page with "Category:STM32Category:STM32 DevelopmentCategory:STM32CubeMXCategory:STM32CubeIdeCategory:STM32 HALCategory:I2C{{metadesc|How to scan an I2C bus using...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Scanning an I2C bus using HAL is really simple. First configure I2C in Stm32CubeMX:

I2c Config.png

Once the I2C has been configured, scanning the bus for slaves become a simple matter:

// Go through all possible i2c addresses
  for (uint8_t i = 0; i < 128; i++) {

	  if (HAL_I2C_IsDeviceReady(&hi2c1, (uint16_t)(i<<1), 3, 5) == HAL_OK) {
		  // We got an ack
		  printf("%2x ", i);
	  } else {
		  printf("-- ");
	  }

	  if (i > 0 && (i + 1) % 16 == 0) printf("\n");

  }

  printf("\n");

The HAL_I2C_IsDeviceReady will return HAL_OK if it receives an ACK or an error if not.

Output from above could be:

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
-- -- -- -- -- -- -- -- -- -- -- -- -- -- 1e -- 
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
-- -- -- 53 -- -- -- -- -- -- -- -- -- -- -- -- 
-- -- -- -- -- -- -- -- 68 -- -- -- -- -- -- -- 
-- -- -- -- -- -- -- 77 -- -- -- -- -- -- -- --