Subversion Repositories svnkaklik

Rev

Rev 647 | 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)
646 kaklik 7
//$Id:$
558 kaklik 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
649 kaklik 23
#define Xl	-0.1		// microphones position
24
#define Xr	0.1
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;
646 kaklik 207
    float *echo_map;
562 kaklik 208
    int *L_signal, *R_signal;
209
    short *chirp, *signal;
623 kaklik 210
    float *chirp_spect, *lecho_spect, *recho_spect;
647 kaklik 211
    float a,b;
561 kaklik 212
    unsigned int i,j,m,n;
563 kaklik 213
    unsigned int delayl[10],delayr[10];	//store delay of signifed correlation
561 kaklik 214
    long int l,r;  // store correlation at strict time
563 kaklik 215
    double df;	//frequency resolution 
647 kaklik 216
    double k; // sample numbers to distance normalising constant
563 kaklik 217
    unsigned int frequency_bins; // number of output frequency bins 
558 kaklik 218
 
563 kaklik 219
    double *inchirp;
220
    fftw_complex *outchirp;
221
    fftw_plan fft_plan_chirp;
222
 
561 kaklik 223
    FILE *out;
558 kaklik 224
 
561 kaklik 225
    snd_pcm_hw_params_alloca(&hwparams);
226
    snd_pcm_sw_params_alloca(&swparams);
558 kaklik 227
 
646 kaklik 228
    printf("Simple PC sonar $Rev:$ starting work.. \n");
558 kaklik 229
 
230
//open and set playback device
561 kaklik 231
    if ((err = snd_pcm_open(&playback_handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0)
232
    {
233
        printf("Playback open error: %s\n", snd_strerror(err));
234
        return 0;
235
    }
558 kaklik 236
 
561 kaklik 237
    if ((err = set_hwparams(playback_handle, hwparams, 1)) < 0)
238
    {
239
        printf("Setting of hwparams failed: %s\n", snd_strerror(err));
240
        exit(EXIT_FAILURE);
241
    }
242
    if ((err = set_swparams(playback_handle, swparams)) < 0)
243
    {
244
        printf("Setting of swparams failed: %s\n", snd_strerror(err));
245
        exit(EXIT_FAILURE);
246
    }
247
 
558 kaklik 248
//open and set capture device
561 kaklik 249
    if ((err = snd_pcm_open(&capture_handle, device, SND_PCM_STREAM_CAPTURE, 0)) < 0)
250
    {
251
        printf("Playback open error: %s\n", snd_strerror(err));
252
        return 0;
253
    }
558 kaklik 254
 
561 kaklik 255
    if ((err = set_hwparams(capture_handle, hwparams, 2)) < 0)
256
    {
257
        printf("Setting of hwparams failed: %s\n", snd_strerror(err));
258
        exit(EXIT_FAILURE);
259
    }
260
    if ((err = set_swparams(capture_handle, swparams)) < 0)
261
    {
262
        printf("Setting of swparams failed: %s\n", snd_strerror(err));
263
        exit(EXIT_FAILURE);
264
    }
265
 
563 kaklik 266
    /*    err = snd_pcm_link( capture_handle, playback_handle); //link capture and playback together
267
        if (err < 0)
268
        {
269
            printf("Device linking error: %s\n", snd_strerror(err));
270
            exit(EXIT_FAILURE);
271
        }*/
558 kaklik 272
 
562 kaklik 273
    correlationl = malloc(period_size * sizeof(long int)); //array to store correlation curve
274
    correlationr = malloc(period_size * sizeof(long int)); //array to store correlation curve
275
    L_signal = malloc(period_size * sizeof(int));
276
    R_signal = malloc(period_size * sizeof(int));
277
    chirp = calloc(2*period_size, sizeof(short));
278
    signal = malloc(2*period_size * sizeof(short));
647 kaklik 279
    echo_map = malloc(3*period_size*period_size * sizeof(float));   // Array to store two dimensional image of echos
280
    if (echo_map == NULL) printf("Can't allocate enought memory");
558 kaklik 281
 
649 kaklik 282
    k = SOUND_SPEED/rate; // normalising constant
283
 
562 kaklik 284
// generate ping pattern
285
    chirp_size = linear_windowed_chirp(chirp);
286
 
563 kaklik 287
    frequency_bins = chirp_size / 2 + 1;
288
    df = (double) rate / (double) chirp_size;
289
    chirp_spect = malloc(frequency_bins * sizeof(float));
623 kaklik 290
    lecho_spect = malloc(frequency_bins * sizeof(float));
291
    recho_spect = malloc(frequency_bins * sizeof(float));
563 kaklik 292
 
293
    inchirp = fftw_malloc(sizeof(double) * chirp_size); 		// allocate input array for FFT
294
    outchirp = fftw_malloc(sizeof(fftw_complex) * frequency_bins);
295
 
296
    fft_plan_chirp = fftw_plan_dft_r2c_1d(chirp_size, inchirp, outchirp, FFTW_ESTIMATE);
297
 
298
    printf("compute chirp spectrum\n");
299
    for(i=0; i < chirp_size; i++) inchirp[i] = chirp[i];
300
    fftw_execute(fft_plan_chirp);
301
    for(i=0; i < frequency_bins; i++) chirp_spect[i] = sqrt( outchirp[i][0] * outchirp[i][0] + outchirp[i][1] * outchirp[i][1] );
302
 
303
// write chirp data to souncard buffer
561 kaklik 304
    err = snd_pcm_writei(playback_handle, chirp, period_size);
305
    if (err < 0)
306
    {
307
        printf("Initial write error: %s\n", snd_strerror(err));
308
        exit(EXIT_FAILURE);
309
    }
560 kaklik 310
 
562 kaklik 311
//start sream
312
    err = snd_pcm_start(playback_handle);
561 kaklik 313
    if (err < 0)
314
    {
562 kaklik 315
        printf("Start error: %s\n", snd_strerror(err));
561 kaklik 316
        exit(EXIT_FAILURE);
317
    }
558 kaklik 318
 
562 kaklik 319
    err = snd_pcm_start(capture_handle);
561 kaklik 320
    if (err < 0)
321
    {
322
        printf("Start error: %s\n", snd_strerror(err));
323
        exit(EXIT_FAILURE);
324
    }
640 kaklik 325
    else printf("Transmitting all samples of chirp\n");
562 kaklik 326
//--------------
564 kaklik 327
 
328
    while ( snd_pcm_avail_update(capture_handle) < period_size)			// wait for one period of data
561 kaklik 329
    {
330
        usleep(1000);
331
        printf(".");
332
    }
558 kaklik 333
 
564 kaklik 334
    err = snd_pcm_drop(playback_handle);		// stop audio stream
562 kaklik 335
    err = snd_pcm_drain(capture_handle);
561 kaklik 336
    if (err < 0)
337
    {
338
        printf("Stop error: %s\n", snd_strerror(err));
339
        exit(EXIT_FAILURE);
340
    }
558 kaklik 341
 
564 kaklik 342
    err = snd_pcm_readi(capture_handle, signal, period_size);		//read period from audio buffer
562 kaklik 343
    if (err < 0)
344
    {
345
        printf("Read error: %s\n", snd_strerror(err));
346
        exit(EXIT_FAILURE);
347
    }
558 kaklik 348
 
561 kaklik 349
    j=0;
562 kaklik 350
    for (i=0;i < period_size;i++)		// separe inretleaved samples to two arrays
561 kaklik 351
    {
352
        L_signal[i]=signal[j];
353
        R_signal[i]=signal[j+1];
354
        j+=2;
355
    }
558 kaklik 356
 
562 kaklik 357
    printf("\nData transmitted \ncorrelating\n");
358
    for (n=0; n < (period_size - chirp_size - 1); n++)
561 kaklik 359
    {
360
        l=0;
361
        r=0;
563 kaklik 362
        for ( m = 0; m < chirp_size;m++)
561 kaklik 363
        {
558 kaklik 364
            l += chirp[m]*L_signal[m+n];	// correlate with left channel
365
            r += chirp[m]*R_signal[m+n];	// correlate with right channel
561 kaklik 366
        }
563 kaklik 367
        correlationl[n]=abs(l);
368
        correlationr[n]=abs(r);
561 kaklik 369
    }
558 kaklik 370
 
646 kaklik 371
    m=0;
643 kaklik 372
    printf("Building echo map\n");		// compute map from left and right correlation data
647 kaklik 373
	for (i=0;i < period_size; i+=10)
644 kaklik 374
	{
647 kaklik 375
		a=k*i;
376
		for(j=0;j < period_size; j+=10)
646 kaklik 377
		{
647 kaklik 378
			b=k*j;
649 kaklik 379
			echo_map[m]=(-a*a+b*b+Xl*Xl+Xr*Xr)/(2*Xl-2*Xr);
380
			echo_map[m+1]=sqrt((a-b-Xl-Xr)*(a+b+Xl+Xr)*(a-b-Xl+Xr)*(a-b-Xl+Xr)*(a+b-Xl+Xr))/(-2*(Xl-Xr));
646 kaklik 381
			echo_map[m+2]=correlationl[i]*correlationr[j];
382
			m+=3;
383
		}
644 kaklik 384
	}
562 kaklik 385
    printf("Searching echos\n");
561 kaklik 386
    r=0;
387
    l=0;
562 kaklik 388
    for (n=0; n < period_size;n++) 			//najde nejvetsi korelace
561 kaklik 389
    {
390
        if (l < correlationl[n])
391
        {
563 kaklik 392
            delayl[1] = n;
561 kaklik 393
            l = correlationl[n];
394
        }
395
        if (r < correlationr[n])
396
        {
563 kaklik 397
            delayr[1] = n;
561 kaklik 398
            r = correlationr[n];
399
        }
400
    }
558 kaklik 401
 
646 kaklik 402
//spocitej frekvencni spektrum pro levy kanal
564 kaklik 403
    for(i=delayl[1]; i < delayl[1] + chirp_size; i++) inchirp[i-delayl[1]] = L_signal[i];
404
    fftw_execute(fft_plan_chirp);
623 kaklik 405
    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 406
 
641 kaklik 407
 
408
// napln pole daty z praveho kanalu a spocitej frekvencni spektrum
623 kaklik 409
    for(i=delayr[1]; i < delayr[1] + chirp_size; i++) inchirp[i-delayr[1]] = R_signal[i];
410
    fftw_execute(fft_plan_chirp);
411
    for(i=0; i < frequency_bins; i++) recho_spect[i] = sqrt(outchirp[i][0] * outchirp[i][0] + outchirp[i][1] * outchirp[i][1]);
412
 
564 kaklik 413
    printf("Writing output files\n");
561 kaklik 414
    out=fopen("/tmp/sonar.txt","w");
563 kaklik 415
    for (i=0; i <= (period_size - 1); i++)
561 kaklik 416
    {
647 kaklik 417
        fprintf(out,"%2.3f %6d %6d %9ld %9ld\n", (float)i*k, L_signal[i], R_signal[i], correlationl[i], correlationr[i]);
561 kaklik 418
    }
419
    fclose(out);
558 kaklik 420
 
646 kaklik 421
    j=0;
644 kaklik 422
    out=fopen("/tmp/plane_cut.txt","w"); // writes plane cut - e.g. density map to file
649 kaklik 423
    for (i=0;i < period_size*period_size/100; i++)
643 kaklik 424
    {
647 kaklik 425
	fprintf(out,"%3.3f %3.3f %3.3f\n", echo_map[j], echo_map[j+1], echo_map[j+2]);
646 kaklik 426
	j+=3;
643 kaklik 427
    }
647 kaklik 428
    fclose(out);
643 kaklik 429
 
563 kaklik 430
    out=fopen("/tmp/chirp.txt","w");
431
    for (i=0; i <= (chirp_size - 1); i++)
432
    {
564 kaklik 433
        fprintf(out,"%6d %6d\n", i, chirp[i]);
563 kaklik 434
    }
435
    fclose(out);
558 kaklik 436
 
564 kaklik 437
    out=fopen("/tmp/echo.txt","w");
623 kaklik 438
    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 439
    fclose(out);
440
 
441
    out=fopen("/tmp/spektra.txt","w");
442
    for (i=0; i < frequency_bins; i++)
443
    {
623 kaklik 444
        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 445
    }
446
    fclose(out);
447
 
563 kaklik 448
    free(correlationl);
449
    free(correlationr);
450
    free(L_signal);
451
    free(R_signal);
452
    free(chirp);
453
    free(signal);
646 kaklik 454
    free(echo_map);
563 kaklik 455
 
561 kaklik 456
    snd_pcm_close(playback_handle);
457
    snd_pcm_close(capture_handle);
458
    return 0;
558 kaklik 459
}
460