#if I2C1_EN
/* 使能GPIO时钟 */
RCC_AHBPeriphClockCmd(I2C1_GPIO_RCC, ENABLE);
/* 使能I2C1时钟 */
RCC_APB1PeriphClockCmd(RCC_APB1PERIPH_I2C1, ENABLE);
/* 配置GPIO */
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_MaxSpeed = GPIO_MaxSpeed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; /* 复用功能 */
GPIO_InitStructure.GPIO_OutType = GPIO_OutType_OD;
GPIO_InitStructure.GPIO_Pull = GPIO_Pull_NOPULL;
/* SCL */
GPIO_InitStructure.GPIO_Pins = I2C1_SCL_PIN;
GPIO_Init(I2C1_SCL_PORT, &GPIO_InitStructure);
/* SDA */
GPIO_InitStructure.GPIO_Pins = I2C1_SDA_PIN;
GPIO_Init(I2C1_SDA_PORT, &GPIO_InitStructure);
/* 配置复用功能 */
GPIO_PinAFConfig(I2C1_SCL_PORT, I2C1_SCL_SOURCE, I2C1_SCL_AF);
GPIO_PinAFConfig(I2C1_SDA_PORT, I2C1_SDA_SOURCE, I2C1_SDA_AF);
/* 配置I2C1总线 */
I2C_StructInit(&I2C_InitStructure);
I2C_InitStructure.I2C_BitRate = I2C1_SPEED; /* I2C总线速度(最大400KHz) */
I2C_InitStructure.I2C_Mode = I2C_Mode_I2CDevice; /* I2C总线模式 */
I2C_InitStructure.I2C_FmDutyCycle = I2C_FmDutyCycle_2_1; /* I2C总线占空比 */
I2C_InitStructure.I2C_AddrMode = I2C_AddrMode_7bit; /* 7位地址模式 */
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable; /* 使能应答 */
I2C_Init(I2C1, &I2C_InitStructure);
/* 使能I2C */
I2C_Cmd(I2C1, ENABLE);
#endif |