What linear sensor for a keyboard?
Most keyboards simply use two contacts per key, configured so that they close (or open) at different positions in the key's travel. They estimate velocity from the time that elapses between the two events. Even the fancy weighted "piano action" keyboards use this basic sensing method.
Trying to measure position and/or velocity directly sounds like massive overkill.
I have to measure the position of each key in order to know how loud the sound should be.
Normally key velocity is calculated by measuring the time between the normally closed up-switch breaking and the normally open down-switch making.
simulate this circuit – Schematic created using CircuitLab
Figure 1. A break-before-make keyboard contact is typically used for velocity measurement.
The volume of the sound is not only function of the velocity of the keys at the end of the descent. ... The length of the maximum displacement is about 2 cm.
In this case you need to mechanically arrange the normally closed contact so that it breaks in the last few mm of travel.
simulate this circuit
Figure 2. The mechanical switching arrangement.
It seems to me that your best bet would be to modify an existing MIDI bass pedalboard to suit your purposes.
OP's comment to Dave Tweed:
I think this method is insufficient. Here's why: if I slowly push the key down half of the path, and then quickly push it down to the end, the sound would be loud on a real piano, and this method would think the key was pushed really slowly and therefore output a really quiet sound. In addition, if I want to repeat a note, I would have to let the key completely return to its original position, which is not at all what I would do on a real piano.
That is why I proposed activating the changeover switch in the last few mm of travel.
You should take a look at analog keyboards. Take a look at this video. This is just an example of concept.
Edit: Also, if optical switches are not working for you, take a look at this:
There is a PCB printed coil under each key cap. As you press the button coil measures the inductance change caused by key spring compressing and decompressing, therefore, you can get pretty accurate reading of the switch position.
Source:
Reddit
Imgur