drv_i2c.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /*
  2. * File : drv_iic.c
  3. * This file is part of RT-Thread RTOS
  4. * COPYRIGHT (C) 2017 RT-Thread Develop Team
  5. *
  6. * The license and distribution terms for this file may be
  7. * found in the file LICENSE in this distribution or at
  8. * http://www.rt-thread.org/license/LICENSE
  9. *
  10. * Change Logs:
  11. * Date Author Notes
  12. * 2017-06-05 tanek first implementation.
  13. */
  14. #include "drv_i2c.h"
  15. #include <board.h>
  16. #include <finsh.h>
  17. #include <rtdevice.h>
  18. #include <rthw.h>
  19. #define DEBUG
  20. #ifdef DEBUG
  21. #define DEBUG_PRINTF(...) rt_kprintf(__VA_ARGS__)
  22. #else
  23. #define DEBUG_PRINTF(...)
  24. #endif
  25. #define I2C_SCL_PIN GPIO_PIN_6
  26. #define I2C_SCL_PORT GPIOB
  27. #define I2C_SCL_PORT_CLK_ENABLE() __HAL_RCC_GPIOB_CLK_ENABLE()
  28. #define I2C_SDA_PIN GPIO_PIN_9
  29. #define I2C_SDA_PORT GPIOB
  30. #define I2C_SDL_PORT_CLK_ENABLE()
  31. static struct rt_i2c_bus_device i2c_bus;
  32. static void stm32f4_i2c_gpio_init()
  33. {
  34. GPIO_InitTypeDef GPIO_Initure;
  35. I2C_SCL_PORT_CLK_ENABLE();
  36. I2C_SDL_PORT_CLK_ENABLE();
  37. GPIO_Initure.Pin = I2C_SCL_PIN | I2C_SDA_PIN;
  38. GPIO_Initure.Mode = GPIO_MODE_OUTPUT_OD;
  39. GPIO_Initure.Pull = GPIO_NOPULL;
  40. GPIO_Initure.Speed = GPIO_SPEED_HIGH;
  41. HAL_GPIO_Init(I2C_SDA_PORT, &GPIO_Initure);
  42. HAL_GPIO_WritePin(I2C_SDA_PORT, I2C_SDA_PIN, GPIO_PIN_SET);
  43. HAL_GPIO_WritePin(I2C_SCL_PORT, I2C_SCL_PIN, GPIO_PIN_SET);
  44. }
  45. static void stm32f4_set_sda(void *data, rt_int32_t state)
  46. {
  47. HAL_GPIO_WritePin(I2C_SDA_PORT, I2C_SDA_PIN, (GPIO_PinState)state);
  48. }
  49. static void stm32f4_set_scl(void *data, rt_int32_t state)
  50. {
  51. HAL_GPIO_WritePin(I2C_SCL_PORT, I2C_SCL_PIN, (GPIO_PinState)state);
  52. }
  53. static rt_int32_t stm32f4_get_sda(void *data)
  54. {
  55. return (rt_int32_t)HAL_GPIO_ReadPin(I2C_SDA_PORT, I2C_SDA_PIN);
  56. }
  57. static rt_int32_t stm32f4_get_scl(void *data)
  58. {
  59. return (rt_int32_t)HAL_GPIO_ReadPin(I2C_SCL_PORT, I2C_SCL_PIN);
  60. }
  61. static void stm32f4_udelay(rt_uint32_t us)
  62. {
  63. rt_int32_t i;
  64. for (; us > 0; us--)
  65. {
  66. i = 50;
  67. while (i > 0)
  68. {
  69. i--;
  70. }
  71. }
  72. }
  73. static const struct rt_i2c_bit_ops bit_ops = {
  74. RT_NULL,
  75. stm32f4_set_sda,
  76. stm32f4_set_scl,
  77. stm32f4_get_sda,
  78. stm32f4_get_scl,
  79. stm32f4_udelay,
  80. 50,
  81. 100
  82. };
  83. int stm32f4_i2c_init(void)
  84. {
  85. i2c_bus.priv = (void *)&bit_ops;
  86. stm32f4_i2c_gpio_init();
  87. rt_i2c_bit_add_bus(&i2c_bus, "i2c0");
  88. return RT_EOK;
  89. }
  90. INIT_DEVICE_EXPORT(stm32f4_i2c_init);