Code:
// button pins
// 4 is pin of button1
// 5 is pin of button2
// 0 means end of buttons
byte buttons[] = {4, 5, 6, 7, 0};
// first 0 is for counting in function
// 1,1,2,1 is code (press Button1, 2, 2, 1 for activating)
// last 0 is end of code
byte code1[] = {0, 1, 2, 2, 1, 0};
byte code2[] = {0, 2, 1, 2, 2, 0};
byte code3[] = {0, 3, 3, 3, 0};
byte code4[] = {0, 1, 2, 3, 4, 3, 2, 1, 0};
byte* codes[] = {code1, code2, code3, code4, 0};
byte initButtons(byte buttons[]) {
// setup button pins for reading
byte counter = 0;
while(buttons[counter]) pinMode(buttons[counter++], INPUT);
}
byte checkButtons(byte* pressed_btn, byte* codes[], byte buttons[]) {
static byte last_pressed = 0;
if (last_pressed) {
if(!digitalRead(buttons[last_pressed-1])) return 0; // Button still pressed? -> return
else { last_pressed = 0; } // else: not pressed anymore -> go on
}
*pressed_btn = 0;
byte btn_counter = 0; // iterate over all buttons
byte code_counter = 0; // iterate over all codes
while(buttons[btn_counter]) {
byte is_pressed = !digitalRead(buttons[btn_counter]); // check buttons one after another
if(is_pressed) {
last_pressed = btn_counter+1; // store pressed button number
*pressed_btn = last_pressed; // write pressed button number to external variable pressed_btn
while(codes[code_counter]) { // check all codes one after another
if(codes[code_counter][(codes[code_counter][0])+1] == btn_counter + 1) { // is the pressed button nr equal to next button nr in code?
codes[code_counter][0]++;
if(!codes[code_counter][(codes[code_counter][0])+1]) { // code veryfied?
byte i = 0; while(codes[i]) { *codes[i++] = 0; } // reset all counters
return code_counter+1; // returns number of detected code
}
}
else { codes[code_counter][0] = 0; }
code_counter++;
}
code_counter = 0;
}
btn_counter++;
}
return 0; // 0 means no code veryfied
}
void setup() {
initButtons(buttons);
Serial.begin(57600);
}
void loop() {
byte btn;
byte detected_code = checkButtons(&btn, codes, buttons);
//if (btn) { Serial.print("Button pressed: "); Serial.println(btn); }
if (detected_code) { Serial.print("Code detected: ");Serial.println(detected_code); }
}
Ausgabe nach dem Drücken der Taster 1,2,2,1 (in dieser Reihenfolge):
Lesezeichen