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