I hope you are doing all really well, I am trying to make a MIDI Piano Keyboard, Pretty basic I press a key the MIDI signal is send and the sounds comes.
But I want to add the velocity to the my keys, there are one contacts per key (the keyboard I am using is Fatar Keyboard).
I need to calculate the time interval between the first contact and then the second contact ( Circuit Diagram is attached below).
- All the keys are in set as input pull_up
- when a key is pressed it goes low … Of course
Mentioned Below is the function where I am reading the keys. what do I need to do to get the following situation done
[they are 49 keys which are arranged in to two diode matrices. There are actually 98 switches in the matrix. The reason for this is that there are two switches under each key. When a key is pressed, one of the switches closes slightly before the other one. By measuring the time of flight between the switches we can derive the velocity]
Situation 1
- Key is pressed
- Start Time
- Time for how long its pressed
- Key Released
Code
void read_keys() {
for (uint8_t key = 0; key < 49; key ++) {
digitalWrite(output_main[key], LOW); //turn off output main key
if (digitalRead(input_pullup[key]) == LOW) {
//check main input key is presses
//check with key_activated array
firstcontactdownmills = millis();
Serial.println(key);
Velocity = map(currentmills - firstcontactdownmills, 0, 256, 127, 0);
if (key_activated[key] == 0) {
//send midi on command
my_midi.sendNoteOn(key + note_offset, Velocity, 1);
main_midi.sendNoteOn(key + note_offset, Velocity, 1);
//update array
key_activated[key] = 1;
}
}
else { //if key released
//check with key_activated array
if (key_activated[key] == 1) {
//send midi off command
my_midi.sendNoteOff(key + note_offset, 0, 1);
main_midi.sendNoteOff(key + note_offset, 0, 1);
//update array
key_activated[key] = 0;
}
}
digitalWrite(output_main[key], HIGH); //turn on output main key
}
}
You can add a state variable to your keys, that keeps track of where your key is. You can then start the timer at the transition from not_pressed to half_pressed. You then evaluate the velocity at a transition from half_pressed to full_pressed.
You should also add a timeout that resets it back to unpressed in case a key press is missed.
But I am not sure if your loop will be fast enough after adding this kind of logic.