at91_i2c_gpio.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2012-04-25 weety first version
  9. */
  10. #include <rtdevice.h>
  11. #include <rthw.h>
  12. #include <at91sam9g45.h>
  13. static void at91_i2c_gpio_init()
  14. {
  15. AT91C_BASE_PMC->PMC_PCER = 1 << AT91C_ID_PIOA; //enable PIOA clock
  16. AT91C_BASE_PIOA->PIO_PUER = (1 << 23);
  17. AT91C_BASE_PIOA->PIO_PER = (1 << 23);
  18. AT91C_BASE_PIOA->PIO_MDER = (1 << 23);
  19. AT91C_BASE_PIOA->PIO_PUER = (1 << 24);
  20. AT91C_BASE_PIOA->PIO_PER = (1 << 24);
  21. AT91C_BASE_PIOA->PIO_MDER = (1 << 24);
  22. AT91C_BASE_PIOA->PIO_OER = (1 << 23);
  23. AT91C_BASE_PIOA->PIO_OER = (1 << 24);
  24. AT91C_BASE_PIOA->PIO_SODR = (1 << 23);
  25. AT91C_BASE_PIOA->PIO_SODR = (1 << 24);
  26. }
  27. static void at91_set_sda(void *data, rt_int32_t state)
  28. {
  29. if (state)
  30. {
  31. AT91C_BASE_PIOA->PIO_SODR = (1 << 23);
  32. }
  33. else
  34. {
  35. AT91C_BASE_PIOA->PIO_CODR = (1 << 23);
  36. }
  37. }
  38. static void at91_set_scl(void *data, rt_int32_t state)
  39. {
  40. if (state)
  41. {
  42. AT91C_BASE_PIOA->PIO_SODR = (1 << 24);
  43. }
  44. else
  45. {
  46. AT91C_BASE_PIOA->PIO_CODR = (1 << 24);
  47. }
  48. }
  49. static rt_int32_t at91_get_sda(void *data)
  50. {
  51. return AT91C_BASE_PIOA->PIO_PDSR & (1 << 23);
  52. }
  53. static rt_int32_t at91_get_scl(void *data)
  54. {
  55. return AT91C_BASE_PIOA->PIO_PDSR & (1 << 24);
  56. }
  57. static void at91_udelay (rt_uint32_t us)
  58. {
  59. rt_int32_t i;
  60. for (; us > 0; us--)
  61. {
  62. i = 50000;
  63. while(i > 0)
  64. {
  65. i--;
  66. }
  67. }
  68. }
  69. static const struct rt_i2c_bit_ops bit_ops = {
  70. RT_NULL,
  71. at91_set_sda,
  72. at91_set_scl,
  73. at91_get_sda,
  74. at91_get_scl,
  75. at91_udelay,
  76. 5,
  77. 100
  78. };
  79. int at91_i2c_init(void)
  80. {
  81. struct rt_i2c_bus_device *bus;
  82. bus = rt_malloc(sizeof(struct rt_i2c_bus_device));
  83. if (bus == RT_NULL)
  84. {
  85. rt_kprintf("rt_malloc failed\n");
  86. return -RT_ENOMEM;
  87. }
  88. rt_memset((void *)bus, 0, sizeof(struct rt_i2c_bus_device));
  89. bus->priv = (void *)&bit_ops;
  90. at91_i2c_gpio_init();
  91. rt_i2c_bit_add_bus(bus, "i2c0");
  92. return 0;
  93. }
  94. INIT_DEVICE_EXPORT(at91_i2c_init);