Skip to content

Instantly share code, notes, and snippets.

@hidsh
Created February 28, 2023 06:22
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 hidsh/50ca182d878ce4f910b87fc6ec40b22f to your computer and use it in GitHub Desktop.
Save hidsh/50ca182d878ce4f910b87fc6ec40b22f to your computer and use it in GitHub Desktop.
arduino: soatari-matrix test pgm for sparkfun's pro micro
// soatari-matrix test for pro micro
// マトリクスのテスト RC1..RC3を順ぐりにLO出力にして、LO出力以外のRCxを入力にしてSWxxをセンスする
// マトリクスが変化したときのAD値を表示する
// 7 8 9 <-- pin number
// RC1 RC2 RC3
// ----------------
// - , SW12, SW13
// SW21, - , SW23
// SW31, SW32, -
// #define VCC_3V3
#define RC_PINS_MAX 3
const uint8_t rc_pins[RC_PINS_MAX] = {7, 8, 9};
uint8_t matrix[RC_PINS_MAX][RC_PINS_MAX] = {0};
uint8_t matrix_old[RC_PINS_MAX][RC_PINS_MAX] = {0};
int ain_monitor;
void analog_print()
{
char s[256], sf[6];
#ifdef VCC_3V3
dtostrf((float)(ain_monitor*3.0/1024.0), 1, 3, sf); // VCC=3.3V
#else
dtostrf((float)(ain_monitor*4.6/1024.0), 1, 3, sf); // VCC=5V
#endif
sprintf(s, "%s V\n", sf);
Serial.print(s);
}
void matrix_backup()
{
memcpy(matrix_old, matrix, sizeof(matrix));
}
void matrix_print()
{
String s = "--------\n";
for(int r=0; r<RC_PINS_MAX; r++) {
for(int c=0; c<RC_PINS_MAX; c++) {
if(r == c) s += "xx "; // don't care
else if(matrix[r][c]) s += " ";
else s += "ON ";
}
s += "\n";
}
Serial.print(s);
}
void unselect_all()
{
for(int i=0; i<RC_PINS_MAX; i++) {
pinMode(rc_pins[i], INPUT_PULLUP);
}
}
// セレクトするRCxにLO出力して、それ以外のピンを入力にする
void select_row(int sel)
{
uint8_t sel_pin = rc_pins[sel];
pinMode(sel_pin, OUTPUT);
digitalWrite(sel_pin, LOW);
for(int i=0; i<RC_PINS_MAX; i++) {
if(rc_pins[i] == sel_pin) continue;
pinMode(rc_pins[i], INPUT_PULLUP);
}
}
// セレクトしているRCx以外のピンを読んで、マトリクスを更新する
// 前回値から変化したら変化した最初のピンのインデックスを返す
int8_t matrix_update(int8_t sel)
{
int8_t changed = -1;
uint8_t sel_pin = rc_pins[sel];
for(int c=0; c<RC_PINS_MAX; c++) {
if(rc_pins[c] == sel_pin) continue;
// セレクトしたカラム以外をすべて読んで、マトリクス内のセレクト中のROWの各カラムと比較し、変化していたらそこに保存
uint8_t key = digitalRead(rc_pins[c]);
if(key != matrix[sel][c]) {
matrix[sel][c] = digitalRead(rc_pins[c]);
ain_monitor = analogRead(rc_pins[c]);
changed = c;
break;
}
}
return changed;
}
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("Start");
unselect_all();
}
void loop() {
static int i = 0;
select_row(i);
if(matrix_update(i) != -1) {
matrix_print();
analog_print();
}
i = (i + 1) % RC_PINS_MAX;
delay(100); // ms
}
@hidsh
Copy link
Author

hidsh commented Feb 28, 2023

output example

--------
xx       
   xx    
   ON xx 
2.892 V
--------
xx       
   xx    
      xx 
2.892 V
--------
xx ON    
   xx    
      xx 
0.923 V
--------
xx       
   xx    
      xx 
2.897 V

remark

  • xx: don't care, diode is implemented here instead of switch
  • : released
  • ON: pressed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment