Difference between revisions of "STM32 Scan I²C bus"

From Stm32World Wiki
Jump to navigation Jump to search
Line 1: Line 1:
 
[[Category:STM32]][[Category:STM32 Development]][[Category:STM32CubeMX]][[Category:STM32CubeIde]][[Category:STM32 HAL]][[Category:I²C]]{{metadesc|How to scan an I2C bus using STM32 HAL}}
 
[[Category:STM32]][[Category:STM32 Development]][[Category:STM32CubeMX]][[Category:STM32CubeIde]][[Category:STM32 HAL]][[Category:I²C]]{{metadesc|How to scan an I2C bus using STM32 HAL}}
Scanning an [[I2C]] bus using HAL is really simple.  First configure [[I²C]] in [[Stm32CubeMX]]:
+
Scanning an [[I2C]] bus using HAL is really simple.  First configure [[I²C]] in [[STM32CubeMX]]:
  
 
[[File:I2c Config.png|400px]]
 
[[File:I2c Config.png|400px]]

Revision as of 04:24, 4 June 2021

Scanning an I2C bus using HAL is really simple. First configure I²C in STM32CubeMX:

I2c Config.png

Once the I²C 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 -- -- -- -- -- -- -- -- 

Notice that I²C addresses are a bit peculiar.

I²C 7-bit Addresses.png

The address itself is shifted 1 bit left and the last (LSB) bit indicates read or write. So - if looking at the above table:

0x1e = 30 = 0b00011110

0b00011110 << 1 = 60 = 0x3c

So for use with the HAL_I2C commands, shift the address left by one bit. The HAL library will control the read/write bit.