Skip to content

Instantly share code, notes, and snippets.

@geocine
Last active December 5, 2020 16:07
Show Gist options
  • Save geocine/c92ab206b68a83c1d55604ede154a5f6 to your computer and use it in GitHub Desktop.
Save geocine/c92ab206b68a83c1d55604ede154a5f6 to your computer and use it in GitHub Desktop.
Demultiplexer
#include <stdint.h>
#include <stdbool.h>
#include "wait.h"
#include "util.h"
#include "matrix.h"
#include "debounce.h"
#include "quantum.h"
// ROW2COL
// #define MATRIX_ROW_PINS { F5, F6 }
static const pin_t row_pins[MATRIX_ROWS] = MATRIX_ROW_PINS;
/* Layout */
// col 0 1
// row 0 KC_1 KC_2
// row 1 KC_3 KC_4
/* Cols 0 - 5
* These columns use a 74CH138 to 8 bit demultiplexer.
* A2 A1 A0
* col / pin: D0 D4 C6
* 0: 0 0 0 Y0
* 1: 0 0 1 Y1
* 2: 0 1 0 Y2
* 3: 0 1 1 Y3
* 4: 1 0 0 Y4
* 5: 1 0 1 Y5
* 6 1 1 0 Y6
* X 1 1 1 Y7 Do not connect anything here
*/
static void select_col(uint8_t col)
{
switch (col) {
case 0:
writePinLow(D0);
writePinLow(D4);
writePinLow(C6);
break;
case 1:
writePinLow(D0);
writePinLow(D4);
break;
}
}
static void unselect_col(uint8_t col)
{
switch (col) {
case 0:
writePinHigh(D0);
writePinHigh(D4);
writePinHigh(C6);
break;
case 1:
writePinHigh(D0);
writePinHigh(D4);
break;
}
}
static void unselect_cols(void)
{
setPinOutput(D0);
setPinOutput(D4);
setPinOutput(C6);
// make all pins high to select Y7, make sure nothing is connected to this pin
writePinHigh(D0);
writePinHigh(D4);
writePinHigh(C6);
}
static void init_pins(void)
{
unselect_cols();
for (uint8_t x = 0; x < MATRIX_ROWS; x++)
{
setPinInputHigh(row_pins[x]);
}
}
static bool read_rows_on_col(matrix_row_t current_matrix[], uint8_t current_col) {
bool matrix_changed = false;
// Select col and wait for col selecton to stabilize
select_col(current_col);
matrix_io_delay();
// For each row...
for (uint8_t row_index = 0; row_index < MATRIX_ROWS; row_index++) {
// Store last value of row prior to reading
matrix_row_t last_row_value = current_matrix[row_index];
matrix_row_t current_row_value = last_row_value;
// Check row pin state
if (readPin(row_pins[row_index]) == 0) {
// Pin LO, set col bit
current_row_value |= (MATRIX_ROW_SHIFTER << current_col);
} else {
// Pin HI, clear col bit
current_row_value &= ~(MATRIX_ROW_SHIFTER << current_col);
}
// Determine if the matrix changed state
if ((last_row_value != current_row_value)) {
matrix_changed |= true;
current_matrix[row_index] = current_row_value;
}
}
// Unselect col
unselect_col(current_col);
return matrix_changed;
}
void matrix_init_custom(void)
{
// initialize key pins
init_pins();
}
bool matrix_scan_custom(matrix_row_t current_matrix[])
{
bool changed = false;
// Set col, read rows
for (uint8_t current_col = 0; current_col < MATRIX_COLS; current_col++)
{
changed |= read_rows_on_col(current_matrix, current_col);
}
return changed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment