drv_i2c.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. static void stm32f4_i2c_gpio_init()
  22. {
  23. GPIO_InitTypeDef GPIO_Initure;
  24. __HAL_RCC_GPIOA_CLK_ENABLE();
  25. __HAL_RCC_GPIOC_CLK_ENABLE();
  26. GPIO_Initure.Pin = GPIO_PIN_8;
  27. GPIO_Initure.Mode = GPIO_MODE_OUTPUT_OD;
  28. GPIO_Initure.Pull = GPIO_PULLUP;
  29. GPIO_Initure.Speed = GPIO_SPEED_FAST;
  30. HAL_GPIO_Init(GPIOA, &GPIO_Initure);
  31. GPIO_Initure.Pin = GPIO_PIN_9;
  32. GPIO_Initure.Mode = GPIO_MODE_OUTPUT_OD;
  33. GPIO_Initure.Pull = GPIO_PULLUP;
  34. GPIO_Initure.Speed = GPIO_SPEED_FAST;
  35. HAL_GPIO_Init(GPIOC, &GPIO_Initure);
  36. HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
  37. HAL_GPIO_WritePin(GPIOC, GPIO_PIN_9, GPIO_PIN_SET);
  38. }
  39. static void stm32f4_set_sda(void *data, rt_int32_t state)
  40. {
  41. HAL_GPIO_WritePin(GPIOC, GPIO_PIN_9, (GPIO_PinState)state);
  42. }
  43. static void stm32f4_set_scl(void *data, rt_int32_t state)
  44. {
  45. HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, (GPIO_PinState)state);
  46. }
  47. static rt_int32_t stm32f4_get_sda(void *data)
  48. {
  49. return (rt_int32_t)HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_9);
  50. }
  51. static rt_int32_t stm32f4_get_scl(void *data)
  52. {
  53. return (rt_int32_t)HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_8);
  54. }
  55. static void stm32f4_udelay(rt_uint32_t us)
  56. {
  57. rt_int32_t i;
  58. for (; us > 0; us--)
  59. {
  60. i = 50;
  61. while (i > 0)
  62. {
  63. i--;
  64. }
  65. }
  66. }
  67. static const struct rt_i2c_bit_ops bit_ops = {
  68. RT_NULL,
  69. stm32f4_set_sda,
  70. stm32f4_set_scl,
  71. stm32f4_get_sda,
  72. stm32f4_get_scl,
  73. stm32f4_udelay,
  74. 5,
  75. 100
  76. };
  77. int stm32f4_i2c_init(void)
  78. {
  79. struct rt_i2c_bus_device *bus;
  80. bus = rt_malloc(sizeof(struct rt_i2c_bus_device));
  81. if (bus == RT_NULL)
  82. {
  83. rt_kprintf("rt_malloc failed\n");
  84. return -RT_ENOMEM;
  85. }
  86. rt_memset((void *)bus, 0, sizeof(struct rt_i2c_bus_device));
  87. bus->priv = (void *)&bit_ops;
  88. stm32f4_i2c_gpio_init();
  89. rt_i2c_bit_add_bus(bus, "i2c3");
  90. return RT_EOK;
  91. }
  92. INIT_DEVICE_EXPORT(stm32f4_i2c_init);