• Sábado 21 de Septiembre de 2024, 22:06

Autor Tema:  Transmision Por El Pto Serial En C  (Leído 1520 veces)

leoworks

  • Nuevo Miembro
  • *
  • Mensajes: 7
    • Ver Perfil
Transmision Por El Pto Serial En C
« en: Sábado 19 de Junio de 2004, 03:10 »
0
Hola, necesito transmitir datos por el puerto serial en C, porfa necesito el codigo ;)

Eternal Idol

  • Moderador
  • ******
  • Mensajes: 4696
  • Nacionalidad: ar
    • Ver Perfil
Re: Transmision Por El Pto Serial En C
« Respuesta #1 en: Sábado 19 de Junio de 2004, 11:48 »
0
Para que Sistema Operativo?

Nacional y Popular En mi país la bandera de Eva es inmortal.


Queremos una Argentina socialmente justa, económicamente libre y  políticamente soberana.
¡Perón cumple, Evita dignifica!


La mano invisible del mercado me robo la billetera.

-SB-

  • Miembro activo
  • **
  • Mensajes: 60
    • Ver Perfil
Re: Transmision Por El Pto Serial En C
« Respuesta #2 en: Sábado 19 de Junio de 2004, 12:37 »
0
En otro post(no se en cual, seguramente en el foro de linux) se publico este codigo, (lo tengo guardado desde que lo lei jeje). Es un codigo que envia datos bit a bit por el puerto serie, pero para Unix.

Código: Text
  1.  
  2. /*
  3. * AUTHOR: Sven Goldt (goldt@math.tu-berlin.de)
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License
  7. * as published by the Free Software Foundation; either version 2
  8. * of the License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. */
  16. /*
  17. This is like all programs in the Linux Programmer's Guide meant
  18. as a simple practical demonstration.
  19. It can be used as a base for a real terminal program.
  20. */
  21.  
  22. #include
  23. #include
  24. #include
  25. #include
  26. #include
  27.  
  28. #define BAUDRATE B38400
  29. #define MODEMDEVICE "/dev/ttyS1"
  30. #define ENDMINITERM 2 /* ctrl-b to quit miniterm */
  31.  
  32. #define _POSIX_SOURCE 1 /* POSIX compliant source */
  33.  
  34. #define FALSE 0
  35. #define TRUE 1
  36.  
  37. volatile int STOP=FALSE;
  38.  
  39. void child_handler(int s)
  40. {
  41. STOP=TRUE;
  42. }
  43.  
  44. main()
  45. {
  46. int fd,c;
  47. struct termios oldtio,newtio,oldstdtio,newstdtio;
  48. struct sigaction sa;
  49.  
  50. /*
  51. Open modem device for reading and writing and not as controlling tty
  52. because we don't want to get killed if linenoise sends CTRL-C.
  53. */
  54. fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY);
  55. if (fd <0) {perror(MODEMDEVICE); exit(-1); }
  56.  
  57. tcgetattr(fd,&oldtio); /* save current modem settings */
  58.  
  59. /*
  60. Set bps rate and hardware flow control and 8n1 (8bit,no parity,1 stopbit).
  61. Also don't hangup automatically and ignore modem status.
  62. Finally enable receiving characters.
  63. */
  64. newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
  65.  
  66. /*
  67. Ignore bytes with parity errors and make terminal raw and dumb.
  68. */
  69. newtio.c_iflag = IGNPAR;
  70.  
  71. /*
  72. Raw output.
  73. */
  74. newtio.c_oflag = 0;
  75.  
  76. /*
  77. Don't echo characters because if you connect to a host it or your
  78. modem will echo characters for you. Don't generate signals.
  79. */
  80. newtio.c_lflag = 0;
  81.  
  82. /* blocking read until 1 char arrives */
  83. newtio.c_cc[VMIN]=1;
  84. newtio.c_cc[VTIME]=0;
  85.  
  86. /* now clean the modem line and activate the settings for modem */
  87. tcflush(fd, TCIFLUSH);
  88. tcsetattr(fd,TCSANOW,&newtio);
  89.  
  90. /*
  91. Strange, but if you uncomment this command miniterm will not work
  92. even if you stop canonical mode for stdout. This is a linux bug.
  93. */
  94. tcsetattr(1,TCSANOW,&newtio); /* stdout settings like modem settings */
  95.  
  96. /* next stop echo and buffering for stdin */
  97. tcgetattr(0,&oldstdtio);
  98. tcgetattr(0,&newstdtio); /* get working stdtio */
  99. newstdtio.c_lflag &= ~(ICANON | ECHO);
  100. tcsetattr(0,TCSANOW,&newstdtio);
  101.  
  102. /* terminal settings done, now handle in/ouput */
  103. switch (fork())
  104. {
  105. case 0: /* child */
  106. /* user input */
  107. close(1); /* stdout not needed */
  108. for (c=getchar(); c!= ENDMINITERM; c=getchar()) write(fd,&c,1);
  109. tcsetattr(fd,TCSANOW,&oldtio); /* restore old modem setings */
  110. tcsetattr(0,TCSANOW,&oldstdtio); /* restore old tty setings */
  111. close(fd);
  112. exit(0); /* will send a SIGCHLD to the parent */
  113. break;
  114. case -1:
  115. perror("fork");
  116. tcsetattr(fd,TCSANOW,&oldtio);
  117. close(fd);
  118. exit(-1);
  119. default: /* parent */
  120. close(0); /* stdin not needed */
  121. sa.sa_handler = child_handler;
  122. sa.sa_flags = 0;
  123. sigaction(SIGCHLD,&sa,NULL); /* handle dying child */
  124. while (STOP==FALSE) /* modem input handler */
  125. {
  126. read(fd,&c,1); /* modem */
  127. write(1,&c,1); /* stdout */
  128. }
  129. wait(NULL); /* wait for child to die or it will become a zombie */
  130. break;
  131. }
  132. }
  133.  
  134.  

Espero que te sirva, un saludo!

Ruben3d

  • Miembro HIPER activo
  • ****
  • Mensajes: 710
  • Nacionalidad: es
    • Ver Perfil
    • Web personal
Re: Transmision Por El Pto Serial En C
« Respuesta #3 en: Sábado 19 de Junio de 2004, 13:45 »
0
Hola.

Hace tiempo remodelé el código que ha indicado -SB- para que estuviera un poco más claro. Aqui está:

Código: Text
  1. /*
  2.  *  AUTHOR: Sven Goldt (goldt@math.tu-berlin.de)
  3.  *
  4.  *  This program is free software; you can redistribute it and/or
  5.  *  modify it under the terms of the GNU General Public License
  6.  *  as published by the Free Software Foundation; either version 2
  7.  *  of the License, or (at your option) any later version.
  8.  *
  9.  *  This program is distributed in the hope that it will be useful,
  10.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.  *  GNU General Public License for more details.
  13.  *
  14. */
  15.  
  16. //
  17. // miniterm.c
  18. //
  19.  
  20. #include <termios.h>
  21. #include <stdio.h>
  22. #include <unistd.h>
  23. #include <fcntl.h>
  24. #include <sys/signal.h>
  25.  
  26. #define TXRXDEVICE "/dev/ttyS0"    // COM1
  27. //#define TXRXDEVICE "/dev/ttyS1"    // COM2
  28.  
  29. #define BAUDRATE B38400      // Las ctes. estan definidas en asm/termbits.h
  30. #define ENDMINITERM 2      // Ctrl+B para salir de miniterm
  31.  
  32. #define _POSIX_SOURCE 1     // Fuente compatible POSIX
  33.  
  34. #define FALSE 0
  35. #define TRUE 1
  36.  
  37. #define STDIN 0
  38. #define STDOUT 1
  39.  
  40. volatile int STOP = FALSE;    // flag de salida
  41.  
  42. // Esta funcion recibe el numero de senyal que emita el proceso hijo. Como la unica que va a emitir
  43. // es la de finalizar, siempre va a poner STOP a TRUE
  44. void child_handler(int s)
  45. {
  46.   STOP = TRUE;
  47. }
  48.  
  49. // Punto de entrada del programa
  50. int main(int argn, char *argv[])
  51. {
  52.   int   fd,  // Descriptor del dispositivo de E/S
  53.     c;  // Lectura de caracteres del teclado
  54.   struct termios oldDevice, newDevice, oldStdin, newStdin, oldStdout;
  55.  
  56.   struct sigaction sa;  // Para manipular el proceso hijo
  57.  
  58.   /*
  59.   =================================================
  60.   APERTURA DEL DISPOSITIVO DE TRANSMISION/RECEPCION
  61.   =================================================
  62.   */
  63.   // Abre el dispositivo de transmision para lectura y escritura y no como controlador tty, ya
  64.   // que no queremos cortar si el ruido de la linea envia un Ctrl+C
  65.   fd = open(TXRXDEVICE, O_RDWR | O_NOCTTY);
  66.   if (fd < 0)
  67.   {
  68.     perror(TXRXDEVICE);
  69.     exit(-1);
  70.   }
  71.  
  72.   /*
  73.   ============================================
  74.   GUARDAR TODAS LAS CONFIGURACIONES ANTERIORES
  75.   ============================================
  76.   */
  77.   // Lo primero es guardar todas las configuraciones anteriores de los dispositivos
  78.   tcgetattr(fd, &oldDevice);  // Guarda la configuracion actual del dispositivo de transmision
  79.   tcgetattr(STDIN, &oldStdin);  // Guarda la cfg de STDIN
  80.   tcgetattr(STDOUT, &oldStdout);  // Guarda la cfg de STDOUT
  81.  
  82.   /*
  83.   ===============================
  84.   CONFIGURA EL DISPOSITIVO DE E/S
  85.   ===============================
  86.   */
  87.   // Configura el ratio de bps, el flujo de control por hardware y 8n1 (8 bits, sin paridad,
  88.   // 1 sopbit). Tambien no colgar automaticamente e ignorar el estado del modem. Finalmente
  89.   // habilita la recepcion de caracteres.
  90.   newDevice.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
  91.  
  92.   // Ignora bits con errores de paridad
  93.   newDevice.c_iflag = IGNPAR;
  94.  
  95.   // Salida
  96.   newDevice.c_oflag = 0;
  97.   //                                                               ,
  98.   // No hacer eco con caracteres, ya que si te conectas a un host, el o el modem lo hara por ti.
  99.   // No generar senales.
  100.   newDevice.c_lflag = 0;
  101.  
  102.   // Bloquea la lectura hasta que un caracter llega
  103.   newDevice.c_cc[VMIN]=1;
  104.   newDevice.c_cc[VTIME]=0;
  105.  
  106.   // Ahora limpia la linea del modem y activa su configuracion
  107.   tcflush(fd, TCIFLUSH);
  108.   tcsetattr(fd, TCSANOW, &newDevice);  // Aplica la nueva cfg
  109.  
  110.   /*
  111.   =======================
  112.   CONFIGURACION DE STDOUT
  113.   =======================
  114.   */
  115.   tcsetattr(STDOUT, TCSANOW, &newDevice); // Configura stdout como si fuera el dispositivo de E/S
  116.  
  117.   /*
  118.   ======================
  119.   CONFIGURACION DE STDIN
  120.   ======================
  121.   */
  122.   tcgetattr(STDIN, &newStdin);     // obtengo la cfg de stdin
  123.   newStdin.c_lflag &= ~(ICANON | ECHO);  // la modifico para detener el eco por pantalla y el buffering
  124.   tcsetattr(STDIN, TCSANOW, &newStdin);  // y la aplico
  125.  
  126.   /*
  127.   =========================
  128.   MANEJAR LA ENTRADA/SALIDA
  129.   =========================
  130.   */
  131.   switch (fork())  // Crea un proceso hijo que es instancia de este. Retorna 0 si estamos en el hijo, -1 si hubo error o el PID del hijo si estamos en el padre
  132.   {
  133.   case 0:  // ==== Si ahora estamos en el hijo ====
  134.     //close(STDOUT);
  135.     for (c=getchar(); c!=ENDMINITERM&#59; c=getchar())  // Lee los caracteres desde el usauario hasta que se introduzca Ctrl+B (ENDMINITERM)
  136.       write(fd,&c,1);        // Los va escribiendo en el dispositivo de salida
  137.     tcsetattr(fd, TCSANOW, &oldDevice);  // Restaura la antigua configuracion del dispositivo de E/S
  138.     tcsetattr(STDIN, TCSANOW, &oldStdin);  // Restaura la antigua cfg de Stdin
  139.     close(fd);        // Cierra el dispositivo E/S
  140.     exit(0);        // envia SIGCHLD al padre
  141.     break;
  142.  
  143.   case -1:// ==== Si hubo un error y no fue creada la instancia ====
  144.     perror("fork");
  145.     tcsetattr(fd, TCSANOW, &oldDevice);  // Restaura la cfg del dispositivo
  146.     close(fd);        // Lo cierra
  147.     exit(-1);
  148.  
  149.   default:// ==== Si ahora estamos en el padre ====
  150.     //close(STDIN);
  151.     sa.sa_handler = child_handler;  // Puntero a la funcion de manipulacion de senyales del hijo
  152.     sa.sa_flags = 0;    // No son necesarias ninguna flag en especial
  153.     sigaction(SIGCHLD, &sa, NULL);  // Aplica la cfg de la manipulacion del proceso hijo
  154.     while (STOP==FALSE)    // Mientras que la funcion child_handler no indique que el hijo ha finalizado
  155.     {
  156.       read(fd, &c, 1);  // Lee desde el dispositivo
  157.       write(STDOUT, &c, 1);  // Lo escribe por pantalla
  158.     }
  159.     tcsetattr(STDOUT, TCSANOW, &oldStdout);  // Restauro la cfg de STDOUT
  160.     wait(NULL);  // Espera a que el proceso hijo sea matado o quede zombi
  161.     break;
  162.   }
  163.   return 0;
  164. }
  165.  

Se ve mejor con tamaño de tabulación 8.

Un saludo.

Ruben3d