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. /*
  2. Copyright 2017 Luiz Ribeiro <luizribeiro@gmail.com>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <avr/io.h>
  15. #include <util/delay.h>
  16. #include "matrix.h"
  17. #ifndef DEBOUNCE
  18. # define DEBOUNCE 5
  19. #endif
  20. static uint8_t debouncing = DEBOUNCE;
  21. static matrix_row_t matrix[MATRIX_ROWS];
  22. static matrix_row_t matrix_debouncing[MATRIX_ROWS];
  23. void matrix_init(void) {
  24. // all outputs for rows high
  25. DDRB = 0xFF;
  26. PORTB = 0xFF;
  27. // all inputs for columns
  28. DDRA = 0x00;
  29. DDRC &= ~(0x111111<<2);
  30. DDRD &= ~(1<<PIND7);
  31. // all columns are pulled-up
  32. PORTA = 0xFF;
  33. PORTC |= (0b111111<<2);
  34. PORTD |= (1<<PIND7);
  35. // initialize matrix state: all keys off
  36. for (uint8_t row = 0; row < MATRIX_ROWS; row++) {
  37. matrix[row] = 0x00;
  38. matrix_debouncing[row] = 0x00;
  39. }
  40. }
  41. void matrix_set_row_status(uint8_t row) {
  42. DDRB = (1 << row);
  43. PORTB = ~(1 << row);
  44. }
  45. uint8_t bit_reverse(uint8_t x) {
  46. x = ((x >> 1) & 0x55) | ((x << 1) & 0xaa);
  47. x = ((x >> 2) & 0x33) | ((x << 2) & 0xcc);
  48. x = ((x >> 4) & 0x0f) | ((x << 4) & 0xf0);
  49. return x;
  50. }
  51. uint8_t matrix_scan(void) {
  52. for (uint8_t row = 0; row < MATRIX_ROWS; row++) {
  53. matrix_set_row_status(row);
  54. _delay_us(5);
  55. matrix_row_t cols = (
  56. // cols 0..7, PORTA 0 -> 7
  57. (~PINA) & 0xFF
  58. ) | (
  59. // cols 8..13, PORTC 7 -> 0
  60. bit_reverse((~PINC) & 0xFF) << 8
  61. ) | (
  62. // col 14, PORTD 7
  63. ((~PIND) & (1 << PIND7)) << 7
  64. );
  65. if (matrix_debouncing[row] != cols) {
  66. matrix_debouncing[row] = cols;
  67. debouncing = DEBOUNCE;
  68. }
  69. }
  70. if (debouncing) {
  71. if (--debouncing) {
  72. _delay_ms(1);
  73. } else {
  74. for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
  75. matrix[i] = matrix_debouncing[i];
  76. }
  77. }
  78. }
  79. matrix_scan_user();
  80. return 1;
  81. }
  82. inline matrix_row_t matrix_get_row(uint8_t row) {
  83. return matrix[row];
  84. }
  85. void matrix_print(void) {
  86. }