You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.6 KiB

  1. // Copyright 2020 zvecr<git@zvecr.com>
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "i2c_master.h"
  4. #include "pca9555.h"
  5. #include "debug.h"
  6. #define SLAVE_TO_ADDR(n) (n << 1)
  7. #define TIMEOUT 100
  8. enum {
  9. CMD_INPUT_0 = 0,
  10. CMD_INPUT_1,
  11. CMD_OUTPUT_0,
  12. CMD_OUTPUT_1,
  13. CMD_INVERSION_0,
  14. CMD_INVERSION_1,
  15. CMD_CONFIG_0,
  16. CMD_CONFIG_1,
  17. };
  18. void pca9555_init(uint8_t slave_addr) {
  19. static uint8_t s_init = 0;
  20. if (!s_init) {
  21. i2c_init();
  22. s_init = 1;
  23. }
  24. // TODO: could check device connected
  25. // i2c_start(SLAVE_TO_ADDR(slave) | I2C_WRITE);
  26. // i2c_stop();
  27. }
  28. bool pca9555_set_config(uint8_t slave_addr, pca9555_port_t port, uint8_t conf) {
  29. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  30. uint8_t cmd = port ? CMD_CONFIG_1 : CMD_CONFIG_0;
  31. i2c_status_t ret = i2c_writeReg(addr, cmd, &conf, sizeof(conf), TIMEOUT);
  32. if (ret != I2C_STATUS_SUCCESS) {
  33. print("pca9555_set_config::FAILED\n");
  34. return false;
  35. }
  36. return true;
  37. }
  38. bool pca9555_set_output(uint8_t slave_addr, pca9555_port_t port, uint8_t conf) {
  39. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  40. uint8_t cmd = port ? CMD_OUTPUT_1 : CMD_OUTPUT_0;
  41. i2c_status_t ret = i2c_writeReg(addr, cmd, &conf, sizeof(conf), TIMEOUT);
  42. if (ret != I2C_STATUS_SUCCESS) {
  43. print("pca9555_set_output::FAILED\n");
  44. return false;
  45. }
  46. return true;
  47. }
  48. bool pca9555_set_output_all(uint8_t slave_addr, uint8_t confA, uint8_t confB) {
  49. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  50. uint8_t conf[2] = {confA, confB};
  51. i2c_status_t ret = i2c_writeReg(addr, CMD_OUTPUT_0, &conf[0], sizeof(conf), TIMEOUT);
  52. if (ret != I2C_STATUS_SUCCESS) {
  53. dprintf("pca9555_set_output::FAILED::%u\n", ret);
  54. return false;
  55. }
  56. return true;
  57. }
  58. bool pca9555_readPins(uint8_t slave_addr, pca9555_port_t port, uint8_t* out) {
  59. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  60. uint8_t cmd = port ? CMD_INPUT_1 : CMD_INPUT_0;
  61. i2c_status_t ret = i2c_readReg(addr, cmd, out, sizeof(uint8_t), TIMEOUT);
  62. if (ret != I2C_STATUS_SUCCESS) {
  63. print("pca9555_readPins::FAILED\n");
  64. return false;
  65. }
  66. return true;
  67. }
  68. bool pca9555_readPins_all(uint8_t slave_addr, uint16_t* out) {
  69. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  70. typedef union {
  71. uint8_t u8[2];
  72. uint16_t u16;
  73. } data16;
  74. data16 data = {.u16 = 0};
  75. i2c_status_t ret = i2c_readReg(addr, CMD_INPUT_0, &data.u8[0], sizeof(data), TIMEOUT);
  76. if (ret != I2C_STATUS_SUCCESS) {
  77. print("pca9555_readPins_all::FAILED\n");
  78. return false;
  79. }
  80. *out = data.u16;
  81. return true;
  82. }