drv_pcf8574.c 1.6 KB

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