hal_i2c1.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include "hal_i2c1.h"
  2. void hal_i2c1_gpio_config(void)
  3. {
  4. RCC_AHB1PeriphClockCmd(HAL_I2C1_SCL_CLK, ENABLE);
  5. RCC_AHB1PeriphClockCmd(HAL_I2C1_SDA_CLK, ENABLE);
  6. GPIO_InitTypeDef GPIO_StructInit;
  7. GPIO_StructInit.GPIO_Mode = GPIO_Mode_AF;
  8. GPIO_StructInit.GPIO_OType = GPIO_OType_OD;
  9. GPIO_StructInit.GPIO_Speed = GPIO_Speed_100MHz;
  10. GPIO_StructInit.GPIO_Pin = HAL_I2C1_SCL_PIN;
  11. GPIO_PinAFConfig(HAL_I2C1_SCL_PORT, HAL_I2C1_SCL_SOURCE, GPIO_AF_I2C1);
  12. GPIO_Init(HAL_I2C1_SCL_PORT, &GPIO_StructInit);
  13. GPIO_PinAFConfig(HAL_I2C1_SDA_PORT, HAL_I2C1_SDA_SOURCE, GPIO_AF_I2C1);
  14. GPIO_StructInit.GPIO_Pin = HAL_I2C1_SDA_PIN;
  15. GPIO_Init(HAL_I2C1_SDA_PORT, &GPIO_StructInit);
  16. }
  17. void hal_i2c1_config(void)
  18. {
  19. RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
  20. I2C_InitTypeDef I2C_InitStructure;
  21. I2C_DeInit(I2C1);
  22. I2C_InitStructure.I2C_Ack = I2C_Ack_Enable; // I2C应答信号使能
  23. I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; // 设置从机地址长度为7位
  24. I2C_InitStructure.I2C_ClockSpeed = HAL_I2C1_SPEED; // 设置目标周期 400khz
  25. I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2; // 设置占空比为2:1
  26. I2C_InitStructure.I2C_Mode = I2C_Mode_I2C; // 设置为I2C模式
  27. I2C_InitStructure.I2C_OwnAddress1 = HAL_I2C1_ADDRESS; // 设置主机地址
  28. I2C_Init(I2C1, &I2C_InitStructure); // 初始化I2C1结构体
  29. I2C_Cmd(I2C1, ENABLE); // 使能I2C1
  30. }
  31. void hal_i2c1_init(void)
  32. {
  33. hal_i2c1_gpio_config();
  34. hal_i2c1_config();
  35. }