drv_pcf8574.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * File : drv_iic.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-09 tanek first implementation.
  13. */
  14. #include "drv_pcf8574.h"
  15. #include <board.h>
  16. #include <rthw.h>
  17. #include <finsh.h>
  18. //#define DEBUG
  19. #ifdef DEBUG
  20. #define DEBUG_PRINTF(...) rt_kprintf(__VA_ARGS__)
  21. #else
  22. #define DEBUG_PRINTF(...)
  23. #endif
  24. #define I2C_BUS_NAME "i2c0"
  25. #define PCF8574_ADDR 0x20
  26. static uint8_t rt_pcf8574_read_onebyte(void);
  27. static void rt_pcf8574_write_onebyte(rt_uint8_t value);
  28. static struct rt_i2c_bus_device * i2c_bus;
  29. rt_err_t rt_pcf8574_init(void)
  30. {
  31. rt_uint8_t buffer[] = { 0xFF };
  32. rt_off_t pos = PCF8574_ADDR;
  33. __HAL_RCC_GPIOB_CLK_ENABLE();
  34. i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(I2C_BUS_NAME);
  35. if (i2c_bus == RT_NULL)
  36. {
  37. DEBUG_PRINTF("\ni2c_bus %s for PCF8574 not found!\n", I2C_BUS_NAME);
  38. return -RT_ENOSYS;
  39. }
  40. if (rt_device_open(&i2c_bus->parent, RT_NULL) != RT_EOK)
  41. {
  42. DEBUG_PRINTF("\ni2c_bus %s for cs43l22 opened failed!\n", I2C_BUS_NAME);
  43. return -RT_EEMPTY;
  44. }
  45. rt_device_write(&i2c_bus->parent, pos, &buffer, 1);
  46. return RT_EOK;
  47. }
  48. static uint8_t rt_pcf8574_read_onebyte(void)
  49. {
  50. rt_uint8_t value;
  51. rt_device_read(&i2c_bus->parent, PCF8574_ADDR, &value, 1);
  52. return value;
  53. }
  54. static void rt_pcf8574_write_onebyte(rt_uint8_t value)
  55. {
  56. rt_device_write(&i2c_bus->parent, PCF8574_ADDR, &value, 1);
  57. }
  58. void rt_pcf8574_write_bit(rt_uint8_t bit, rt_uint8_t state)
  59. {
  60. rt_uint8_t data;
  61. data = rt_pcf8574_read_onebyte();
  62. if (state == 0)
  63. data &= ~(1 << bit);
  64. else
  65. data |= 1 << bit;
  66. rt_pcf8574_write_onebyte(data);
  67. }
  68. rt_uint8_t rt_pcf8574_read_bit(rt_uint8_t bit)
  69. {
  70. rt_uint8_t data;
  71. data = rt_pcf8574_read_onebyte();
  72. if (data&(1 << bit))
  73. return 1;
  74. else
  75. return 0;
  76. }