~kline/geiger

39894bd78e794b3e8b10d79f46c0ca679c164d51 — Gareth Pulham 1 year, 7 months ago
Initial commit driven by stdin
3 files changed, 101 insertions(+), 0 deletions(-)

A .gitignore
A Makefile
A geiger.c
A  => .gitignore +2 -0
@@ 1,2 @@
*.o
geiger

A  => Makefile +18 -0
@@ 1,18 @@
CC = clang
CFLAGS = -std=c99 -Wall -D_POSIX_C_SOURCE=200809L
LDFLAGS = -lpthread -lasound
SOURCES = $(wildcard *.c)
OBJECTS = $(SOURCES:.c=.o)
EXECUTABLE = geiger

all: $(EXECUTABLE)

%.o: %.c %.h
	$(CC) -c $(CFLAGS) $< -o $@

$(EXECUTABLE): $(OBJECTS)
	$(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@

.PHONY: clean all
clean:
	rm -f *.o $(EXECUTABLE)

A  => geiger.c +81 -0
@@ 1,81 @@
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>

char stop = 0;
char decay = 0;

void* worker(void *z){
    // mostly lifted from https://www.alsa-project.org/alsa-doc/alsa-lib/_2test_2pcm__min_8c-example.html
    static char *device = "default";

    unsigned char click[16];
    unsigned char blank[16];

    int err;
    unsigned int i;
    snd_pcm_t *handle;
    snd_pcm_sframes_t frames;

    for (i = 0; i < sizeof(click); i++){
        click[i] = 0;
        blank[i] = 0;
    }
    click[0] = 250;

    if ((err = snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
        fprintf(stderr, "Playback open error: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }
    if ((err = snd_pcm_set_params(handle,
                                  SND_PCM_FORMAT_U8,
                                  SND_PCM_ACCESS_RW_INTERLEAVED,
                                  1,
                                  8000,
                                  1,
                                  125)) < 0) {
        fprintf(stderr, "Playback open error: %s\n", snd_strerror(err));
        exit(EXIT_FAILURE);
    }

    while (!stop) {
        if (decay) {
            frames = snd_pcm_writei(handle, click, sizeof(click));
            decay = 0;
        }
        else
            frames = snd_pcm_writei(handle, blank, sizeof(click));
        if (frames < 0)
            frames = snd_pcm_recover(handle, frames, 0);
            if (frames < 0) {
                fprintf(stderr, "snd_pcm_writei failed: %s\n", snd_strerror(err));
                break;
            }
            if (frames > 0 && frames < (long)sizeof(click))
                fprintf(stderr, "Short write (expected %li, wrote %li)\n", (long)sizeof(click), frames);
    }

    snd_pcm_close(handle);
    return 0;
}

int main(){
    pthread_t worker_thread;
    int rc = pthread_create(&worker_thread, NULL, worker, (void *)NULL);
    if (rc) {
        fprintf(stderr, "Whoops!\n");
        return -1;
    }
    for (;;){
        char input = getchar();
        if (input != 10){
            break;
        }
        decay = 1;
    }
    stop = 1;
    fprintf(stderr, "Stopping: %d\n", stop);
    pthread_join(worker_thread, NULL);
    return 0;
}