drv_pcf8574.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. * 2018-06-12 zylx the first version.
  9. */
  10. #include "drv_pcf8574.h"
  11. #define PCF8574_I2CBUS_NAME "i2c1"
  12. static struct rt_i2c_bus_device *pcf8574_i2c_bus;
  13. int pcf8574_Init(void)
  14. {
  15. rt_uint8_t value = 0x01;
  16. pcf8574_i2c_bus = rt_i2c_bus_device_find(PCF8574_I2CBUS_NAME);
  17. if (pcf8574_i2c_bus == RT_NULL)
  18. {
  19. rt_kprintf("can't find i2c device\r\n");
  20. return -RT_ERROR;
  21. }
  22. if (!rt_i2c_master_send(pcf8574_i2c_bus, PCF8574_ADDR, 0, &value, 1))
  23. {
  24. rt_kprintf("can't find pcf8574\r\n");
  25. return -RT_ERROR;
  26. }
  27. return 0;
  28. }
  29. INIT_COMPONENT_EXPORT(pcf8574_Init);
  30. rt_uint8_t pcf8574_read_byte(void)
  31. {
  32. rt_uint8_t temp = 0;
  33. rt_i2c_master_recv(pcf8574_i2c_bus, PCF8574_ADDR, 0, &temp, 1);
  34. return temp;
  35. }
  36. void pcf8574_write_byte(rt_uint8_t data)
  37. {
  38. rt_i2c_master_send(pcf8574_i2c_bus, PCF8574_ADDR, 0, &data, 1);
  39. }
  40. void pcf8574_write_bit(rt_uint8_t bit, rt_uint8_t sta)
  41. {
  42. rt_uint8_t data;
  43. data = pcf8574_read_byte();
  44. if (sta == 0)data &= ~(1 << bit);
  45. else data |= 1 << bit;
  46. pcf8574_write_byte(data);
  47. }
  48. rt_uint8_t pcf8574_read_bit(rt_uint8_t bit)
  49. {
  50. rt_uint8_t data;
  51. data = pcf8574_read_byte();
  52. if (data & (1 << bit))return 1;
  53. else return 0;
  54. }