12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- #include "hal_i2c1.h"
- void hal_i2c1_gpio_config(void)
- {
- RCC_AHB1PeriphClockCmd(HAL_I2C1_SCL_CLK, ENABLE);
- RCC_AHB1PeriphClockCmd(HAL_I2C1_SDA_CLK, ENABLE);
- GPIO_InitTypeDef GPIO_StructInit;
- GPIO_StructInit.GPIO_Mode = GPIO_Mode_AF;
- GPIO_StructInit.GPIO_OType = GPIO_OType_OD;
- GPIO_StructInit.GPIO_Speed = GPIO_Speed_100MHz;
- GPIO_StructInit.GPIO_Pin = HAL_I2C1_SCL_PIN;
- GPIO_PinAFConfig(HAL_I2C1_SCL_PORT, HAL_I2C1_SCL_SOURCE, GPIO_AF_I2C1);
- GPIO_Init(HAL_I2C1_SCL_PORT, &GPIO_StructInit);
- GPIO_PinAFConfig(HAL_I2C1_SDA_PORT, HAL_I2C1_SDA_SOURCE, GPIO_AF_I2C1);
- GPIO_StructInit.GPIO_Pin = HAL_I2C1_SDA_PIN;
- GPIO_Init(HAL_I2C1_SDA_PORT, &GPIO_StructInit);
- }
- void hal_i2c1_config(void)
- {
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
- I2C_InitTypeDef I2C_InitStructure;
- I2C_DeInit(I2C1);
- I2C_InitStructure.I2C_Ack = I2C_Ack_Enable; // I2C应答信号使能
- I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; // 设置从机地址长度为7位
- I2C_InitStructure.I2C_ClockSpeed = HAL_I2C1_SPEED; // 设置目标周期 400khz
- I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2; // 设置占空比为2:1
- I2C_InitStructure.I2C_Mode = I2C_Mode_I2C; // 设置为I2C模式
- I2C_InitStructure.I2C_OwnAddress1 = HAL_I2C1_ADDRESS; // 设置主机地址
- I2C_Init(I2C1, &I2C_InitStructure); // 初始化I2C1结构体
- I2C_Cmd(I2C1, ENABLE); // 使能I2C1
- }
- void hal_i2c1_init(void)
- {
- hal_i2c1_gpio_config();
- hal_i2c1_config();
- }
|