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.0 KiB

  1. #include <stdbool.h>
  2. #include "action.h"
  3. #include "i2c_master.h"
  4. #include "expander.h"
  5. #include "debug.h"
  6. #define I2C_TIMEOUT 100
  7. static uint8_t expander_status = 0;
  8. static uint8_t expander_input = 0;
  9. void expander_config(void);
  10. uint8_t expander_write(uint8_t reg, uint8_t data);
  11. uint8_t expander_read(uint8_t reg, uint8_t *data);
  12. void expander_init(void)
  13. {
  14. i2c_init();
  15. expander_scan();
  16. }
  17. void expander_scan(void)
  18. {
  19. dprintf("expander status: %d ... ", expander_status);
  20. uint8_t ret = i2c_start(EXPANDER_ADDR | I2C_WRITE, I2C_TIMEOUT);
  21. if (ret == 0) {
  22. i2c_stop();
  23. if (expander_status == 0) {
  24. dprintf("attached\n");
  25. expander_status = 1;
  26. expander_config();
  27. clear_keyboard();
  28. }
  29. }
  30. else {
  31. if (expander_status == 1) {
  32. dprintf("detached\n");
  33. expander_status = 0;
  34. clear_keyboard();
  35. }
  36. }
  37. dprintf("%d\n", expander_status);
  38. }
  39. void expander_read_cols(void)
  40. {
  41. expander_read(EXPANDER_REG_GPIOA, &expander_input);
  42. }
  43. uint8_t expander_get_col(uint8_t col)
  44. {
  45. if (col > 4) {
  46. col++;
  47. }
  48. return expander_input & (1<<col) ? 1 : 0;
  49. }
  50. matrix_row_t expander_read_row(void)
  51. {
  52. expander_read_cols();
  53. /* make cols */
  54. matrix_row_t cols = 0;
  55. for (uint8_t col = 0; col < MATRIX_COLS; col++) {
  56. if (expander_get_col(col)) {
  57. cols |= (1UL << (MATRIX_COLS - 1 - col));
  58. }
  59. }
  60. return cols;
  61. }
  62. void expander_unselect_rows(void)
  63. {
  64. expander_write(EXPANDER_REG_IODIRB, 0xFF);
  65. }
  66. void expander_select_row(uint8_t row)
  67. {
  68. expander_write(EXPANDER_REG_IODIRB, ~(1<<(row+1)));
  69. }
  70. void expander_config(void)
  71. {
  72. expander_write(EXPANDER_REG_IPOLA, 0xFF);
  73. expander_write(EXPANDER_REG_GPPUA, 0xFF);
  74. expander_write(EXPANDER_REG_IODIRB, 0xFF);
  75. }
  76. uint8_t expander_write(uint8_t reg, uint8_t data)
  77. {
  78. if (expander_status == 0) {
  79. return 0;
  80. }
  81. return i2c_writeReg(EXPANDER_ADDR, reg, &data, 1, I2C_TIMEOUT);
  82. }
  83. uint8_t expander_read(uint8_t reg, uint8_t *data)
  84. {
  85. if (expander_status == 0) {
  86. return 0;
  87. }
  88. return i2c_readReg(EXPANDER_ADDR, reg, data, 1, I2C_TIMEOUT);
  89. }