drv_i2c.c 2.2 KB

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