1
0

drv_pcf8574.c 1.8 KB

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