i2c.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "i2c.h"
  2. #include <stm32f10x.h>
  3. void stm32_set_sda(void *data, rt_int32_t state)
  4. {
  5. if(state == 1)
  6. GPIO_SetBits(I2C1_GPIO , I2C1_GPIO_SDA); //GPIOB->BSRRL = I2C1_GPIO_SDA
  7. else if(state == 0)
  8. GPIO_ResetBits(I2C1_GPIO , I2C1_GPIO_SDA); //GPIOB->BSRRH = I2C1_GPIO_SDA
  9. }
  10. void stm32_set_scl(void *data, rt_int32_t state)
  11. {
  12. if(state == 1)
  13. GPIO_SetBits(I2C1_GPIO , I2C1_GPIO_SCL); //GPIOB->BSRRL = I2C1_GPIO_SCL
  14. else if(state == 0)
  15. GPIO_ResetBits(I2C1_GPIO , I2C1_GPIO_SCL); //GPIOB->BSRRH = I2C1_GPIO_SCL
  16. }
  17. rt_int32_t stm32_get_sda(void *data)
  18. {
  19. return (rt_int32_t)GPIO_ReadInputDataBit(I2C1_GPIO , I2C1_GPIO_SDA); //return(GPIOB->IDR & I2C1_GPIO_SDA)
  20. }
  21. rt_int32_t stm32_get_scl(void *data)
  22. {
  23. return (rt_int32_t)GPIO_ReadInputDataBit(I2C1_GPIO , I2C1_GPIO_SCL); //return(GPIOB->IDR & I2C1_GPIO_SCL)
  24. }
  25. void stm32_udelay(rt_uint32_t us)
  26. {
  27. rt_uint32_t delta;
  28. /* sysTick->LOAD=21000, RT_TICK_PER_SECOND=1000 */
  29. us = us * (SysTick->LOAD/(1000000/RT_TICK_PER_SECOND));
  30. delta = SysTick->VAL;
  31. /* delay us */
  32. while (delta - SysTick->VAL< us);
  33. }
  34. void stm32_mdelay(rt_uint32_t ms)
  35. {
  36. stm32_udelay(ms * 1000);
  37. }
  38. static const struct rt_i2c_bit_ops stm32_i2c_bit_ops =
  39. {
  40. (void*)0xaa, //no use in set_sda,set_scl,get_sda,get_scl
  41. stm32_set_sda,
  42. stm32_set_scl,
  43. stm32_get_sda,
  44. stm32_get_scl,
  45. stm32_udelay,
  46. 20,
  47. };
  48. static void RCC_Configuration(void)
  49. {
  50. RCC->APB2ENR|=1<<4;
  51. RCC_APB2PeriphClockCmd( RCC_I2C, ENABLE );
  52. }
  53. static void GPIO_Configuration(void)
  54. {
  55. GPIO_InitTypeDef GPIO_InitStructure;
  56. GPIO_InitStructure.GPIO_Pin = I2C1_GPIO_SDA | I2C1_GPIO_SCL;
  57. GPIO_InitStructure.GPIO_Mode =GPIO_Mode_Out_OD ;
  58. GPIO_InitStructure.GPIO_Speed =GPIO_Speed_50MHz;
  59. GPIO_Init(I2C1_GPIO, &GPIO_InitStructure);
  60. }
  61. int rt_hw_i2c_init(void)
  62. {
  63. static struct rt_i2c_bus_device stm32_i2c;
  64. RCC_Configuration();
  65. GPIO_Configuration();
  66. rt_memset((void *)&stm32_i2c, 0, sizeof(struct rt_i2c_bus_device));
  67. stm32_i2c.priv = (void *)&stm32_i2c_bit_ops;
  68. rt_i2c_bit_add_bus(&stm32_i2c, "i2c1");
  69. return 0;
  70. }
  71. INIT_BOARD_EXPORT(rt_hw_i2c_init);