Subversion Repositories svnkaklik

Rev

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

Rev Author Line No. Line
532 kaklik 1
///////////////////////////////////////////////////////////////////////////////////
2
//                        This small demo of sonar.
3
// Program allow distance measuring.
4
//
5
//
6
///////////////////////////////////////////////////////////////////////////////////
526 kaklik 7
 
8
#include <stdio.h>
9
#include <stdlib.h>
10
#include <string.h>
11
#include <sched.h>
12
#include <errno.h>
13
#include <getopt.h>
14
#include <alsa/asoundlib.h>
15
#include <sys/time.h>
16
#include <math.h>
17
 
18
static char *device = "plughw:0,0";			/* playback device */
19
static snd_pcm_format_t format = SND_PCM_FORMAT_S16;	/* sample format */
536 kaklik 20
static unsigned int rate = 98000;			/* stream rate */
526 kaklik 21
static unsigned int channels = 1;			/* count of channels */
22
static unsigned int buffer_time = 500000;		/* ring buffer length in us */
23
static unsigned int period_time = 100000;		/* period time in us */
24
static int verbose = 0;					/* verbose flag */
25
static int resample = 1;				/* enable alsa-lib resampling */
26
static int period_event = 0;				/* produce poll event after each period */
27
 
533 kaklik 28
#define SOUND_SPEED	340
538 kaklik 29
#define SIGNAL_SAMPLES 100000
533 kaklik 30
 
531 kaklik 31
unsigned int chirp_size;
527 kaklik 32
 
526 kaklik 33
int period=0;
527 kaklik 34
int cperiod=0;
532 kaklik 35
int chirp[100000];
36
short signal[1000000];		// record 6s of input samples
526 kaklik 37
 
38
static snd_pcm_sframes_t buffer_size;	// size of buffer at sound card
39
static snd_pcm_sframes_t period_size;	//samples per frame
40
static snd_output_t *output = NULL;
41
 
42
static int set_hwparams(snd_pcm_t *handle,
43
			snd_pcm_hw_params_t *params,
44
			snd_pcm_access_t access)
45
{
46
	unsigned int rrate;
47
	snd_pcm_uframes_t size;
48
	int err, dir;
49
 
50
	/* choose all parameters */
51
	err = snd_pcm_hw_params_any(handle, params);
52
	if (err < 0) {
53
		printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
54
		return err;
55
	}
56
	/* set hardware resampling */
57
	err = snd_pcm_hw_params_set_rate_resample(handle, params, resample);
58
	if (err < 0) {
59
		printf("Resampling setup failed for playback: %s\n", snd_strerror(err));
60
		return err;
61
	}
62
	/* set the interleaved read/write format */
63
	err = snd_pcm_hw_params_set_access(handle, params, access);
64
	if (err < 0) {
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
		printf("Sample format not available for playback: %s\n", snd_strerror(err));
72
		return err;
73
	}
74
	/* set the count of channels */
75
	err = snd_pcm_hw_params_set_channels(handle, params, channels);
76
	if (err < 0) {
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
		printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
85
		return err;
86
	}
87
	if (rrate != rate) {
88
		printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
89
		return -EINVAL;
90
	}
537 kaklik 91
	else printf("Rate set to %i Hz\n", rate, err); 
526 kaklik 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
		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
		printf("Unable to get buffer size for playback: %s\n", snd_strerror(err));
101
		return err;
102
	}
103
	buffer_size = size;
104
	/* set the period time */
105
	err = snd_pcm_hw_params_set_period_time_near(handle, params, &period_time, &dir);
106
	if (err < 0) {
107
		printf("Unable to set period time %i for playback: %s\n", period_time, snd_strerror(err));
108
		return err;
109
	}
110
	err = snd_pcm_hw_params_get_period_size(params, &size, &dir);
111
	if (err < 0) {
112
		printf("Unable to get period size for playback: %s\n", snd_strerror(err));
113
		return err;
114
	}
115
	period_size = size;
116
	/* write the parameters to device */
117
	err = snd_pcm_hw_params(handle, params);
118
	if (err < 0) {
119
		printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
120
		return err;
121
	}
122
	return 0;
123
}
124
 
125
static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams)
126
{
127
	int err;
128
 
129
	/* get the current swparams */
130
	err = snd_pcm_sw_params_current(handle, swparams);
131
	if (err < 0) {
132
		printf("Unable to determine current swparams for playback: %s\n", snd_strerror(err));
133
		return err;
134
	}
135
	/* start the transfer when the buffer is almost full: */
136
	/* (buffer_size / avail_min) * avail_min */
137
	err = snd_pcm_sw_params_set_start_threshold(handle, swparams, (buffer_size / period_size) * period_size);
138
	if (err < 0) {
139
		printf("Unable to set start threshold mode for playback: %s\n", snd_strerror(err));
140
		return err;
141
	}
142
	/* allow the transfer when at least period_size samples can be processed */
143
	/* or disable this mechanism when period event is enabled (aka interrupt like style processing) */
144
	err = snd_pcm_sw_params_set_avail_min(handle, swparams, period_event ? buffer_size : period_size);
145
	if (err < 0) {
146
		printf("Unable to set avail min for playback: %s\n", snd_strerror(err));
147
		return err;
148
	}
149
	/* enable period events when requested */
150
	if (period_event) {
151
		err = snd_pcm_sw_params_set_period_event(handle, swparams, 1);
152
		if (err < 0) {
153
			printf("Unable to set period event: %s\n", snd_strerror(err));
154
			return err;
155
		}
156
	}
157
	/* write the parameters to the playback device */
158
	err = snd_pcm_sw_params(handle, swparams);
159
	if (err < 0) {
160
		printf("Unable to set sw params for playback: %s\n", snd_strerror(err));
161
		return err;
162
	}
163
	return 0;
164
}
165
 
166
struct async_private_data {
167
	signed short *samples;
168
	snd_pcm_channel_area_t *areas;
169
	unsigned int period;
170
};
171
 
172
/*int linear_chirp(int *pole, int delka_pole){  // vygeneruje linearni chirp a vzorky ulozi do pole
173
 
174
static const float f0 = 0.0001;
175
static const float k = 0.00001;
176
 
177
int t;
178
 
179
//  if((spozdeni+delka) < delka_pole)
180
    for(t=0;t < delka_pole;t++) pole[t] = round ( 10000*sin(2*M_PI*(t+faze)*(f0+(k/2)*(t+faze))) );
181
    faze +=t;
182
//  else return 0;
183
 
527 kaklik 184
}*/
526 kaklik 185
 
532 kaklik 186
// vygeneruje linearni chirp a vzorky ulozi do pole
187
unsigned int linear_windowed_chirp(unsigned int *pole, unsigned int delka_pole)
188
{  
527 kaklik 189
unsigned int maxval = (1 << (snd_pcm_format_width(format) - 1)) - 1;
526 kaklik 190
 
538 kaklik 191
static const float f0 = 3000;
192
static const float fmax = 5000;
536 kaklik 193
static const float Tw = 0.002;
527 kaklik 194
static float k;
526 kaklik 195
 
531 kaklik 196
unsigned int n=0;
197
double t;
198
unsigned int perioda;
526 kaklik 199
 
532 kaklik 200
  k=2*(fmax-f0)/Tw;
201
  perioda = rate*Tw; 
526 kaklik 202
 
532 kaklik 203
  for(n=0;n<=perioda;n++){
204
     t = (double) n/ (double)rate;
205
     pole[n] = (short) round ( (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))) );
206
  }
207
  return perioda;
527 kaklik 208
}
209
 
532 kaklik 210
// generate sine samples and store
531 kaklik 211
int sine(unsigned int *pole, unsigned int delka_pole)
526 kaklik 212
{
527 kaklik 213
unsigned int maxval = (1 << (snd_pcm_format_width(format) - 1)) - 1;
531 kaklik 214
unsigned int n;
215
double t;
216
 
217
  for(n=0;n < delka_pole;n++){
218
    t = 440.0 * (double) n/ (double)rate;
219
    pole[n] = (short) round(maxval*sin(2*M_PI*t));
220
  }
526 kaklik 221
}
222
 
223
 
224
 
225
static void async_playback_callback(snd_async_handler_t *ahandler)
226
{
227
	snd_pcm_t *handle = snd_async_handler_get_pcm(ahandler);
527 kaklik 228
/*	struct async_private_data *data = snd_async_handler_get_callback_private(ahandler);
526 kaklik 229
	signed short *samples = data->samples;
527 kaklik 230
	snd_pcm_channel_area_t *areas = data->areas;*/
526 kaklik 231
	snd_pcm_sframes_t avail;
232
	int err;
233
 
234
	avail = snd_pcm_avail_update(handle);
531 kaklik 235
	while ((avail >= period_size) && ((period*period_size) < chirp_size) ) {
526 kaklik 236
 
527 kaklik 237
		err = snd_pcm_writei(handle, (chirp+period*period_size), period_size);
526 kaklik 238
		if (err < 0) {
239
			printf("Write error: %s\n", snd_strerror(err));
240
			exit(EXIT_FAILURE);
241
		}
242
		if (err != period_size) {
243
			printf("Write error: written %i expected %li\n", err, period_size);
244
			exit(EXIT_FAILURE);
245
		}
246
		avail = snd_pcm_avail_update(handle);
527 kaklik 247
		period++;
526 kaklik 248
	}
249
}
250
 
527 kaklik 251
static void async_capture_callback(snd_async_handler_t *ahandler)
252
{
253
	snd_pcm_t *handle = snd_async_handler_get_pcm(ahandler);
254
/*	struct async_private_data *data = snd_async_handler_get_callback_private(ahandler);
255
	signed short *samples = data->samples;
256
	snd_pcm_channel_area_t *areas = data->areas;*/
257
	snd_pcm_sframes_t avail;
258
	int err;
259
 
260
	avail = snd_pcm_avail_update(handle);
532 kaklik 261
	while ((avail >= period_size) /*&& ((period*period_size) < (CHIRP_SIZE-100))*/ ) {  // segmentation fault checking disabled
527 kaklik 262
 
263
		err = snd_pcm_readi(handle, (signal+cperiod*period_size), period_size);
264
		if (err < 0) {
265
			printf("Read error: %s\n", snd_strerror(err));
266
			exit(EXIT_FAILURE);
267
		}
268
		if (err != period_size) {
269
			printf("Read error: red %i expected %li\n", err, period_size);
270
			exit(EXIT_FAILURE);
271
		}
272
		avail = snd_pcm_avail_update(handle);
273
		cperiod++;
531 kaklik 274
	}
527 kaklik 275
}
276
 
277
 
526 kaklik 278
int main(int argc, char *argv[])
279
{
280
	snd_pcm_t *playback_handle, *capture_handle;
281
	int err;
282
	snd_pcm_hw_params_t *hwparams;
283
	snd_pcm_sw_params_t *swparams;
284
	signed short *frame;  // pointer to array of samples
285
	unsigned int chn;
286
	snd_pcm_channel_area_t *areas;
287
 
288
	struct async_private_data data;
527 kaklik 289
	snd_async_handler_t *chandler, *phandler;
526 kaklik 290
	int count;
532 kaklik 291
	unsigned int i,j,m,n;
536 kaklik 292
	unsigned int delay[10];	//store delay of signifed correlation
532 kaklik 293
  	double r;
294
	double correlation[1000000]; //array to store correlation curve
526 kaklik 295
 
527 kaklik 296
	FILE *out;
526 kaklik 297
 
298
	snd_pcm_hw_params_alloca(&hwparams);
299
	snd_pcm_sw_params_alloca(&swparams);
300
 
537 kaklik 301
 
532 kaklik 302
//open and set playback device
526 kaklik 303
	if ((err = snd_pcm_open(&playback_handle, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
304
		printf("Playback open error: %s\n", snd_strerror(err));
305
		return 0;
306
	}
307
 
308
	if ((err = set_hwparams(playback_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
309
		printf("Setting of hwparams failed: %s\n", snd_strerror(err));
310
		exit(EXIT_FAILURE);
311
	}
312
	if ((err = set_swparams(playback_handle, swparams)) < 0) {
313
		printf("Setting of swparams failed: %s\n", snd_strerror(err));
314
		exit(EXIT_FAILURE);
315
	}
316
 
317
//open and set capture device
318
	if ((err = snd_pcm_open(&capture_handle, device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
319
		printf("Playback open error: %s\n", snd_strerror(err));
320
		return 0;
321
	}
322
 
323
	if ((err = set_hwparams(capture_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
324
		printf("Setting of hwparams failed: %s\n", snd_strerror(err));
325
		exit(EXIT_FAILURE);
326
	}
530 kaklik 327
	if ((err = set_swparams(capture_handle, swparams)) < 0) {
526 kaklik 328
		printf("Setting of swparams failed: %s\n", snd_strerror(err));
329
		exit(EXIT_FAILURE);
530 kaklik 330
	}
526 kaklik 331
 
531 kaklik 332
        chirp_size=linear_windowed_chirp(chirp,1000000);
526 kaklik 333
 
527 kaklik 334
/// register playback callback 
335
	err = snd_async_add_pcm_handler(&phandler, playback_handle, async_playback_callback, &data); // fill by dummy &data
526 kaklik 336
	if (err < 0) {
337
		printf("Unable to register async handler\n");
338
		exit(EXIT_FAILURE);
339
	}
531 kaklik 340
	for (period = 0; period < 2; period++) {
526 kaklik 341
 
527 kaklik 342
		err = snd_pcm_writei(playback_handle, (chirp+period*period_size), period_size);
526 kaklik 343
		if (err < 0) {
344
			printf("Initial write error: %s\n", snd_strerror(err));
345
			exit(EXIT_FAILURE);
346
		}
347
		if (err != period_size) {
348
			printf("Initial write error: written %i expected %li\n", err, period_size);
349
			exit(EXIT_FAILURE);
350
		}
351
	}
352
 
527 kaklik 353
// register capture callback 
354
	err = snd_async_add_pcm_handler(&chandler, capture_handle, async_capture_callback, &data); // fill by dummy &data
355
	if (err < 0) {
356
		printf("Unable to register async handler\n");
357
		exit(EXIT_FAILURE);
358
	}
359
 
526 kaklik 360
 
527 kaklik 361
//start capture
362
	if ((err = snd_pcm_prepare (capture_handle)) < 0) {
363
		fprintf (stderr, "cannot prepare audio interface for use (%s)\n",
364
			 snd_strerror (err));
365
		exit (1);
366
	}
367
 
368
	err = snd_pcm_start(capture_handle);
369
	if (err < 0) {
370
			printf("Start error: %s\n", snd_strerror(err));
371
			exit(EXIT_FAILURE);
372
	}
538 kaklik 373
 
374
 
375
//start playback
376
	if (snd_pcm_state(playback_handle) == SND_PCM_STATE_PREPARED) {
377
		err = snd_pcm_start(playback_handle);
378
		if (err < 0) {
379
			printf("Start error: %s\n", snd_strerror(err));
380
			exit(EXIT_FAILURE);
381
		}
382
	}
383
 
527 kaklik 384
 
532 kaklik 385
//wait until all samples aren't transmitted
386
	printf("Waiting for transmitt all samples\n");
531 kaklik 387
	while(cperiod<10) {
526 kaklik 388
		sleep(1);
532 kaklik 389
		printf(".");
527 kaklik 390
	}	
537 kaklik 391
	printf("\nData transmitted... \ncorrelating...\n");
526 kaklik 392
 
533 kaklik 393
	for(n=0; n < (SIGNAL_SAMPLES - chirp_size);n++){			//spocita korelaci pro mozna spozdeni
394
	  r=0;
538 kaklik 395
	  for(m=chirp_size;m > 0;m--) r += chirp[m]*signal[m+n];	// reverse echo patern
396
	  correlation[n]=abs(r);
533 kaklik 397
	}
532 kaklik 398
 
537 kaklik 399
	printf("\nFinding echos...\n");
533 kaklik 400
	r=0;
536 kaklik 401
	for(n=0; n < (SIGNAL_SAMPLES - chirp_size);n++){			//najde nejvetsi korelace
533 kaklik 402
	  if (r < correlation[n]){
536 kaklik 403
	  delay[1] = n;
533 kaklik 404
	  r = correlation[n];
405
	  }
406
	}
532 kaklik 407
 
536 kaklik 408
	out=fopen("./output.txt","w");
409
	for(i=0;i<=100000;i++) fprintf(out,"%6d	%6d %6d %6.2f\n",i,chirp[i],signal[i],correlation[i]); 
410
	fclose(out);
532 kaklik 411
 
536 kaklik 412
	printf("\nEcho zacina na: %d vzorku.\n", delay[1]);
413
	printf("Casove na: %f s\n", ((float)delay[1]/rate));
414
	printf("vzdalenost: %f m\n", (SOUND_SPEED*(float)delay[1]/rate));
415
 
526 kaklik 416
	snd_pcm_close(playback_handle);
417
	snd_pcm_close(capture_handle);
418
	return 0;
419
}
420