Skip to content

Instantly share code, notes, and snippets.

@mondalaci
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mondalaci/b904eceb4fe3168077fc to your computer and use it in GitHub Desktop.
Save mondalaci/b904eceb4fe3168077fc to your computer and use it in GitHub Desktop.
Keyboard matrix scan code
/* A single pin of the microcontroller to which a row or column is connected. */
typedef struct {
volatile uint8_t *Direction;
volatile uint8_t *Name;
uint8_t Number;
} Pin_t;
/* This part of the key matrix is stored in the Flash to save SRAM space. */
typedef struct {
const uint8_t ColNum;
const uint8_t RowNum;
const Pin_t *ColPorts;
const Pin_t *RowPins;
} KeyMatrixInfo_t;
/* This Part of the key matrix is stored in the SRAM. */
typedef struct {
const __flash KeyMatrixInfo_t *Info;
uint8_t *Matrix;
} KeyMatrix_t;
const __flash KeyMatrixInfo_t KeyMatrix = {
.ColNum = 2,
.RowNum = 2,
.RowPins = (Pin_t[]) {
{ .Direction=&DDRA, .Name=&PINA, .Number=PINA0 },
{ .Direction=&DDRA, .Name=&PINA, .Number=PINA1 }
},
.ColPorts = (Pin_t[]) {
{ .Direction=&DDRB, .Name=&PORTB, .Number=PORTB0 },
{ .Direction=&DDRB, .Name=&PORTB, .Number=PORTB1 },
}
};
void KeyMatrix_Scan(KeyMatrix_t *KeyMatrix)
{
for (uint8_t Col=0; Col<KeyMatrix->Info->ColNum; Col++) {
const Pin_t *ColPort = KeyMatrix->Info->ColPorts + Col;
for (uint8_t Row=0; Row<KeyMatrix->Info->RowNum; Row++) {
const Pin_t *RowPin = KeyMatrix->Info->RowPins + Row;
uint8_t IsKeyPressed = *RowPin->Name & 1<<RowPin->Number;
KeyMatrix_SetElement(KeyMatrix, Row, Col, IsKeyPressed);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment