#include "i2c1.h"

void i2c1_gpio_config(void)
{
    RCC_AHB1PeriphClockCmd(I2C1_SCL_CLK, ENABLE);
    RCC_AHB1PeriphClockCmd(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   = I2C1_SCL_PIN;
    GPIO_PinAFConfig(I2C1_SCL_PORT, I2C1_SCL_SOURCE, GPIO_AF_I2C1);
    GPIO_Init(I2C1_SCL_PORT, &GPIO_StructInit);

    GPIO_PinAFConfig(I2C1_SDA_PORT, I2C1_SDA_SOURCE, GPIO_AF_I2C1);
    GPIO_StructInit.GPIO_Pin = I2C1_SDA_PIN;
    GPIO_Init(I2C1_SDA_PORT, &GPIO_StructInit);
}
void 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          = I2C1_SPEED;                   // 设置目标周期 400khz
    I2C_InitStructure.I2C_DutyCycle           = I2C_DutyCycle_2;              // 设置占空比为2：1
    I2C_InitStructure.I2C_Mode                = I2C_Mode_I2C;                 // 设置为I2C模式
    I2C_InitStructure.I2C_OwnAddress1         = I2C1_ADDRESS;                 // 设置主机地址

    I2C_Init(I2C1, &I2C_InitStructure); // 初始化I2C1结构体

    I2C_Cmd(I2C1, ENABLE); // 使能I2C1
}

void i2c1_init(void)
{
    i2c1_gpio_config();
    i2c1_config();
}