drv_i2c.c 2.2 KB

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