@@ -217,32 +217,30 @@ void i2c_init(I2C_HandleTypeDef *i2c) {
217217 GPIO_InitStructure .Speed = GPIO_SPEED_FAST ;
218218 GPIO_InitStructure .Pull = GPIO_NOPULL ; // have external pull-up resistors on both lines
219219
220- const pyb_i2c_obj_t * self ;
221- const pin_obj_t * pins [2 ];
220+ int i2c_unit ;
221+ const pin_obj_t * scl_pin ;
222+ const pin_obj_t * sda_pin ;
222223
223224 if (0 ) {
224225 #if defined(MICROPY_HW_I2C1_SCL )
225226 } else if (i2c == & I2CHandle1 ) {
226- self = & pyb_i2c_obj [0 ];
227- pins [0 ] = & MICROPY_HW_I2C1_SCL ;
228- pins [1 ] = & MICROPY_HW_I2C1_SDA ;
229- GPIO_InitStructure .Alternate = GPIO_AF4_I2C1 ;
227+ i2c_unit = 1 ;
228+ scl_pin = & MICROPY_HW_I2C1_SCL ;
229+ sda_pin = & MICROPY_HW_I2C1_SDA ;
230230 __I2C1_CLK_ENABLE ();
231231 #endif
232232 #if defined(MICROPY_HW_I2C2_SCL )
233233 } else if (i2c == & I2CHandle2 ) {
234- self = & pyb_i2c_obj [1 ];
235- pins [0 ] = & MICROPY_HW_I2C2_SCL ;
236- pins [1 ] = & MICROPY_HW_I2C2_SDA ;
237- GPIO_InitStructure .Alternate = GPIO_AF4_I2C2 ;
234+ i2c_unit = 2 ;
235+ scl_pin = & MICROPY_HW_I2C2_SCL ;
236+ sda_pin = & MICROPY_HW_I2C2_SDA ;
238237 __I2C2_CLK_ENABLE ();
239238 #endif
240239 #if defined(MICROPY_HW_I2C3_SCL )
241240 } else if (i2c == & I2CHandle3 ) {
242- self = & pyb_i2c_obj [2 ];
243- pins [0 ] = & MICROPY_HW_I2C3_SCL ;
244- pins [1 ] = & MICROPY_HW_I2C3_SDA ;
245- GPIO_InitStructure .Alternate = GPIO_AF4_I2C3 ;
241+ i2c_unit = 3 ;
242+ scl_pin = & MICROPY_HW_I2C3_SCL ;
243+ sda_pin = & MICROPY_HW_I2C3_SDA ;
246244 __I2C3_CLK_ENABLE ();
247245 #endif
248246 } else {
@@ -251,11 +249,8 @@ void i2c_init(I2C_HandleTypeDef *i2c) {
251249 }
252250
253251 // init the GPIO lines
254- for (uint i = 0 ; i < 2 ; i ++ ) {
255- mp_hal_gpio_clock_enable (pins [i ]-> gpio );
256- GPIO_InitStructure .Pin = pins [i ]-> pin_mask ;
257- HAL_GPIO_Init (pins [i ]-> gpio , & GPIO_InitStructure );
258- }
252+ mp_hal_gpio_set_af (scl_pin , & GPIO_InitStructure , AF_FN_I2C , i2c_unit );
253+ mp_hal_gpio_set_af (sda_pin , & GPIO_InitStructure , AF_FN_I2C , i2c_unit );
259254
260255 // init the I2C device
261256 if (HAL_I2C_Init (i2c ) != HAL_OK ) {
@@ -267,6 +262,7 @@ void i2c_init(I2C_HandleTypeDef *i2c) {
267262 }
268263
269264 // invalidate the DMA channels so they are initialised on first use
265+ const pyb_i2c_obj_t * self = & pyb_i2c_obj [i2c_unit - 1 ];
270266 dma_invalidate_channel (self -> tx_dma_stream , self -> tx_dma_channel );
271267 dma_invalidate_channel (self -> rx_dma_stream , self -> rx_dma_channel );
272268}
0 commit comments