##// END OF EJS Templates
imanay -
r246:247
parent child
Show More
@@ -1,1196 +1,1287
1 1 /*
2 2 * Servidor.c
3 3 *
4 4 * Created on: Nov 3, 2009
5 5 * Author: Jose Francisco Quenta
6 6 *
7 7 * Se implementa:
8 8 * -Carga en memoria los apuntes contenidos en un archivo de experimentos: apunte0 -> GPIO
9 9 * -Cambio de apunte.
10 10 * -Lectura del estado actual del apunte y grabado del mismo en un archivo
11 11 *
12 12 * Modified by Iván Manay since Nov 2012
13 13 * -From UDP to TCP.
14 14 * -Use of a frame for TCP communications with the central control module.
15 15 */
16 16
17 17 #include <stdio.h>
18 18 #include <stdlib.h>
19 19 #include <string.h>
20 20 #include <unistd.h>
21 21 #include <errno.h>
22 22
23 23 #include <sys/types.h>
24 24 #include <sys/socket.h>
25 25 #include <netinet/in.h>
26 26 #include <arpa/inet.h>
27 27 #include <netdb.h>
28 28 #include <time.h>
29 29 #include <math.h>
30 30
31 31 #include "./Librerias/at91gpio.h"
32 32 //#include "./Librerias/Mensajes.h"
33 33 #include "./Librerias/at91adc.h"
34 34 //clock
35 35 #include "./Librerias/at91sysclock.h"
36 36
37 37 #define PUERTO_SERVIDOR 5500
38 38 #define TAM_BUFFER 1024
39 39
40 40 #define maskc_out_beam PC30+PC28+PC26+PC24+PC22+PC20 //MSB-UP-LSB MSB-DOWN-LSB //APUNTE
41 41 #define maskc_out_cntl PC4+PC5+PC6 //MONITORING CONTROL
42 42
43 43 #define mask_sel_canal PC4 //MONITORING CONTROL
44 44 #define mask_sel_atenuacion PC5
45 45 #define mask_sel_calibracion PC6
46 46
47 47 #define maskb_in PB16+PB18+PB20+PB30+PB24+PB22 //MSB-UP-LSB MSB-DOWN-LSB //VERIFICACION
48 48
49 49 #define maskc_in_adc PC0+PC1
50 50
51 51 #define bit_up_2 0x00010000 //Mascara de cada bit a revisar: bit_up_2 es MSB
52 52 #define bit_up_1 0x00040000
53 53 #define bit_up_0 0x00100000
54 54 #define bit_dow_2 0x40000000
55 55 #define bit_dow_1 0x01000000
56 56 #define bit_dow_0 0x00400000
57 57
58 58 #define MyID 11
59 59 #define MAXPENDING 5 /* Maximum outstanding connection requests */
60 60
61 61 //parameters for the name of the output file
62 62 #define FPRE "AD" //prefix for the output file name
63 63 #define FEXT ".out" //file extension for the output file
64 64 #define FNAMELEN 40
65 65
66 66 //ADC parameters
67 67 #define REP 1 //defines how many times the data acquisation loop is repeated
68 68 #define NSAMPLES 10 //defines how many samples are taken in one data acqu-
69 69 // isation loop
70 70
71 71 #define NLOOPS 200 // Number of loops for the transmisor checking
72 72 #define CNVTIME 14.3 //defines how long it takes to get one sample. Value
73 73 // is only needed for the output file, doesn't change
74 74 // any ADC configurations
75 75 #define UREF 3.3 //Reference Voltage of ADC (max. ADC Voltage)
76 76 #define ADCRES 1023 //Resolution of ADC (10bit=1023)
77 77
78 78
79 79 char *buff_experimento= NULL;
80 //char *cbeam = malloc(7);
81 char *cbeam = NULL;
80 82
81 83 AT91S_PIO *pioc;
82 84 AT91S_PIO *piob;
83 85 AT91S_PIO *pio_adc;
84 86 AT91S_ADC *padc;
85 87 AT91S_ADC *padd;
86 88
87 89 struct control_module_parameters {
88 90 char ID[20];
89 91 char param2[20];
90 92 char param3[20];
91 93 char param4[20];
92 94 };
93 95
94 96 typedef struct control_module_parameters cmp;
95 97
96 98 char *header = NULL;
97 99 char *TypeOfInstrument = NULL;
98 100 char *iDSource = NULL;
99 101 char *iDDestino = NULL;
100 102 char *rx_len = NULL;
101 103 char *cmd = NULL;
102 104 char *rx_data = NULL;
103 105 char *crc = NULL;
104 106
105 107 cmp parameters;
106 108 /*
107 109 * Zona de declaracion de cabeceras.
108 110 */
109 111 cmp inicializa_modulo(cmp p, char *filename);
110 112 int inicializa_ethernet();
111 113 int rxData(int, char*);
112 114 void txData(int, char*);
113 115 void inicializa_gpio();
114 116 void inicializa_adc();
115 117 void procesa_peticion(char *rx_buffer, char *tx_buffer);
116 118 int cambia_apuntamiento(char *puntero_char);
117 119 int carga_experimento(char *nombre_archivo);
118 120 char *chequeo_sistema(char *filename, char *numero_muestras);
121 char *chequeo_sistema2();
119 122 void escribe_experimento(char *data, char filename[]);
120 123 char *Lee_experimento(char *filename);
121 124 void consigue_nombre_experimento(char *rx_data, char filename[]);
122 125 void SplitFrame(char *frame);
123 126 void intToStr( int number, char* str );
124 127 int update_app(char *filename, char *ip_number);
125 128
126 129 //ABS monitoring
127 130 //int ABS_monitoreo(int sel_atenuador, int sel_calibracion, float umbral, int pulsewidth);
128 131 char* ABS_monitoreo(int sel_atenuador, int sel_calibracion, float umbral, int pulsewidth);
129 132 AT91S_ADC * configADC1(void);
130 133 AT91S_ADC * configADC2(void);
131 134
132 135 FILE * create_Output(char*, time_t);
133 136
134 137 void writeOutput(float resultado, FILE * output);
135 138
136 139 int checkTx(long int results1[],long int results2[], float umbral, int pulsewidth);
137 140
138 141 double mediana(long int *results, unsigned int cuenta);
139 142 float getPhase(long int results1[], long int results2[]);
140 143
141 144 int fExists(char *);
142 145 int configCLK();
143 146 //
144 147
145 148 /*
146 149 *
147 150 */
148 151 int main(int argc, char *argv[]){
149 152 // arg[1] : Archivo de configuracion del modulo de control
150 153 int servSocket;
151 154 int clntSocket;
152 155
153 156 char *rx_buffer = (char *) malloc(TAM_BUFFER);
154 157 char *tx_buffer = (char *) malloc(TAM_BUFFER);
155 158 /* Inicializa parametros del modulo*/
156 159 parameters = inicializa_modulo(parameters, argv[1]);
157 160 printf("%s\n%s\n%s\n%s\n",parameters.ID, parameters.param2, parameters.param3, parameters.param4);
158 161 /* Inicializa red*/
159 162 servSocket = inicializa_ethernet();
160 163 /* Inicializamos el puerto GPIO del sistema embebido GSBC-9260S */
161 164 inicializa_gpio();
162 165 inicializa_adc();
163 166
164 167 while(1){
165 168 // Recepción TCP de petición
166 169 clntSocket = rxData(servSocket, rx_buffer);
167 170 //testpoint
168 171 printf("rx:%s\n",rx_buffer);
169 172 // Procesamiento de la petición
170 173 procesa_peticion(rx_buffer, tx_buffer);
171 174 //testpoint
172 175 printf("tx:%s\n",tx_buffer);
173 176 // Respuesta del modulo de control
174 177 txData(clntSocket, tx_buffer);
175 178
176 179 }
177 180 }
178 181
179 182
180 183 int inicializa_ethernet(){
181 184
182 185 struct sockaddr_in inf_servidor;
183 186
184 187 int servSocket;
185 188
186 189 int resultado;
187 190
188 191 /* Haciendo la estructura local*/
189 192 memset(&inf_servidor, 0, sizeof(inf_servidor));
190 193 inf_servidor.sin_family= AF_INET;
191 194 inf_servidor.sin_port= htons(PUERTO_SERVIDOR);
192 195 inf_servidor.sin_addr.s_addr= INADDR_ANY;
193 196
194 197 /* Se establece el socket */
195 198 servSocket = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
196 199 if (servSocket == -1){
197 200 printf("No se establecio correctamente el socket: socket()\n");
198 201 //ERROR_FATAL("No se establecio correctamente el socket: socket()\n");
199 202 exit(-1);
200 203 }
201 204
202 205 /* Se asocia el socket a un puerto y una IP */
203 206 resultado = bind(servSocket,(struct sockaddr *)&inf_servidor,sizeof(inf_servidor));
204 207 if (resultado== -1){
205 208 printf("No se establecio correctamente el socket: bind()\n");
206 209 //ERROR_FATAL("No se establecio correctamente el socket: bind()\n");
207 210 exit(-1);
208 211 }
209 212
210 213 if (listen(servSocket, MAXPENDING) < 0){
211 214 printf("listen() failed\n");
212 215 exit(-1);
213 216 }
214 217
215 218 return servSocket;
216 219
217 220 }
218 221
219 222 int rxData(int servSocket, char* rx_buffer){
220 223
221 224 int clntSocket;
222 225 struct sockaddr_in inf_cliente;
223 226 int numbytes_recibidos;
224 227 unsigned int inf_client_Len;
225 228
226 229 printf("\nEsperando solicitud de cliente...\n");
227 230
228 231 /* Set the size of the in-out parameter */
229 232 inf_client_Len = sizeof(inf_cliente);
230 233 /* Se espera hasta que un cliente se conecte */
231 234 if ((clntSocket = accept(servSocket, (struct sockaddr *) &inf_cliente,
232 235 &inf_client_Len)) < 0)
233 236 printf("accept() failed\n");
234 237
235 238 if ((numbytes_recibidos = recv(clntSocket, rx_buffer, TAM_BUFFER, 0)) < 0)
236 239 printf("recv() failed\n");
237 240
238 241 /* Se procede a procesar los datos recibidos */
239 242 rx_buffer[numbytes_recibidos]= '\0';
240 243
241 244 return clntSocket;
242 245 }
243 246
244 247 void txData(int clntSocket, char* data){
245 248
246 249 /* Echo message back to client */
247 250 if (send(clntSocket, data, strlen(data), 0) != strlen(data))
248 251 printf("send() failed\n");
249 252
250 253 close(clntSocket); /* Close client socket */
251 254 }
252 255
253 256 /*
254 257 * Esta funcion incializa el puerto GPIO
255 258 */
256 259 void inicializa_gpio(){
257 260
258 261 int desplazamiento_beam[6]={30,28,26,24,22,20}; //Desplazamientos para los pines de apunte
259 262 int desplazamiento_cntl[3]={4,5,6}; //Desplazamientos para los pines de control de monitoreo
260 263 unsigned long acumulado_ceros=0;
261 264 int i;
262 265
263 266 // Configuracion de los pines de APUNTE y control de monitoreo
264 267 pioc = pio_map(PIOC_BASE);
265 268 pio_enable(pioc, maskc_out_beam + maskc_out_cntl);
266 269 pio_disable_irq(pioc, maskc_out_beam + maskc_out_cntl);
267 270 pio_disable_multiple_driver(pioc, maskc_out_beam + maskc_out_cntl);
268 271 pio_disable_pull_ups(pioc, maskc_out_beam + maskc_out_cntl);
269 272 pio_synchronous_data_output(pioc, maskc_out_beam + maskc_out_cntl);
270 273 pio_output_enable(pioc, maskc_out_beam + maskc_out_cntl);
271 274
272 275 // Configuracion de los pines de VERIFICACION
273 276 piob = pio_map(PIOB_BASE);
274 277 pio_enable(piob, maskb_in);
275 278 pio_disable_irq(piob, maskb_in);
276 279 pio_disable_multiple_driver(piob, maskb_in);
277 280 pio_disable_pull_ups(piob, maskb_in);
278 281 pio_input_enable(piob, maskb_in);
279 282
280 283 //Pînes de ADC
281 284 pio_adc = pio_map(PIOC_BASE);
282 285 pin_adc_enable(pio_adc,maskc_in_adc); //Habilitamos PC0 para usar con ADC0 y 1
283 286 pio_disable_irq(pio_adc, maskc_in_adc);
284 287 pio_disable_multiple_driver(pio_adc, maskc_in_adc);
285 288 pio_disable_pull_ups(pio_adc, maskc_in_adc);
286 289 pio_input_enable(pio_adc, maskc_in_adc);
287 290
288 291 //Inicializando a cero los pines de apunte
289 292 for(i=0;i<6;i++)
290 293 acumulado_ceros= acumulado_ceros + (1 << desplazamiento_beam[i]);
291 294 pio_out(pioc, maskc_out_beam, acumulado_ceros, 0);
292 295
293 296 //Inicializando a cero los pines de control de monitoreo: atenuacion, calibracion y canal
294 297 for(i=0;i<3;i++)
295 298 acumulado_ceros= acumulado_ceros + (1 << desplazamiento_cntl[i]);
296 299 pio_out(pioc, maskc_out_cntl, acumulado_ceros, 0);
297 300
298 301 }
299 302
300 303 void inicializa_adc(){
301 304
302 305 if (configCLK() == 1)
303 306 printf("clock ADC enable.\n");
304 307 //configure ADC Settings
305 308 padc=configADC1();
306 309 padd=configADC2();
307 310 }
308 311
309 312
310 313 /*
311 314 * Divide rx frame into the frame components
312 315 */
313 316 void SplitFrame(char *frame){
314 317 header = malloc(4);
315 318 *header = *frame;
316 319 *(header + 1) = *(frame + 1);
317 320 *(header + 2) = *(frame + 2);
318 321 *(header + 3) = '\0';
319 322 TypeOfInstrument = malloc(4);
320 323 *TypeOfInstrument = *(frame + 3);
321 324 *(TypeOfInstrument + 1) = *(frame + 4);
322 325 *(TypeOfInstrument + 2) = *(frame + 5);
323 326 *(TypeOfInstrument + 3) = '\0';
324 327 iDSource = malloc(8);
325 328 *iDSource = *(frame + 6);
326 329 *(iDSource + 1) = *(frame + 7);
327 330 *(iDSource + 2) = *(frame + 8);
328 331 *(iDSource + 3) = *(frame + 9);
329 332 *(iDSource + 4) = *(frame + 10);
330 333 *(iDSource + 5) = *(frame + 11);
331 334 *(iDSource + 6) = *(frame + 12);
332 335 *(iDSource + 7) = '\0';
333 336 iDDestino = malloc(8);
334 337 *iDDestino = *(frame + 13);
335 338 *(iDDestino + 1) = *(frame + 14);
336 339 *(iDDestino + 2) = *(frame + 15);
337 340 *(iDDestino + 3) = *(frame + 16);
338 341 *(iDDestino + 4) = *(frame + 17);
339 342 *(iDDestino + 5) = *(frame + 18);
340 343 *(iDDestino + 6) = *(frame + 19);
341 344 *(iDDestino + 7) = '\0';
342 345 rx_len = malloc(7);
343 346 *rx_len = *(frame + 20);
344 347 *(rx_len + 1) = *(frame + 21);
345 348 *(rx_len + 2) = *(frame + 22);
346 349 *(rx_len + 3) = *(frame + 23);
347 350 *(rx_len + 4) = *(frame + 24);
348 351 *(rx_len + 5) = *(frame + 25);
349 352 *(rx_len + 6) = '\0';
350 353 cmd = malloc(5);
351 354 *cmd = *(frame + 26);
352 355 *(cmd + 1) = *(frame + 27);
353 356 *(cmd + 2) = *(frame + 28);
354 357 *(cmd + 3) = *(frame + 29);
355 358 *(cmd + 4) = '\0';
356 359
357 360 int l = atoi(rx_len);
358 361 rx_data = malloc(l + 1);
359 362 int i;
360 363 for (i = 30; i < 30 + l; i++)
361 364 *(rx_data + (i-30)) = *(frame + i);
362 365 *(rx_data + l) = '\0';
363 366 crc = malloc(2);
364 367 *crc = *(frame + 30 + l);
365 368 *(crc + 1) = '\0';
366 369 }
367 370
368 371 /*
369 372 * Esta funcion procesa el mensaje de peticion y genera respuesta
370 373 */
371 374 void procesa_peticion(char *rx_buffer, char *tx_buffer){
372 375 // int n = 0;
373 376 char filename1[50];
374 377 char filename2[] = "verificacion.txt";
375 378 char *tx_data = NULL;
376 379 char *tx_len = NULL;
377 380 SplitFrame(rx_buffer);
378 381
379 382 if ((cmd == NULL) || (rx_data == NULL)){
380 383 printf("procesarPeticion: formato de mensaje incorrecto");
381 384 //ERROR("procesarPeticion: formato de mensaje incorrecto");
382 385
383 386 }
384 387 else{
385 388 if(strcmp(cmd,"SNDF") == 0){
386 389 escribe_experimento(rx_data,filename1);
387 390 carga_experimento(filename1);
388 391 cambia_apuntamiento("0");
389 392 tx_data = (char*)malloc(3);
390 393 tx_data = "OK";
391 394 }
392 395 else if(strcmp(cmd,"GETF") == 0){
393 396 consigue_nombre_experimento(rx_data,filename1); //get a filename from frame
394 397 tx_data = Lee_experimento(filename1); //return a pointer to the content of the filename
395 398 }
396 399 else if(strcmp(cmd,"CHGB") == 0){
397 400 cambia_apuntamiento(rx_data);
398 401 tx_data = (char*)malloc(3);
399 402 tx_data = "OK";
400 403 }
401 404 else if(strcmp(cmd,"ANST") == 0){
402 405 tx_data = chequeo_sistema(filename2,rx_data);
403 406 printf("%s\n",tx_data);
404 407 }
405 408 else if(strcmp(cmd,"BGPH") == 0){
406 409 tx_data = ABS_monitoreo(1, 0, 50, 10);
407 410 // tx_data = "Not implemented\n";
408 411 printf("%s\n",tx_data);
409 412 }
410 413 else if(strcmp(cmd,"LWPH") == 0){
411 414 tx_data = ABS_monitoreo(0, 0, 50, 10);
412 415 // tx_data = "Not implemented\n";
413 416 printf("%s\n",tx_data);
414 417 }
415 418 else if(strcmp(cmd,"NTST") == 0){
416 419 tx_data = malloc(strlen(parameters.ID) + 1);
417 420 strcpy(tx_data,parameters.ID);
418 421 printf("%s\n",tx_data);
419 422 }
420 423 else if(strcmp(cmd,"UAPP") == 0){
421 424 tx_data = malloc(strlen(parameters.ID) + 1);
422 425 strcpy(tx_data,parameters.ID);
423 426 printf("%s\n",tx_data);
424 427 }
428 else if(strcmp(cmd,"MNTR") == 0){
429 if(strcmp(rx_data,"0") == 0){
430 //Only current beam is requested
431 tx_data = malloc(50);
432 strcpy(tx_data,parameters.ID);
433 strcat(tx_data,"\n-------\n");
434 strcat(tx_data,cbeam);
435 printf("%s\n",tx_data);
436 }
437 else if(strcmp(rx_data,"1") == 0){
438 //Only relay status is requested
439 tx_data = malloc(50);
440 strcpy(tx_data,parameters.ID);
441 strcat(tx_data,"\n-------\n");
442 strcat(tx_data,chequeo_sistema2());
443 printf("%s\n",tx_data);
444 }
445 else if(strcmp(rx_data,"2") == 0){
446 //Only phase is requested
447 tx_data = malloc(100);
448 strcpy(tx_data,parameters.ID);
449 strcat(tx_data,"\n-------\n");
450 strcat(tx_data,ABS_monitoreo(1, 0, 50, 10));
451 printf("%s\n",tx_data);
452 }
453 else if(strcmp(rx_data,"3") == 0){
454 //Current beam and relay status is requested
455 tx_data = malloc(100);
456 strcpy(tx_data,parameters.ID);
457 strcat(tx_data,"\n-------\n");
458 strcat(tx_data,cbeam);
459 strcat(tx_data,chequeo_sistema2());
460 printf("%s\n",tx_data);
461 }
462 else{
463 //Current beam, relays status and phase is requested
464 tx_data = malloc(100);
465 strcpy(tx_data,parameters.ID);
466 strcat(tx_data,"\n-------\n");
467 strcat(tx_data,cbeam);
468 strcat(tx_data,chequeo_sistema2());
469 strcat(tx_data,ABS_monitoreo(1, 0, 50, 10));
470 printf("%s\n",tx_data);
471 }
472 }
425 473 else{
426 474 tx_data = (char*)malloc(6);
427 475 tx_data = "Error";
428 476 printf("procesa_peticion: comando no reconocido");
429 477 //ERROR("procesa_peticion: comando no reconocido");
430 478 }
431 479
432 480 tx_len = malloc(7);
433 481 int number = strlen(tx_data);
434 482 intToStr(number, tx_len );
435 483
436 484 strcpy(tx_buffer,header); //3
437 485 strcat(tx_buffer,TypeOfInstrument); //3
438 486 strcat(tx_buffer,parameters.ID); //7
439 487 strcat(tx_buffer,iDSource); //7
440 488 strcat(tx_buffer,tx_len); //6
441 489 strcat(tx_buffer,cmd); //4
442 490 strcat(tx_buffer,tx_data); //?
443 491 strcat(tx_buffer,crc); //1
444 492 }
445 493
446 494 }
447 495
448 496
449 497 char* Lee_experimento(char filename[]){
450 498 char *buffer = NULL;
451 499 FILE * fd = fopen(filename,"r");
452 500 fseek(fd, 0, SEEK_END);
453 501 size_t sz = ftell(fd);
454 502 fseek(fd, 0, SEEK_SET);
455 503 buffer = malloc(sz);
456 504 fread(buffer,sizeof(char),sz,fd);
457 505 fclose(fd);
458 506
459 507 char *ans = malloc(sz + 1);
460 508 strcpy(ans, buffer);
461 509 ans[sz] = '\0';
462 510 return ans;
463 511 }
464 512 /*
465 513 * Esta función genera el archivo de experimento a partir de la trama TCP recibida
466 514 */
467 515 void escribe_experimento(char *p_data, char filename[]){
468 516 FILE *fd;
469 517 int i = 0;
470 518
471 519 while (*p_data != '\n'){
472 520 filename[i] = *p_data;
473 521 i++;
474 522 p_data++;
475 523 }
476 524 filename[i] = '\0';
477 525 p_data = p_data - i;
478 526 fd = fopen(filename,"w");
479 527 fprintf(fd, p_data);
480 528 fclose(fd);
481 529 }
482 530
483 531 void consigue_nombre_experimento(char *p_data, char filename[]){
484 532
485 533 int i = 0;
486 534
487 535 while (*p_data != '\n'){
488 536 filename[i] = *p_data;
489 537 i++;
490 538 p_data++;
491 539 }
492 540 filename[i] = '\0';
493 541 }
494 542
495 543 /*
496 544 * Esta funcion carga un archivo en un buffer que esta ubicado en memoria, luego
497 545 * este buffer es usado en la funcion "cambia_apuntamiento" para obtener el dato
498 546 * que sera usado en el cambio de apuntamiento.
499 547 */
500 548 int carga_experimento(char *nombre_archivo){
501 549
502 550 FILE *Archivo_Fd;
503 551
504 552 char *cadena = (char *) malloc(25);
505 553
506 554 int longitud_cadena;
507 555 int num_bytes= 0;
508 556 int num_filas= 0;
509 557
510 558 Archivo_Fd = fopen(nombre_archivo,"r"); // Se procede a abrir el archivo, segun la ruta especificada
511 559 if(!Archivo_Fd){
512 560 printf("carga_archivo: No se pudo abrir el archivo!!! --> fopen()\n");
513 561 //ERROR("carga_archivo: No se pudo abrir el archivo!!! --> fopen()\n");
514 562 return -1;
515 563 }else{
516 564
517 565 while(!feof(Archivo_Fd)){ // Se procede a calcular la longitud del archivo para separar memoria
518 566 fgets(cadena,20,Archivo_Fd);
519 567 longitud_cadena= strlen(cadena);
520 568 cadena[longitud_cadena-1] = '\0';
521 569 num_bytes = num_bytes + longitud_cadena;
522 570 num_filas++;
523 571 }
524 572
525 573 rewind(Archivo_Fd); // Se reinicia el puntero del archivo
526 574
527 575 char *buffer_temporal = (char *) malloc(num_bytes+1); // Se separa espacio de memoria segun
528 576 // la longitud del archivo
529 577 fread(buffer_temporal, sizeof(char), num_bytes, Archivo_Fd);
530 578
531 579 char *puntero= strstr(buffer_temporal,".ab1"); // Se procede a eliminar la cabecera del archivo
532 580 puntero= puntero + 12;
533 581
534 582 buff_experimento = (char *) malloc(7*(num_filas-3)); // num_bytes_fila*(num_filas-3);
535 583 strncpy(buff_experimento,puntero,7*(num_filas-3)); // Se carga en memoria la informacion del archivo
536 584
537 585 fclose(Archivo_Fd);
538 586
539 587 return 1;
540 588 }
541 589 }
542 590
543 591 /*
544 592 * Esta funcion recibe un numero en formato char, el dato se transforma a su equivalente en
545 593 * un numero entero, que sera usado para sacar un dato del buffer "buff_experimento", esta
546 594 * dato es el valor que se enviara al sistema de conmutacion RF para el cambio de apunte a
547 595 * traves del puerto GPIO.
548 596 */
549 597 int cambia_apuntamiento(char *puntero_char){
550 598
551 599 /*MSB-UP-LSB MSB-DOWN-LSB*/
552 600 int desplazamiento[6]={30,28,26,24,22,20}; // Defino los dezplazamientos que se aplicara
553 601 // al dato que ingresa para formar el número
554 602 // entero que se le pasara al puerto GPIO
555 603 // Estos números son los pines del puerto GPIO
556 604 // que se estan usando para el control
557 605
558 606 int puntero= atoi(puntero_char); // Se convierte a entero la direccion del puntero
559 607
560 608 int base= 7*puntero; // base= cantidad_bytes del dato x puntero
561 609 // cantidad de bytes es el numero de bytes que
562 printf("%s\n",puntero_char); // contiene cada dato, para este caso es 7
610 // contiene cada dato, para este caso es 7
563 611 // porque es 6 bits de datos + 1 bit del cambio
564 612 // de linea.
565 613 char valor_char;
566 614 unsigned long valor;
567 615 unsigned long acumulado_ceros=0;
568 616 unsigned long acumulado_unos=0;
569 617
570 618 int offset; // Defino offset para el desplazamiento a traves
571 619 for(offset=0;offset<6;offset++){ // de cada dato que se obtiene del "buff_experimento"
572 620
573 621 valor_char= buff_experimento[base+offset]; // Obtengo el dato
574 622
575 623 if (valor_char == '0'){ // Obtengo el número acumulado segun sea un cero o un uno
576 624 valor= 0;
577 625 acumulado_ceros= acumulado_ceros + (1 << desplazamiento[offset]);
578 626 }else{
579 627 valor= 1;
580 628 acumulado_unos= acumulado_unos + (1 << desplazamiento[offset]);
581 629 }
582 630 }
631 //
632
633 char cero = '\0';
634 char enter = '\n';
635 cbeam = malloc(8);
636 sprintf(cbeam,"%c%c%c%c%c%c%c%c",buff_experimento[base],buff_experimento[base+1],buff_experimento[base+2],buff_experimento[base+3],buff_experimento[base+4],buff_experimento[base+5],enter,cero);
637 printf("Beam: %s : %s\n",puntero_char,cbeam);
583 638 pio_out(pioc, maskc_out_beam, acumulado_unos, 1);
584 639 pio_out(pioc, maskc_out_beam, acumulado_ceros, 0);
585 640
586 641 return 1;
587 642
588 643 }
589 644
590 645 /*
591 646 * Esta funcion lee "n" veces el estado del APUNTE actual y reporta
592 647 * una cadena de Verificacion.
593 648 */
594 649 char* chequeo_sistema(char *filename, char *numero_muestras){
595 650
596 651 int i;
597 652 int cnt = 0;
598 653 unsigned int entradac= 0;
599 654
600 655 char page0[250];
601 656
602 657 /*strcpy(page0,"Verificacion\n");
603 658 strcat(page0,parameters.ID);*/
604 659 strcpy(page0,parameters.ID);
605 660 strcat(page0,"\n-------\n");
606 661
607 662 char page1[8];
608 663
609 664 do{
610 665 //Inicializando arreglo
611 666 for(i=0;i<6;i++)
612 667 page1[i]='0';
613 668 page1[6] = '\n';
614 669 page1[7] = '\0';
615 670 //Lectura de puerto
616 671 entradac= pio_in(piob,maskb_in);
617 672 //Dandole formato al dato
618 673 if (!(entradac & bit_up_2))
619 674 page1[0] = '1';
620 675 if (!(entradac & bit_up_1))
621 676 page1[1] = '1';
622 677 if (!(entradac & bit_up_0))
623 678 page1[2] = '1';
624 679 if (!(entradac & bit_dow_2))
625 680 page1[3] = '1';
626 681 if (!(entradac & bit_dow_1))
627 682 page1[4] = '1';
628 683 if (!(entradac & bit_dow_0))
629 684 page1[5] = '1';
630 685
631 686 strcat(page0, page1);
632 687 cnt=cnt+1;
633 688 usleep(1*1000*1000);
634 689
635 690 }while(cnt < atoi(numero_muestras));
636 691
637 692 page0[strlen(page0)] = '\0';
638 693
639 694 char *all_pages = malloc(strlen(page0)+1);
640 695 strcpy(all_pages, page0);
641 696 return all_pages;
642 697 }
643 698
699 char* chequeo_sistema2(){
700
701 int i;
702 unsigned int entradac= 0;
703 char page1[8];
704
705 //Inicializando arreglo
706 for(i=0;i<6;i++)
707 page1[i]='0';
708 page1[6] = '\n';
709 page1[7] = '\0';
710 //Lectura de puerto
711 entradac= pio_in(piob,maskb_in);
712 //Dandole formato al dato
713 if (!(entradac & bit_up_2))
714 page1[0] = '1';
715 if (!(entradac & bit_up_1))
716 page1[1] = '1';
717 if (!(entradac & bit_up_0))
718 page1[2] = '1';
719 if (!(entradac & bit_dow_2))
720 page1[3] = '1';
721 if (!(entradac & bit_dow_1))
722 page1[4] = '1';
723 if (!(entradac & bit_dow_0))
724 page1[5] = '1';
725
726 char *all_pages = malloc(strlen(page1)+1);
727 strcpy(all_pages, page1);
728
729 return all_pages;
730 }
731
732
644 733 int update_app(char *filename, char *ip_number){
645 734
646 735 char cmd[80];
647 736 strcpy(cmd,"tftp -gr");
648 737 strcat(cmd," ");
649 738 strcat(cmd,filename);
650 739 strcat(cmd," ");
651 740 strcat(cmd,ip_number);
652 741
653 742 system(cmd);
654 743
655 744 printf(cmd);
656 745
657 746 return 0;
658 747 }
659 748
660 749 /*
661 750 *
662 751 */
663 752 cmp inicializa_modulo(cmp p, char *filename){
664 753 //FILE *fd = fopen("configuration.txt","r");
665 754 FILE *fd = fopen(filename,"r");
666 755 fgets(p.ID,20,fd);
667 756 p.ID[7]='\0';
668 757 fgets(p.param2,20,fd);
669 758 p.param2[10]='\0';
670 759 fgets(p.param3,20,fd);
671 760 p.param3[10]='\0';
672 761 fgets(p.param4,20,fd);
673 762 p.param4[10]='\0';
674 763 fclose(fd);
675 764 return p;
676 765 }
677 766
678 767 /*
679 768 *
680 769 */
681 770 void intToStr( int number, char* str )
682 771
683 772 {
684 773 int index = 0;
685 774
686 775 while( number > 0 )
687 776 {
688 777 int digit = number%10;
689 778 str[index++] = digit + '0';
690 779 number /= 10;
691 780 }
692 781 str[index] = '\0';
693 782 //Adding zero to the left
694 783 int n= strlen(str);
695 784 if (n == 1) {
696 785 strcat(str,"00000");
697 786 index = index + 5;
698 787 }else if(n == 2){
699 788 strcat(str,"0000");
700 789 index = index + 4;
701 790 }else if(n == 3){
702 791 strcat(str,"000");
703 792 index = index + 3;
704 793 }else if(n == 4){
705 794 strcat(str,"00");
706 795 index = index + 2;
707 796 }else if(n == 5){
708 797 strcat(str,"0");
709 798 index = index + 1;
710 799 }
711 800 //Now reverse the numbers in the string.
712 801 int position;
713 802 for( position = 0; position <= (index-1)/2; ++position )
714 803 {
715 804 char tmp = str[position];
716 805 str[position] = str[(index-1)-position];
717 806 str[(index-1)-position] = tmp;
718 807 }
719 808 }
720 809
721 810
722 811 //*****************************************************************
723 812 //ABS_monitoreo es la funci�n principal del proyecto ABS_Monitoreo.
724 813 //Esta funci�n es la que se debe agregar en otros c�digos.
725 814 //*****************************************************************
726 815 char* ABS_monitoreo(int sel_atenuador, int sel_calibracion, float umbral, int pulsewidth){
727 816
728 817 //local variables
729 818 /* AT91S_PIO *pioc;
730 819 pioc = pio_map(PIOC_BASE);
731 820 unsigned int mask_sel_canal =PC4; //Aqu� se indican los pines que se desean usar como salidas. Las constantes PCx est�n defiidas en el header at91gpio.h
732 821 unsigned int mask_sel_atenuacion =PC5;
733 822 unsigned int mask_sel_calibracion =PC6;*/
734 823
735 824 unsigned long acumulado_ceros=0;
736 825 unsigned long acumulado_unos=0;
737 826 /* AT91S_ADC *padc;
738 827 AT91S_ADC *padd;*/
739 828 FILE *fp;
740 829 long int results1[NSAMPLES], results2[NSAMPLES], results3[NSAMPLES], results4[NSAMPLES];
741 830 unsigned int i=0;
742 831 char fname[FNAMELEN];
743 832 int j=0;
744 833 time_t now;
745 834 FILE *archivo;
746 835 float phase1;
747 836 float phase2;
748 char page0[30];
837 //char page0[30];
749 838 char page1[20];
750 839
751 840 int cnt = 0;
752 841 //system("./map_clock");
753 842 /*
754 843 if (configCLK() == 1)
755 844 printf("clock ADC enable.\n");
756 845 */
757 846 /*
758 847 //configurar tres pines como salida usando als m�scaras mask_sel_canal, mask_sel_atenuacion y mask_sel_calibracion. En este caso corresponden a los pines pc4, pc5 y pc6.
759 848 pio_enable(pioc, mask_sel_canal);
760 849 pio_enable(pioc, mask_sel_atenuacion);
761 850 pio_enable(pioc, mask_sel_calibracion);
762 851 pio_output_enable(pioc, mask_sel_canal); //configurar pc4 como salida
763 852 pio_output_enable(pioc, mask_sel_atenuacion); //configurar pc5 como salida
764 853 pio_output_enable(pioc, mask_sel_calibracion); //configurar pc6 como salida
765 854 */
766 855
767 856 //Se modifican las salidas correspondientes a la selecci�n del atenuador y calibraci�n, de acuerdo a los par�metros ingresados en la funci�n ABS_monitoreo.
768 857 /*if ( sel_atenuador == 1)
769 858 pio_out(pioc, mask_sel_atenuacion, sel_atenuador,1);
770 859 else
771 860 pio_out(pioc, mask_sel_atenuacion, sel_atenuador,0);
772 861 if ( sel_calibracion == 1)
773 862 pio_out(pioc, mask_sel_calibracion, sel_calibracion,1);
774 863 else
775 864 pio_out(pioc, mask_sel_calibracion, sel_calibracion,0);*/
776 865
777 866 if ( sel_atenuador == 1)
778 867 acumulado_unos = acumulado_unos + (1 << 5);
779 868 else
780 869 acumulado_ceros = acumulado_ceros + (1 << 5);
781 870 if ( sel_calibracion == 1)
782 871 acumulado_unos = acumulado_unos + (1 << 6);
783 872 else
784 873 acumulado_ceros = acumulado_ceros + (1 << 6);
785 874
786 875
787 876 strcpy (fname, "/mnt/sd/absmonitoreo.txt"); //Direcci�n y nombre del archivo donde se desea guardar los datos.
788 877
789 878 if (fExists(fname)==0){ //si el archivo no existe, crea uno y le asigna el titulo
790 879 archivo = fopen(fname,"a+");
791 880 fprintf(archivo,"%s"," Registro de datos del ABS Control \n");
792 881 fprintf(archivo,"%s"," Fecha y hora Fase UP Fase DOWN\n");
793 882 fclose(archivo);
794 883 }
795 884
796 885 /*
797 886 //configure ADC Settings
798 887 padc=configADC1();
799 888 padd=configADC2();
800 889 */
801 890 //while (1){
802 891
803 892 ENABLE_CHANNEL(padc, ADC_CH0+ADC_CH1);
804 893 printf("\nAdquiriendo datos...\n"); //Indica en el terminal que se est�n adquiriendo datos (muestreando la se�al).
805 894
806 895
807 896 now = time(0); //Get current Time for File Name
808 897
809 898 //Se pone la salida de selecci�n de canal para seleccionar el canal 1 del detector de fase
810 899 acumulado_ceros = acumulado_ceros + (1 << 4);
811 900 pio_out(pioc, maskc_out_cntl, acumulado_ceros, 0);
812 901 pio_out(pioc, maskc_out_cntl, acumulado_unos, 1);
813 902 sleep(1);
814 903
815 904 //Se toman muestras para el canal 1 del detector de fase
816 905 /*while(1){
817 906 for(i=0; i < NSAMPLES; i++){
818 907
819 908 ADC_INIT(padc);
820 909 results1[i] = GET_ADC0(padc);
821 910 results2[i] = GET_ADC1(padd);
822 911 }
823 912
824 913 if (checkTx(results1, results2, umbral, pulsewidth)==1){ //Se verifica que las muestras tomadas del canal 1 del datector de fase //correspondan a un pulso.
825 914 break;
826 915 }
827 916
828 917 }*/
829 918
830 919 do{
831 920 for(i=0; i < NSAMPLES; i++){
832 921
833 922 ADC_INIT(padc);
834 923 results1[i] = GET_ADC0(padc);
835 924 results2[i] = GET_ADC1(padd);
836 925 }
837 926
838 927 if (checkTx(results1, results2, umbral, pulsewidth)==1){ //Se verifica que las muestras tomadas del canal 1 del datector de fase //correspondan a un pulso.
839 928 break;
840 929 }
841 930 cnt += 1;
842 931 }while (cnt < NLOOPS);
843 932
844 933 //Se pone la salida de selecci�n de canal para seleccionar el canal 2 del detector de fase
845 934 acumulado_ceros = acumulado_ceros - (1 << 4);
846 935 acumulado_unos = acumulado_unos + (1 << 4);
847 936 pio_out(pioc, maskc_out_cntl, acumulado_ceros, 0);
848 937 pio_out(pioc, maskc_out_cntl, acumulado_unos, 1);
849 938 sleep(1);
850 939
851 940
852 941 //Setoman muestras para el canal 2 del detector de fase
853 942 /* while(1){
854 943 for(i=0; i < NSAMPLES; i++){
855 944
856 945 ADC_INIT(padc);
857 946 results3[i] = GET_ADC0(padc);
858 947 results4[i] = GET_ADC1(padd);
859 948 }
860 949
861 950 if (checkTx(results3, results4, umbral, pulsewidth)==1){ //Se verifica que las muestras tomadas del canal 2 del detector de fase //correspondan a un pulso.
862 951 break;
863 952 }
864 953 }*/
865 954 cnt = 0;
866 955 do{
867 956 for(i=0; i < NSAMPLES; i++){
868 957
869 958 ADC_INIT(padc);
870 959 results3[i] = GET_ADC0(padc);
871 960 results4[i] = GET_ADC1(padd);
872 961 }
873 962
874 963 if (checkTx(results3, results4, umbral, pulsewidth)==1){ //Se verifica que las muestras tomadas del canal 2 del detector de fase //correspondan a un pulso.
875 964 break;
876 965 }
877 966 cnt += 1;
878 967 }while(cnt < NLOOPS);
879 968
880 969 //Una vez que se ha encontrado un pulso en cada canal, se calcula la fase de ambos.
881 970
882 971 phase1 = getPhase(results1, results2); //Calcular la fase del canal 1 del detector de fase.
883 972 phase2 = getPhase(results3, results4); //Calcular la fase del canal 2 del detector de fase.
884 973 //create Output File
885 974
886 975 strcpy (fname, "/mnt/sd/absmonitoreo.txt");
887 976 printf("\nTerminada la prueba # %d \n", j++);
888 977 fp=create_Output(fname, now); //Coloca la fecha y la hora en el archivo de texto
889 978 printf("mediana ch1 = %1.2f\n", phase1); //muestra resultado en terminal
890 979 printf("mediana ch2 = %1.2f\n", phase2); //muestra resultado en terminal
891 980 writeOutput(phase1, fp); //graba el resultado en el archivo de texto
892 981 writeOutput(phase2, fp); //graba el resultado en el archivo de texto
893 982 fprintf(fp, "\n"); //Pasa a la siguiente l�nea del archivo de texto
894 983 fclose(fp);
895 984 printf("Resultado guardado en %s \n", fname);
896 985
897 986 sleep(1);
898 987
899 strcpy(page0,parameters.ID);
900 strcat(page0,"\n-------\n");
988 // strcpy(page0,parameters.ID);
989 // strcat(page0,"\n-------\n");
901 990
902 991 //sprintf(page1,"UP:%1.2f DW:%1.2f\n",phase1, phase2);
903 sprintf(page1,"%1.2f %1.2f\n",phase1, phase2);
904 strcat(page0,page1);
905 char *all_pages = malloc(strlen(page0)+1);
906 strcpy(all_pages, page0);
992 sprintf(page1,"%1.2f\n%1.2f\n",phase1, phase2);
993 page1[strlen(page1)]='\0';
994 // strcat(page0,page1);
995 // char *all_pages = malloc(strlen(page0)+1);
996 char *all_pages = malloc(strlen(page1)+1);
997 strcpy(all_pages, page1);
907 998 return all_pages;
908 999
909 1000 // }
910 1001 // return 0;
911 1002 }
912 1003 /*=============================================================================
913 1004 Function definitions
914 1005 =============================================================================*/
915 1006
916 1007 // Configures ADC registers in order to get a sample every 10us
917 1008 AT91S_ADC * configADC1(void){
918 1009 //Variables a usar:
919 1010 /*
920 1011 unsigned int maskc_adc =PC0; //Usamos ADC0 y ADC1
921 1012
922 1013 //configuro pin:
923 1014 AT91S_PIO *pioc;
924 1015 pioc = pio_map(PIOC_BASE);
925 1016 pin_adc_enable(pioc,maskc_adc); //Habilitamos PC0 para usar con ADC0 y 1
926 1017 pio_disable_irq(pioc, maskc_adc);
927 1018 pio_disable_multiple_driver(pioc, maskc_adc);
928 1019 pio_disable_pull_ups(pioc, maskc_adc);
929 1020 pio_input_enable(pioc, maskc_adc);
930 1021 */
931 1022
932 1023 //Configuro el ADC:
933 1024 //AT91S_ADC *padc;
934 1025
935 1026 padc = adc_map1(ADC_BASE);
936 1027
937 1028 //clock ADC = 1MHz
938 1029 //time startup = 8us
939 1030 //time sample and hold = 2us
940 1031 // hold
941 1032 // ___________
942 1033 // start ___________| |___________
943 1034 //
944 1035 // | --1.2us-- | --0.15us-- |
945 1036 //ADC_RESET(padc);
946 1037 CONFIG_ADC(padc,ADC_TRGEN_DIS | ADC_RES_10BIT | ADC_SLEEP_NORMAL_MODE | ADC_PRESCAL | ADC_STARTUP | ADC_SHTIM);
947 1038 ENABLE_CHANNEL(padc,ADC_CH0); //habilito canal 0
948 1039 return padc;
949 1040 }
950 1041
951 1042 AT91S_ADC * configADC2(void){
952 1043 //Variables a usar:
953 1044 /*
954 1045 unsigned int maskc_adc =PC1; //Usamos ADC0 y ADC1
955 1046
956 1047 //configuro pin:
957 1048 AT91S_PIO *piod;
958 1049 piod = pio_map(PIOC_BASE);
959 1050 pin_adc_enable(piod,maskc_adc); //Habilitamos PC1 para usar con ADC0 y 1
960 1051 pio_disable_irq(piod, maskc_adc);
961 1052 pio_disable_multiple_driver(piod, maskc_adc);
962 1053 pio_disable_pull_ups(piod, maskc_adc);
963 1054 pio_input_enable(piod, maskc_adc);
964 1055 */
965 1056 //Configuro el ADC:
966 1057 //AT91S_ADC *padd;
967 1058
968 1059 padd = adc_map1(ADC_BASE);
969 1060
970 1061 //clock ADC = 1MHz
971 1062 //time startup = 8us
972 1063 //time sample and hold = 2us
973 1064 // hold
974 1065 // ___________
975 1066 // start ___________| |___________
976 1067 //
977 1068 // | --1.2us-- | --0.15us-- |
978 1069 //ADC_RESET(padc);
979 1070 CONFIG_ADC(padd,ADC_TRGEN_DIS | ADC_RES_10BIT | ADC_SLEEP_NORMAL_MODE | ADC_PRESCAL | ADC_STARTUP | ADC_SHTIM);
980 1071 ENABLE_CHANNEL(padd,ADC_CH1); //habilito canal 1
981 1072 return padd;
982 1073 }
983 1074
984 1075
985 1076 //++++++++++++++++++++
986 1077
987 1078 //creats the output file with a timestamp in the name
988 1079 FILE * create_Output(char *fname, time_t rawtime){
989 1080 FILE *file;
990 1081 char timestamp[80];//, counter[5]="dcv";
991 1082 //char str[4];
992 1083 struct tm * timeinfo;
993 1084
994 1085 //format time
995 1086 timeinfo = localtime ( &rawtime );
996 1087 strftime (timestamp,sizeof(timestamp),"%a %y-%m-%d %H:%M:%S %Z",timeinfo);
997 1088
998 1089
999 1090 //Creates the file name out of the #define parameters
1000 1091
1001 1092 strcpy (fname, "/mnt/sd/absmonitoreo.txt");
1002 1093 file = fopen(fname,"a+");
1003 1094 fprintf(file,"%s", timestamp);
1004 1095 //printf("\nTerminada la prueba # %d. Guardando resultado en %s\n",r, fname);
1005 1096 //printf("\nTerminada la prueba # %d/%d. Writing data to the file %s\n",r+1 , REP, fname);
1006 1097 //printf("\nAAAAAAAAAA %d...%s\n", counter[1], fname);
1007 1098 // return file pointer
1008 1099 return file;
1009 1100 }
1010 1101
1011 1102 //++++++++++++++++++++
1012 1103
1013 1104 //tests if a file already exists. returns 1 if it exists and 0 if it doesn't
1014 1105
1015 1106
1016 1107
1017 1108 //Funci�n checkTx verifica que la se�al muestreada corresponda a un pulso.
1018 1109 //results1 y results2 son los arreglos que contienen los datos muestreados por ambos canales del ADC del embebido.
1019 1110 //umbral indica qu� valor debe superar una muestra para considerarla un posible pulso o pico.
1020 1111 //pulsewidth indica cu�ntas muestras consecutivas deben superar el umbral para que se considere que se ha detectado un pulso.
1021 1112 int checkTx(long int results1[],long int results2[], float umbral, int pulsewidth){
1022 1113
1023 1114 int i, cont;
1024 1115 float z[NSAMPLES], sum, avg;
1025 1116 int isSignal, pulse;
1026 1117
1027 1118 for(i=0;i<NSAMPLES;i++){
1028 1119
1029 1120 z[i] =sqrt(1.0*results1[i]*results1[i]+1.0*results2[i]*results2[i]);
1030 1121 }
1031 1122
1032 1123 pulse = 0;
1033 1124 isSignal = 0;
1034 1125 cont =0;
1035 1126
1036 1127 sum = 0;
1037 1128 for(i=0;i<NSAMPLES;i++){
1038 1129
1039 1130 sum += z[i];
1040 1131 avg = sum/(i+1);
1041 1132 if ((z[i] - avg) > umbral){
1042 1133 if (isSignal == 1){
1043 1134 cont += 1;
1044 1135 }
1045 1136 if (cont == pulsewidth){
1046 1137 pulse = 1;
1047 1138 break;
1048 1139 }
1049 1140 isSignal = 1;
1050 1141 continue;
1051 1142 isSignal = 0;
1052 1143 cont = 0;
1053 1144 }
1054 1145 }
1055 1146
1056 1147 return pulse; //devuelve un entero: 1 si se ha detectado pulso, de lo contrario, 0.
1057 1148 }
1058 1149
1059 1150
1060 1151 int fExists(char * fname){
1061 1152 FILE * file;
1062 1153
1063 1154 file = fopen (fname, "r");
1064 1155 if (file == NULL)
1065 1156 {
1066 1157 return 0;
1067 1158 }
1068 1159 fclose(file);
1069 1160 return 1;
1070 1161 }
1071 1162
1072 1163
1073 1164 //Funci�n que calcula la mediana de un conjunto de muestras
1074 1165 double mediana(long int *results,unsigned int cuenta){
1075 1166 unsigned int i=0,j=0,aux=0;
1076 1167
1077 1168 double median=0;
1078 1169 /*Calculo mediana */
1079 1170
1080 1171 for(i=0;i<cuenta-1;i++){
1081 1172 for (j=i+1;j<cuenta;j++){
1082 1173 if(results[i]>results[j] ){
1083 1174
1084 1175 aux=results[i];
1085 1176 results[i]=results[j];
1086 1177 results[j]=aux;
1087 1178
1088 1179 }
1089 1180 }
1090 1181
1091 1182 }
1092 1183 median=results[cuenta/2];
1093 1184 return median;
1094 1185 }
1095 1186
1096 1187
1097 1188
1098 1189 //Funci�n que halla la fase de la se�al.
1099 1190 //Tiene como entradas las muestras correspondientes a la parte real e imaginaria de la se�al.
1100 1191 float getPhase(long int results1[],long int results2[]){
1101 1192
1102 1193 unsigned int count=0, i=0,umbral=1000;
1103 1194 //long int results1[];
1104 1195 //long int results2[];
1105 1196 long int power[NSAMPLES];
1106 1197 long int sumI=0,sumQ=0,I[NSAMPLES], Q[NSAMPLES],II[NSAMPLES], QQ[NSAMPLES];
1107 1198 double median1=0,median2=0;
1108 1199 long int promedioI=0,promedioQ=0;/*Calculo mediana 1*/
1109 1200 float resultado=0;
1110 1201
1111 1202 for(i=0;i<NSAMPLES;i++){
1112 1203
1113 1204 I[i] =results1[i];
1114 1205 Q[i] =results2[i];
1115 1206 }
1116 1207
1117 1208 /*Calculo mediana 1*/
1118 1209 median1=mediana(I,NSAMPLES);
1119 1210
1120 1211 /*Calculo mediana 2*/
1121 1212 median2=mediana(Q,NSAMPLES);
1122 1213
1123 1214
1124 1215
1125 1216
1126 1217
1127 1218
1128 1219 for(i=0;i<NSAMPLES;i++){
1129 1220
1130 1221 I[i] =results1[i];
1131 1222 Q[i] =results2[i];
1132 1223
1133 1224 }
1134 1225
1135 1226
1136 1227
1137 1228 for(i = 0; i < NSAMPLES ; i++){
1138 1229
1139 1230 I[i]=(I[i]-median1);
1140 1231 Q[i]=(Q[i]-median2);
1141 1232
1142 1233 }
1143 1234
1144 1235 for(i = 0; i < NSAMPLES ; i++){
1145 1236
1146 1237 power[i]=I[i]*I[i]+Q[i]*Q[i];
1147 1238
1148 1239 if(power[i] > umbral)
1149 1240 {
1150 1241
1151 1242 II[count]=I[i];
1152 1243 QQ[count]=Q[i];
1153 1244 count=count+1;
1154 1245
1155 1246 }
1156 1247
1157 1248 }
1158 1249
1159 1250 for(i = 0; i < count ; i++){
1160 1251
1161 1252 sumI=sumI+II[i];
1162 1253 sumQ=sumQ+QQ[i];
1163 1254
1164 1255 }
1165 1256
1166 1257 promedioI=sumI;
1167 1258 promedioQ=sumQ;
1168 1259
1169 1260 resultado = atan2(1.0*promedioI,1.0*promedioQ)*180/3.1416+62-44;
1170 1261
1171 1262
1172 1263 return resultado;
1173 1264
1174 1265 }
1175 1266
1176 1267
1177 1268
1178 1269 //Funci�n que muestra la fase detectada en el terminal y tambi�n la graba en el archivo de texto.
1179 1270 void writeOutput(float resultado, FILE * output){
1180 1271
1181 1272
1182 1273 //
1183 1274
1184 1275 fprintf(output," %1.2f ",resultado); //graba resultado en archivo .txt
1185 1276 //
1186 1277
1187 1278 }
1188 1279
1189 1280 int configCLK(){
1190 1281 //configuro pin:
1191 1282 AT91S_PMC *sys_clock;
1192 1283 sys_clock = clock_map(CLOCK_BASE);
1193 1284 enable_clock_adc(sys_clock);
1194 1285 //printf("clock ADC enable.\n");
1195 1286 return 1;
1196 1287 }
General Comments 0
You need to be logged in to leave comments. Login now