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.

104 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. }
  26. bool pca9555_set_config(uint8_t slave_addr, pca9555_port_t port, uint8_t conf) {
  27. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  28. uint8_t cmd = port ? CMD_CONFIG_1 : CMD_CONFIG_0;
  29. i2c_status_t ret = i2c_write_register(addr, cmd, &conf, sizeof(conf), TIMEOUT);
  30. if (ret != I2C_STATUS_SUCCESS) {
  31. print("pca9555_set_config::FAILED\n");
  32. return false;
  33. }
  34. return true;
  35. }
  36. bool pca9555_set_output(uint8_t slave_addr, pca9555_port_t port, uint8_t conf) {
  37. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  38. uint8_t cmd = port ? CMD_OUTPUT_1 : CMD_OUTPUT_0;
  39. i2c_status_t ret = i2c_write_register(addr, cmd, &conf, sizeof(conf), TIMEOUT);
  40. if (ret != I2C_STATUS_SUCCESS) {
  41. print("pca9555_set_output::FAILED\n");
  42. return false;
  43. }
  44. return true;
  45. }
  46. bool pca9555_set_output_all(uint8_t slave_addr, uint8_t confA, uint8_t confB) {
  47. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  48. uint8_t conf[2] = {confA, confB};
  49. i2c_status_t ret = i2c_write_register(addr, CMD_OUTPUT_0, &conf[0], sizeof(conf), TIMEOUT);
  50. if (ret != I2C_STATUS_SUCCESS) {
  51. dprintf("pca9555_set_output::FAILED::%u\n", ret);
  52. return false;
  53. }
  54. return true;
  55. }
  56. bool pca9555_readPins(uint8_t slave_addr, pca9555_port_t port, uint8_t* out) {
  57. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  58. uint8_t cmd = port ? CMD_INPUT_1 : CMD_INPUT_0;
  59. i2c_status_t ret = i2c_read_register(addr, cmd, out, sizeof(uint8_t), TIMEOUT);
  60. if (ret != I2C_STATUS_SUCCESS) {
  61. print("pca9555_readPins::FAILED\n");
  62. return false;
  63. }
  64. return true;
  65. }
  66. bool pca9555_readPins_all(uint8_t slave_addr, uint16_t* out) {
  67. uint8_t addr = SLAVE_TO_ADDR(slave_addr);
  68. typedef union {
  69. uint8_t u8[2];
  70. uint16_t u16;
  71. } data16;
  72. data16 data = {.u16 = 0};
  73. i2c_status_t ret = i2c_read_register(addr, CMD_INPUT_0, &data.u8[0], sizeof(data), TIMEOUT);
  74. if (ret != I2C_STATUS_SUCCESS) {
  75. print("pca9555_readPins_all::FAILED\n");
  76. return false;
  77. }
  78. *out = data.u16;
  79. return true;
  80. }