ChordJoy is a keyboard application that accepts chordal input from a set of digital ports, outputting letters and the chords that correspond to the piano keyboard keys the user has pressed.
Dependencies: PinDetect_KL25Z mbed-rtos mbed
Fork of ChordJoy by
Diff: main.cpp
- Revision:
- 3:ed89297af2ce
- Parent:
- 2:49e2b1273f16
- Child:
- 4:400a042e762a
--- a/main.cpp Sat Sep 20 21:19:25 2014 +0000 +++ b/main.cpp Mon Sep 22 02:12:29 2014 +0000 @@ -6,10 +6,10 @@ const int BUZZERS = 3; const int LETTERS = 27; -// Flag that says whether we're waiting to collect input from other buttons -// following one upward edge. -bool flag = false; -time_t startSeconds = time(NULL); +// Collection is the time that it takes after pressing one key and then reading +// all the keys to determine what the chord is. +const int COLLECTION_MS = 500; +Timer collectionTimer; InterruptIn buttons [BUTTONS] = { InterruptIn(D2), @@ -43,8 +43,10 @@ 2024, // B4 10000000 // inaudible pitch }; +// Possible chords that can be played. +// Note that 7 is no button pressed, or a 'silent' pitch. int chords [LETTERS][BUZZERS] = { - {0, 2, 4}, // single notes + {0, 7, 7}, // single notes {1, 7, 7}, {2, 7, 7}, {3, 7, 7}, @@ -92,7 +94,7 @@ } void setFlag() { - flag = true; + collectionTimer.start(); } void silenceBuzzers(void) { @@ -108,20 +110,49 @@ } } +int readChord(void) { + /* Detect the current chord from the keys pressed. Return int index of chord. + Return -1 if no chord can be found with the current keys. + Note that we can only read as many keys as there are buzzers, so check + on each key in an ascending order. */ + int firstThreeButtons[BUZZERS] = {7, 7, 7}; + int pressedCount = 0; + for (int i = 0; i < BUTTONS; i++) { + if (buttons[i].read() == 1) { + firstThreeButtons[pressedCount] = i; + pressedCount++; + } + if (pressedCount >= BUZZERS) { + break; + } + } + int matchIndex = -1; + for (int i = 0; i < LETTERS; i++) { + bool chordMatches = true; + for (int j = 0; j < BUZZERS; j++) { + if (firstThreeButtons[j] != chords[i][j]) { + chordMatches = false; + break; + } + } + if (chordMatches == true) { + matchIndex = i; + break; + } + } + pc.printf("Matched chord %d\n", matchIndex); + return matchIndex; +} + void waitForChord(void) { - /* Should be run in the main loop so that it can print */ + /* This method should be run in the main loop so that it can print */ while (true) { - time_t currentSeconds = time(NULL); - time_t secondsPast = currentSeconds - startSeconds; - if (flag == true) { - pc.printf("Pressed\n"); - flag = false; + if (collectionTimer.read_ms() > COLLECTION_MS) { + collectionTimer.stop(); + collectionTimer.reset(); + int chordIndex = readChord(); } - else { - pc.printf("Not pressed\n"); - } - pc.printf("Seconds: %d\n", secondsPast); - wait_ms(500); + wait_ms(10); } }