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