Subversion Repositories svnkaklik

Rev

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