I’m trying to use a membrane keypad, and its library, as input for a music synthesizer. I’m running into a problem because the program acts as if the keys stay pressed. In other words, keypad.isPressed() returns true after a key has been released. Here is the bit of code that I need help with:
void loop() {
pressed_note = instrument.getKey(); //gets the key that is being pressed
if (pressed_note && pressed_note != '8'){ //if available key in keypad is pressed
while (instrument.isPressed(pressed_note)){
digitalWrite(buzzPin, HIGH); //next four lines play the note, delay based on freq of note
delayMicroseconds(notes[pressed_note-'0']);
digitalWrite(buzzPin, LOW);
delayMicroseconds(notes[pressed_note-'0']);
}
}
}
I also tried changing the value within the while loop, but this leads to only one iteration happening, even if the key is still pressed:
void loop() {
pressed_note = instrument.getKey(); //gets the key that is being pressed
if (pressed_note && pressed_note != '8'){ //if available key in keypad is pressed
while (instrument.isPressed(pressed_note)){
pressed_note = instrument.getKey(); //NEW LINE
digitalWrite(buzzPin, HIGH); //next four lines play the note, delay based on freq of note
delayMicroseconds(notes[pressed_note-'0']);
digitalWrite(buzzPin, LOW);
delayMicroseconds(notes[pressed_note-'0']);
}
}
}
Why is this happening? How can I fix it? Any input would help.
I have also put my complete code below in case anyone wants to look at it. Thank you in advance!
#include <Keypad.h>
const int ROWS = 4;
const int COLS = 4;
byte colPins[COLS] = {5,4,3,2}; //connect to the row pinouts of the keypad
byte rowPins[ROWS] = {9,8,7,6}; //connect to the column pinouts of the keypad
char keys[ROWS][COLS] = {
{'0', '1', '2', '8'},
{'3', '4', '5', '8'},
{'6', '7', '8', '8'},
{'8', '8', '8', '8'}
};
Keypad instrument = Keypad (makeKeymap(keys), rowPins, colPins, ROWS, COLS); //starts keypad
int buzzPin = 13;
long unsigned int notes[8] = {3817, 3405, 3034, 2863, 2551, 2273, 2025, 1908}; //based on frequencies of notes
char pressed_note;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(buzzPin, OUTPUT);
}
void loop() {
pressed_note = instrument.getKey(); //gets the key that is being pressed
if (pressed_note && pressed_note != '8'){ //if available key in keypad is pressed
while (instrument.isPressed(pressed_note)){
pressed_note = instrument.getKey();
digitalWrite(buzzPin, HIGH); //next four lines play the note, delay based on freq of note
delayMicroseconds(notes[pressed_note-'0']);
digitalWrite(buzzPin, LOW);
delayMicroseconds(notes[pressed_note-'0']);
}
}
}