Search code examples
ckeypress

Beats per minute counter using key presses in C


I'm building a C program to determine how many times a key is pressed in one minute (think "beats per minute") so I can use it later in a metronome I'm building.

I want to build something like this in C. How would I read the key presses as they happen?


Solution

  • Use fgetc() to read keypress of the ENTER key.

    Use gettimeofday() to measure time in microseconds, compute time elapsed from previous keypress, and divide 60s by it.

    #include <sys/time.h>
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        struct timeval t0, t1;
        float elapsed;
        gettimeofday(&t0, 0);
        while(1) {
            fgetc(stdin);
            gettimeofday(&t1, 0);
            elapsed = (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) / 1000.0f;
            memcpy(&t0, &t1, sizeof(struct timeval));
            printf("%f\n", 60000./elapsed);
        }
        return 0;
    }
    

    You may want to average displayed values (e.g. keep a running average) to reduce variance.