Subversion Repositories svnkaklik

Rev

Rev 562 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log

Rev Author Line No. Line
558 kaklik 1
///////////////////////////////////////////////////////////////////////////////////
2
//                        A small demo of sonar.
3
// Program allow distance measuring.
4
// Uses cross-correlation algorithm to find echos
5
//
6
// Author: kaklik  (kaklik@mlab.cz)
7
//
8
///////////////////////////////////////////////////////////////////////////////////
9
 
10
#include <stdio.h>
11
#include <stdlib.h>
12
#include <string.h>
13
#include <sched.h>
14
#include <errno.h>
15
#include <getopt.h>
16
#include <alsa/asoundlib.h>
17
#include <sys/time.h>
18
#include <math.h>
563 kaklik 19
#include <fftw3.h>
558 kaklik 20
 
561 kaklik 21
#define SOUND_SPEED	340.0	// sound speed in air in metrs per second
22
#define MAX_RANGE	10.0	// maximal working radius in meters
23
 
558 kaklik 24
static char *device = "plughw:0,0";			/* playback device */
25
static snd_pcm_format_t format = SND_PCM_FORMAT_S16;	/* sample format */
561 kaklik 26
static unsigned int rate = 96000;			/* stream rate */
562 kaklik 27
static unsigned int buffer_time = 2 * (MAX_RANGE / SOUND_SPEED * 1e6);		/* ring buffer length in us */
28
static unsigned int period_time = MAX_RANGE / SOUND_SPEED * 1e6;		/* period time in us */
558 kaklik 29
static int resample = 1;				/* enable alsa-lib resampling */
30
 
31
unsigned int chirp_size;
32
 
33
static snd_pcm_sframes_t buffer_size;	// size of buffer at sound card
34
static snd_pcm_sframes_t period_size;	//samples per frame
35
static snd_output_t *output = NULL;
36
 
37
static int set_hwparams(snd_pcm_t *handle, snd_pcm_hw_params_t *params, unsigned int channels)
38
{
561 kaklik 39
    unsigned int rrate;
40
    snd_pcm_uframes_t size;
41
    int err, dir;
558 kaklik 42
 
561 kaklik 43
    /* choose all parameters */
44
    err = snd_pcm_hw_params_any(handle, params);
45
    if (err < 0)
46
    {
47
        printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
48
        return err;
49
    }
50
    /* set hardware resampling */
51
    err = snd_pcm_hw_params_set_rate_resample(handle, params, resample);
52
    if (err < 0)
53
    {
54
        printf("Resampling setup failed for playback: %s\n", snd_strerror(err));
55
        return err;
56
    }
57
    /* set the interleaved read/write format */
58
    err = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
59
    if (err < 0)
60
    {
61
        printf("Access type not available for playback: %s\n", snd_strerror(err));
62
        return err;
63
    }
64
    /* set the sample format */
65
    err = snd_pcm_hw_params_set_format(handle, params, format);
66
    if (err < 0)
67
    {
68
        printf("Sample format not available for playback: %s\n", snd_strerror(err));
69
        return err;
70
    }
71
    /* set the count of channels */
72
    err = snd_pcm_hw_params_set_channels(handle, params, channels);
73
    if (err < 0)
74
    {
75
        printf("Channels count (%i) not available for playbacks: %s\n", channels, snd_strerror(err));
76
        return err;
77
    }
78
    /* set the stream rate */
79
    rrate = rate;
80
    err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
81
    if (err < 0)
82
    {
83
        printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
84
        return err;
85
    }
86
    if (rrate != rate)
87
    {
88
        printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
89
        return -EINVAL;
90
    }
91
    else printf("Rate set to %i Hz\n", rate, err);
92
    /* set the buffer time */
93
    err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &buffer_time, &dir);
94
    if (err < 0)
95
    {
96
        printf("Unable to set buffer time %i for playback: %s\n", buffer_time, snd_strerror(err));
97
        return err;
98
    }
99
    err = snd_pcm_hw_params_get_buffer_size(params, &size);
100
    if (err < 0)
101
    {
102
        printf("Unable to get buffer size for playback: %s\n", snd_strerror(err));
103
        return err;
104
    }
105
    buffer_size = size;
106
    printf("Bufffer size set to:  %d  Requested buffer time: %ld \n", (int) buffer_size, (long) buffer_time);
107
 
108
 
109
    /// set the period time
110
    err = snd_pcm_hw_params_set_period_time_near(handle, params, &period_time, &dir);
111
    if (err < 0)
112
    {
113
        printf("Unable to set period time %i for playback: %s\n", period_time, snd_strerror(err));
114
        return err;
115
    }
116
 
117
    err = snd_pcm_hw_params_get_period_size(params, &size, &dir);
118
    if (err < 0)
119
    {
120
        printf("Unable to get period size for playback: %s\n", snd_strerror(err));
121
        return err;
122
    }
123
    period_size = size;
124
    printf("Period size set to:  %d Requested period time: %ld \n", (int) period_size, (long) period_time);
125
 
126
    /* write the parameters to device */
127
    err = snd_pcm_hw_params(handle, params);
128
    if (err < 0)
129
    {
130
        printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
131
        return err;
132
    }
133
    return 0;
558 kaklik 134
}
135
 
136
static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams)
137
{
561 kaklik 138
    int err;
558 kaklik 139
 
561 kaklik 140
    /* get the current swparams */
141
    err = snd_pcm_sw_params_current(handle, swparams);
142
    if (err < 0)
143
    {
144
        printf("Unable to determine current swparams for playback: %s\n", snd_strerror(err));
145
        return err;
146
    }
563 kaklik 147
    // start the transfer when the buffer is almost full: never fou our case
561 kaklik 148
    err = snd_pcm_sw_params_set_start_threshold(handle, swparams, 2 * buffer_size);
149
    if (err < 0)
150
    {
151
        printf("Unable to set start threshold mode for playback: %s\n", snd_strerror(err));
152
        return err;
153
    }
154
 
155
    err = snd_pcm_sw_params_set_period_event(handle, swparams, 1);
156
    if (err < 0)
157
    {
158
        printf("Unable to set period event: %s\n", snd_strerror(err));
159
        return err;
160
    }
161
 
162
    /* write the parameters to the playback device */
163
    err = snd_pcm_sw_params(handle, swparams);
164
    if (err < 0)
165
    {
166
        printf("Unable to set sw params for playback: %s\n", snd_strerror(err));
167
        return err;
168
    }
169
    return 0;
558 kaklik 170
}
171
 
172
////// SIGNAL GENERATION STUFF
561 kaklik 173
unsigned int linear_windowed_chirp(short *pole)
558 kaklik 174
{
561 kaklik 175
    unsigned int maxval = (1 << (snd_pcm_format_width(format) - 1)) - 1;
558 kaklik 176
 
562 kaklik 177
    static const float f0 = 5000;		//starting frequency
178
    static const float fmax = 13000;		//ending frequency
179
    static const float Tw = 0.0015;
561 kaklik 180
    static float k;
558 kaklik 181
 
561 kaklik 182
    unsigned int n=0;
183
    double t;
184
    unsigned int chirp_samples;		// number of samples per period
558 kaklik 185
 
561 kaklik 186
    k=2*(fmax-f0)/Tw;
187
    chirp_samples = ceil(rate*Tw);
558 kaklik 188
 
561 kaklik 189
    for (n=0;n<=chirp_samples;n++)
190
    {
191
        t = (double) n / (double)rate;
192
        pole[n] = (short) floor( (0.35875 - 0.48829*cos(2*M_PI*t*1/Tw) + 0.14128*cos(2*M_PI*2*t*1/Tw) - 0.01168*cos(2*M_PI*3*t*1/Tw))*maxval*sin(2*M_PI*(t)*(f0+(k/2)*(t))) );
193
    }
194
    return (chirp_samples);
558 kaklik 195
}
196
 
197
int main(int argc, char *argv[])
198
{
561 kaklik 199
    snd_pcm_t *playback_handle, *capture_handle;
200
    int err;
201
    snd_pcm_hw_params_t *hwparams;
202
    snd_pcm_sw_params_t *swparams;
558 kaklik 203
 
562 kaklik 204
    long int *correlationl, *correlationr;
205
    int *L_signal, *R_signal;
206
    short *chirp, *signal;
563 kaklik 207
    float *chirp_spect, *echo_spect;
561 kaklik 208
    unsigned int i,j,m,n;
563 kaklik 209
    unsigned int delayl[10],delayr[10];	//store delay of signifed correlation
561 kaklik 210
    long int l,r;  // store correlation at strict time
563 kaklik 211
    double df;	//frequency resolution 
212
    unsigned int frequency_bins; // number of output frequency bins 
558 kaklik 213
 
563 kaklik 214
    double *inchirp;
215
    fftw_complex *outchirp;
216
    fftw_plan fft_plan_chirp;
217
 
561 kaklik 218
    FILE *out;
558 kaklik 219
 
561 kaklik 220
    snd_pcm_hw_params_alloca(&hwparams);
221
    snd_pcm_sw_params_alloca(&swparams);
558 kaklik 222
 
561 kaklik 223
    printf("Simple PC sonar ver. 000000001 starting work.. \n");
558 kaklik 224
 
225
//open and set playback device
561 kaklik 226
    if ((err = snd_pcm_open(&playback_handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0)
227
    {
228
        printf("Playback open error: %s\n", snd_strerror(err));
229
        return 0;
230
    }
558 kaklik 231
 
561 kaklik 232
    if ((err = set_hwparams(playback_handle, hwparams, 1)) < 0)
233
    {
234
        printf("Setting of hwparams failed: %s\n", snd_strerror(err));
235
        exit(EXIT_FAILURE);
236
    }
237
    if ((err = set_swparams(playback_handle, swparams)) < 0)
238
    {
239
        printf("Setting of swparams failed: %s\n", snd_strerror(err));
240
        exit(EXIT_FAILURE);
241
    }
242
 
558 kaklik 243
//open and set capture device
561 kaklik 244
    if ((err = snd_pcm_open(&capture_handle, device, SND_PCM_STREAM_CAPTURE, 0)) < 0)
245
    {
246
        printf("Playback open error: %s\n", snd_strerror(err));
247
        return 0;
248
    }
558 kaklik 249
 
561 kaklik 250
    if ((err = set_hwparams(capture_handle, hwparams, 2)) < 0)
251
    {
252
        printf("Setting of hwparams failed: %s\n", snd_strerror(err));
253
        exit(EXIT_FAILURE);
254
    }
255
    if ((err = set_swparams(capture_handle, swparams)) < 0)
256
    {
257
        printf("Setting of swparams failed: %s\n", snd_strerror(err));
258
        exit(EXIT_FAILURE);
259
    }
260
 
563 kaklik 261
    /*    err = snd_pcm_link( capture_handle, playback_handle); //link capture and playback together
262
        if (err < 0)
263
        {
264
            printf("Device linking error: %s\n", snd_strerror(err));
265
            exit(EXIT_FAILURE);
266
        }*/
558 kaklik 267
 
562 kaklik 268
    correlationl = malloc(period_size * sizeof(long int)); //array to store correlation curve
269
    correlationr = malloc(period_size * sizeof(long int)); //array to store correlation curve
270
    L_signal = malloc(period_size * sizeof(int));
271
    R_signal = malloc(period_size * sizeof(int));
272
    chirp = calloc(2*period_size, sizeof(short));
273
    signal = malloc(2*period_size * sizeof(short));
558 kaklik 274
 
562 kaklik 275
// generate ping pattern
276
    chirp_size = linear_windowed_chirp(chirp);
277
 
563 kaklik 278
    frequency_bins = chirp_size / 2 + 1;
279
    df = (double) rate / (double) chirp_size;
280
    chirp_spect = malloc(frequency_bins * sizeof(float));
281
    echo_spect = malloc(frequency_bins * sizeof(float));
282
 
283
    inchirp = fftw_malloc(sizeof(double) * chirp_size); 		// allocate input array for FFT
284
    outchirp = fftw_malloc(sizeof(fftw_complex) * frequency_bins);
285
 
286
    fft_plan_chirp = fftw_plan_dft_r2c_1d(chirp_size, inchirp, outchirp, FFTW_ESTIMATE);
287
 
288
    printf("compute chirp spectrum\n");
289
    for(i=0; i < chirp_size; i++) inchirp[i] = chirp[i];
290
    fftw_execute(fft_plan_chirp);
291
    for(i=0; i < frequency_bins; i++) chirp_spect[i] = sqrt( outchirp[i][0] * outchirp[i][0] + outchirp[i][1] * outchirp[i][1] );
292
 
293
// write chirp data to souncard buffer
561 kaklik 294
    err = snd_pcm_writei(playback_handle, chirp, period_size);
295
    if (err < 0)
296
    {
297
        printf("Initial write error: %s\n", snd_strerror(err));
298
        exit(EXIT_FAILURE);
299
    }
560 kaklik 300
 
562 kaklik 301
//start sream
302
    err = snd_pcm_start(playback_handle);
561 kaklik 303
    if (err < 0)
304
    {
562 kaklik 305
        printf("Start error: %s\n", snd_strerror(err));
561 kaklik 306
        exit(EXIT_FAILURE);
307
    }
558 kaklik 308
 
562 kaklik 309
    err = snd_pcm_start(capture_handle);
561 kaklik 310
    if (err < 0)
311
    {
312
        printf("Start error: %s\n", snd_strerror(err));
313
        exit(EXIT_FAILURE);
314
    }
315
    else printf("Waiting for transmitt all samples\n");
562 kaklik 316
//--------------
317
    while ( snd_pcm_avail_update(capture_handle) < period_size)
561 kaklik 318
    {
319
        usleep(1000);
320
        printf(".");
321
    }
558 kaklik 322
 
562 kaklik 323
    err = snd_pcm_drop(playback_handle);
324
    err = snd_pcm_drain(capture_handle);
561 kaklik 325
    if (err < 0)
326
    {
327
        printf("Stop error: %s\n", snd_strerror(err));
328
        exit(EXIT_FAILURE);
329
    }
558 kaklik 330
 
562 kaklik 331
    err = snd_pcm_readi(capture_handle, signal, period_size);
332
    if (err < 0)
333
    {
334
        printf("Read error: %s\n", snd_strerror(err));
335
        exit(EXIT_FAILURE);
336
    }
558 kaklik 337
 
561 kaklik 338
    j=0;
562 kaklik 339
    for (i=0;i < period_size;i++)		// separe inretleaved samples to two arrays
561 kaklik 340
    {
341
        L_signal[i]=signal[j];
342
        R_signal[i]=signal[j+1];
343
        j+=2;
344
    }
558 kaklik 345
 
562 kaklik 346
    printf("\nData transmitted \ncorrelating\n");
347
    for (n=0; n < (period_size - chirp_size - 1); n++)
561 kaklik 348
    {
349
        l=0;
350
        r=0;
563 kaklik 351
        for ( m = 0; m < chirp_size;m++)
561 kaklik 352
        {
558 kaklik 353
            l += chirp[m]*L_signal[m+n];	// correlate with left channel
354
            r += chirp[m]*R_signal[m+n];	// correlate with right channel
561 kaklik 355
        }
563 kaklik 356
        correlationl[n]=abs(l);
357
        correlationr[n]=abs(r);
561 kaklik 358
    }
558 kaklik 359
 
562 kaklik 360
    printf("Searching echos\n");
561 kaklik 361
    r=0;
362
    l=0;
562 kaklik 363
    for (n=0; n < period_size;n++) 			//najde nejvetsi korelace
561 kaklik 364
    {
365
        if (l < correlationl[n])
366
        {
563 kaklik 367
            delayl[1] = n;
561 kaklik 368
            l = correlationl[n];
369
        }
370
        if (r < correlationr[n])
371
        {
563 kaklik 372
            delayr[1] = n;
561 kaklik 373
            r = correlationr[n];
374
        }
375
    }
558 kaklik 376
 
563 kaklik 377
 
378
 
562 kaklik 379
    printf("Writing output file\n");
561 kaklik 380
    out=fopen("/tmp/sonar.txt","w");
381
    j=0;
563 kaklik 382
    for (i=0; i <= (period_size - 1); i++)
561 kaklik 383
    {
563 kaklik 384
        fprintf(out,"%6d %6d %6d %9ld %9ld\n",i,L_signal[i],R_signal[i],correlationl[i], correlationr[i]);
561 kaklik 385
        j+=2;
386
    }
387
    fclose(out);
558 kaklik 388
 
563 kaklik 389
    out=fopen("/tmp/chirp.txt","w");
390
    j=0;
391
    for (i=0; i <= (chirp_size - 1); i++)
392
    {
393
        fprintf(out,"%6d %6d %f\n", i, chirp[i], chirp_spect[i]);
394
        j+=2;
395
    }
396
    fclose(out);
558 kaklik 397
 
563 kaklik 398
    printf("Echo zacina na: %d vzorku.\n", delayl[1]);
399
    printf("Casove na: %f s\n", ((float)delayl[1]/rate));
400
    printf("vzdalenost: %f m\n", (SOUND_SPEED*(float)delayl[1]/rate));
401
 
402
    free(correlationl);
403
    free(correlationr);
404
    free(L_signal);
405
    free(R_signal);
406
    free(chirp);
407
    free(signal);
408
 
561 kaklik 409
    snd_pcm_close(playback_handle);
410
    snd_pcm_close(capture_handle);
411
    return 0;
558 kaklik 412
}
413