将 I2C 接口初始化用作从机和/或主机的代码
时间: 2024-01-15 07:03:41 浏览: 115
I2C通讯初始化例程
以下是使用STM32 HAL库将I2C接口初始化作为主机和/或从机的示例代码:
作为主机:
```c
I2C_HandleTypeDef hi2c;
void MX_I2C_Init(void)
{
hi2c.Instance = I2C1;
hi2c.Init.ClockSpeed = 100000;
hi2c.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c.Init.OwnAddress1 = 0;
hi2c.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c.Init.OwnAddress2 = 0;
hi2c.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c) != HAL_OK)
{
Error_Handler();
}
}
void I2C_WriteData(uint8_t DevAddress, uint8_t MemAddress, uint8_t *pData, uint16_t Size)
{
HAL_I2C_Mem_Write(&hi2c, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 1000);
}
void I2C_ReadData(uint8_t DevAddress, uint8_t MemAddress, uint8_t *pData, uint16_t Size)
{
HAL_I2C_Mem_Read(&hi2c, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 1000);
}
```
作为从机:
```c
I2C_HandleTypeDef hi2c;
void MX_I2C_Init(void)
{
hi2c.Instance = I2C1;
hi2c.Init.ClockSpeed = 100000;
hi2c.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c.Init.OwnAddress1 = 0x50; //设置从机地址为0x50
hi2c.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c.Init.OwnAddress2 = 0;
hi2c.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c) != HAL_OK)
{
Error_Handler();
}
HAL_I2C_EnableListen_IT(&hi2c); //使能从机监听
}
void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode)
{
if(TransferDirection == I2C_DIRECTION_RECEIVE)
{
//执行从机接收操作
}
else
{
//执行从机发送操作
}
}
void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c)
{
//从机发送完成回调函数
}
void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
{
//从机接收完成回调函数
}
```
以上示例代码中,主机初始化了I2C1接口,并提供了写入和读取函数。从机同样初始化了I2C1接口,并设置了从机地址为0x50,同时注册了从机回调函数以接收和发送数据。需要注意的是,从机回调函数的实现需要根据具体应用场景来编写。
阅读全文