pca9555.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "i2c_master.h"
  2. #include "pca9555.h"
  3. #include "debug.h"
  4. #define SLAVE_TO_ADDR(n) (n<<1)
  5. #define TIMEOUT 100
  6. enum {
  7. CMD_INPUT_0 = 0,
  8. CMD_INPUT_1,
  9. CMD_OUTPUT_0,
  10. CMD_OUTPUT_1,
  11. CMD_INVERSION_0,
  12. CMD_INVERSION_1,
  13. CMD_CONFIG_0,
  14. CMD_CONFIG_1
  15. };
  16. void pca9555_init(uint8_t slave_addr) {
  17. static uint8_t s_init = 0;
  18. if (!s_init) {
  19. i2c_init();
  20. s_init=1;
  21. }
  22. // TODO: could check device connected
  23. //i2c_start(SLAVE_TO_ADDR(slave) | I2C_WRITE);
  24. //i2c_stop();
  25. }
  26. void pca9555_set_config(uint8_t slave_addr, uint8_t port, uint8_t conf) {
  27. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  28. uint8_t cmd = port ? CMD_OUTPUT_1 : CMD_OUTPUT_0;
  29. i2c_status_t ret = i2c_writeReg(addr, cmd, &conf, sizeof(conf), TIMEOUT);
  30. if (ret != I2C_STATUS_SUCCESS) {
  31. print("pca9555_set_config::FAILED\n");
  32. }
  33. }
  34. void pca9555_set_output(uint8_t slave_addr, uint8_t port, uint8_t conf) {
  35. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  36. uint8_t cmd = port ? CMD_CONFIG_1 : CMD_CONFIG_0;
  37. i2c_status_t ret = i2c_writeReg(addr, cmd, &conf, sizeof(conf), TIMEOUT);
  38. if (ret != I2C_STATUS_SUCCESS) {
  39. print("pca9555_set_output::FAILED\n");
  40. }
  41. }
  42. uint8_t pca9555_readPins(uint8_t slave_addr, uint8_t port) {
  43. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  44. uint8_t cmd = port ? CMD_INPUT_1 : CMD_INPUT_0;
  45. uint8_t data = 0;
  46. i2c_status_t ret = i2c_readReg(addr, cmd, &data, sizeof(data), TIMEOUT);
  47. if (ret != I2C_STATUS_SUCCESS) {
  48. print("pca9555_readPins::FAILED\n");
  49. }
  50. return data;
  51. }