tunerlistd/arduino/sterring_buttons_attiny84a/sterring_buttons_attiny84a.ino

133 lines
2.5 KiB
C++

#include <SoftwareSerial.h>
#define COL_3 0
#define COL_2 1
#define COL_1 2
#define ROW_3 5
#define ROW_2 4
#define ROW_1 3
SoftwareSerial serial(9, 10);
int scanRows[] = { ROW_1, ROW_2 };
int scanCols[] = { COL_1, COL_2, COL_3 };
const int numRows = sizeof(scanRows) / sizeof(scanRows[0]);
const int numCols = sizeof(scanCols) / sizeof(scanCols[0]);
int lastStates[2][3] = {
{ 0, 0, 0 },
{ 0, 0, 0 }
};
char buttons[2][3][9] = {
{ 0, 1, 2 },
{ 3, 4, 5 }
};
/*
VOL_DOWN: 0
VOL_UP : 1
OK: 2
SRC_UP : 3
PAUSE: 4
SRC_DOWN: 5
CW: 6
CCW: 7
*/
void setup() {
serial.begin(600);
for (int col = 0; col < numCols; col++) {
pinMode(scanCols[col], INPUT_PULLUP);
}
for (int row = 0; row < numRows; row++) {
pinMode(scanRows[row], OUTPUT);
digitalWrite(scanRows[row], HIGH);
}
}
int processWheel() {
/*
https://forum.arduino.cc/t/3-phase-rotary-encoder/1100320/8
*/
pinMode(ROW_3, OUTPUT);
digitalWrite(ROW_3, LOW);
static bool phaseALatch, phaseBLatch, phaseCLatch;
static bool encoderTurned, CW;
if (!digitalRead(COL_1)) {
phaseALatch = true;
if (phaseBLatch) {
CW = false;
} else if (phaseCLatch) {
CW = true;
}
encoderTurned = phaseBLatch | phaseCLatch;
phaseBLatch = false;
phaseCLatch = false;
}
if (!digitalRead(COL_2)) {
phaseBLatch = true;
if (phaseCLatch) {
CW = false;
} else if (phaseALatch) {
CW = true;
}
encoderTurned = phaseALatch | phaseCLatch;
phaseALatch = false;
phaseCLatch = false;
}
if (!digitalRead(COL_3)) {
phaseCLatch = true;
if (phaseALatch) {
CW = false;
} else if (phaseBLatch) {
CW = true;
}
encoderTurned = phaseALatch | phaseBLatch;
phaseALatch = false;
phaseBLatch = false;
}
pinMode(ROW_3, INPUT);
if (encoderTurned) {
if (CW) serial.write(6);
else serial.write(7);
encoderTurned = false;
return 1;
}
return 0;
}
void processButtons() {
for (int row = 0; row < numRows; row++) {
pinMode(scanRows[row], OUTPUT);
digitalWrite(scanRows[row], LOW);
for (int col = 0; col < numCols; col++) {
int keyState = digitalRead(scanCols[col]);
if (keyState != lastStates[row][col]) {
serial.write(row);
serial.write(col);
serial.write(keyState);
serial.write(0xFF);
lastStates[row][col] = keyState;
}
}
digitalWrite(scanRows[row], HIGH);
}
}
void loop() {
if (!processWheel()) {
processButtons();
}
else {
serial.write(0xFF);
}
delay(50);
}