STM32 I2C配置
主机配置
主机只要配置速度就行
从机配置
从机配置相同速度,可以设置第二地址
因为我的板子上面已经有了上拉电阻,所以可以直接通信
STM32 I2C DMA 定长主从通信代码示例
int state = 0;
static uint8_t I2C_recvBuf[10] = {0};
static uint8_t I2C_sendBuf[10] = {2,1,2,3,4,5,6,7,8,9};void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
{HAL_I2C_Slave_Receive_DMA(&hi2c1, I2C_recvBuf, 5);state = 1;
}// I2C 干扰检测
void I2C2_ER_IRQHandler(void)
{printf("ERROR I2C\r\n");HAL_I2C_Slave_Receive_DMA(&hi2c1, I2C_recvBuf, 5);HAL_I2C_ER_IRQHandler(&hi2c2);
}int main(void)
{HAL_Init();SystemClock_Config();MX_GPIO_Init();MX_DMA_Init();MX_I2C1_Init();MX_USART1_UART_Init();MX_I2C2_Init();printf("hello i2c stm32 \r\n");HAL_I2C_Slave_Receive_DMA(&hi2c1, I2C_recvBuf, 5);while (1){// 可以多地址接收数据HAL_I2C_Master_Transmit_DMA(&hi2c2, (20<<1)|0x01 ,I2C_sendBuf, 5);//HAL_I2C_Master_Transmit_DMA(&hi2c2, (10<<1)|0x01 ,I2C_sendBuf, 5);if(state == 1){state = 0;for (int i=0; i<4; i++){ printf("[%d]:%d", i, I2C_recvBuf[i]);}I2C_sendBuf[0] = I2C_sendBuf[0] + 1;if(I2C_sendBuf[0] > 100){I2C_sendBuf[0] = 0;}printf("\r\n");}HAL_Delay(1000);}
}
示例代码下载
https://download.csdn.net/download/hmxm6/89324145