Subversion Repositories svnkaklik

Rev

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