C · Local Linux terminal
Why does the piano keep playing after you release a key?
Online version: https://fpga.labsland.com/altera/embedded-systems/lab-08/part-03/
Your computer
Embedded Systems · Audio · POSIX threads in C. Build a piano with a keyboard thread and an audio thread. You will record the notes each thread produces together, then diagnose a stuck chord. Use a Linux computer with a C compiler, Linux userspace headers and Python 3. The included score player gives you the same key events on every trial.
Play the score
In this keyboard layout, Q, W, E, R, T, Y, U and I play the eight white keys from middle C to the next C. The five intervening black keys are 2, 3, 5, 6 and 7. A press starts a sound, a held key slowly decays and a release damps the sound much faster. From the extracted worksheet directory run:
cc -std=c11 -O2 -Wall -Wextra -Werror starter/piano.c -pthread -lm -o piano
python3 resources/play_score.py ./piano before.wav triad
python3 resources/measure_release.py before.wav
The score presses Q, E and T to build a C major chord, releases each key and finishes with a repeat event for T. Listen to the ending or inspect the thirteen measured amplitudes. Positions 0, 4 and 7 represent C, E and G. Compare the quiet interval at the start with the interval from 2.55 to 2.85 seconds. When should the sound have died away?
Find the missing transition
In resources/piano_engine.h, follow the key event from the input thread to the next 80-frame audio block. Find where the mutex protects a note's held flag and strike count. At 8 kHz, how long is a block? Why does the audio thread release the mutex before generating samples?
Track the bit for middle C through a press, a duplicate press and a release. Inspect update_held in starter/piano.c. Change it so a release affects only the released note. Rebuild and record after.wav. Include the measured triad and release windows for both programs. A repeat event by itself should never start a fresh note.
| Time in the score | Sound you predict | Before your edit | After your edit |
|---|---|---|---|
| 0.42–0.65 s | |||
| 1.32–1.51 s | |||
| 2.55–2.85 s |
Run again with octave in place of triad. This score releases the lower C before pressing the upper C. During the upper note, which bins would distinguish a stuck key from ordinary decay? Change one note or one release time in your own copy of play_score.py and predict the result before measuring.
The score player sends Linux key-event records through a private pipe. If your instructor has provided a dedicated readable Linux event device, you can pass its path directly, for example ./piano /dev/input/by-id/CLASSROOM-event-kbd live.wav 3 with the actual classroom path. The file records the synthesized notes and can be played afterward. Submit your edit, two recordings or their measurements, and an explanation of how the threads share key state.
FPGAcademy audio exercise · Exercise notice · LabsLand source license
