Autor Tópico: Porta serie  (Lida 2264 vezes)

Offline hulkPT

  • Usuário Ubuntu
  • *
  • Mensagens: 5
    • Ver perfil
Porta serie
« Online: 10 de Dezembro de 2009, 12:28 »
Viva, eu a fazer um programa para comunicar pela porta serie uso as seguintes configuraçoes

Código: [Selecionar]
void configurePort(int fd)

{

struct termios options;

fcntl(fd, F_SETFL, FNDELAY);                  /* Configure port reading */
                                    /* Get the current options for the port */
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);                 /* Set the baud rates to 9600 */
cfsetospeed(&options, B9600);
                                  /* Enable the receiver and set local mode */
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB; /* Mask the character size to 8 bits, no parity */
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |=  CS8;                              /* Select 8 data bits */
options.c_cflag &= ~CRTSCTS;               /* Disable hardware flow control */
                                /* Enable data to be processed as raw input */
options.c_lflag &= ~(ICANON | ECHO | ISIG);
                                       /* Set the new options for the port */
tcsetattr(fd, TCSANOW, &options);


}

a aplicação em si consiste só num sistema de comunicação entre dois Computadores para testar se a minha configuração estava correcta o meu professor deu me um codigo onde eu so tinha de por o codigo da configuração

Código: [Selecionar]
/*-------------------------------------------------------------

Embedded Systems Research Group

Industrial Electronics Department

University of Minho

-------------------------------------------------------------*/



#include <stdio.h>

#include <fcntl.h>

#include <termios.h>

#include <string.h>

#include <errno.h>

#include <stdlib.h>


#define  testError() \

{ \

if (j < 0) \

{ \

printf ("Receiving: read() error - %s\n", strerror(errno)); \

return (1); \

} \

else if (j == 0) \

{ \

printf ("Receiving: timeout...\n"); \

return (1); \

} \

}





void configurePort(int fd)

{

/*
   INSERT YOUR CODE HERE
*/
struct termios options;

fcntl(fd, F_SETFL, FNDELAY);                  /* Configure port reading */
                                    /* Get the current options for the port */
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);                 /* Set the baud rates to 9600 */
cfsetospeed(&options, B9600);
                                  /* Enable the receiver and set local mode */
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB; /* Mask the character size to 8 bits, no parity */
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |=  CS8;                              /* Select 8 data bits */
options.c_cflag &= ~CRTSCTS;               /* Disable hardware flow control */
                                /* Enable data to be processed as raw input */
options.c_lflag &= ~(ICANON | ECHO | ISIG);
                                       /* Set the new options for the port */
tcsetattr(fd, TCSANOW, &options);

}


int main()

{

int  fd;

int i,j,payload;

char *sendFrame, *recvFrame;



fd = open("/dev/ttyUSB0", O_RDWR|O_NOCTTY|O_NDELAY); //abre a porta com 01  3 flags com a definição de cada uma em baixo
     
/* ********************************************************************************************
O_RDWR means that we open the port for reading and writing
O_NOCTTY specifies that the program won't be the controlling entity for the port
O_NDELAY means that your program ignores the DCD line
***********************************************************************************************/



if (fd == -1)

{

printf("Mensagem : Error opening serial port /dev/ttyUSB0 \n");

return (1);

}



configurePort(fd);


sendFrame = (char *) malloc(64);
sendFrame [0] = 0x55; //Sinaliza o inicio da trama
  sendFrame [1] = 64-3;  //Tamanho dos dados (payload)
sendFrame [63] = 0x55; //Simula controlo de erros
for (i=2;i<63;i++)
sendFrame[i] = (char) i-2;


printf("\n*** Frame sent ***\n");

        for (j=0;j<63;j++) 
      printf("sendFrame[%d]=%c | ",j, sendFrame [j]); // Só para teste: Mostra os caracteres a enviar

      printf("sendFrame[%d]=%c\n",j, sendFrame [j]);


        i = write(fd,sendFrame ,64); //Envio da frame
if (i < 0)

{

printf("Error sending....\n");

return (1);

}

close(fd);//hugo


/**************** Recepção da frame **************/

fd = open("/dev/ttyUSB0", O_RDWR|O_NOCTTY|O_NDELAY);//hugo
fcntl(fd, F_SETFL, FNDELAY);//hugo


recvFrame = (char*) malloc (64); 


j = read(fd,recvFrame,1);

testError();

if(recvFrame[0] != 0x55)
{

printf("Receiving: framing error...\n");

return (1);

}


j = read(fd,recvFrame+1,1);

testError();

if(recvFrame[1] != (64-3))

{

printf("Receiving: Frame size error...\n");

return (1);

}



payload = (int) recvFrame[1];

i=0;

while (i < payload)

{

j=read(fd,recvFrame+(i+2),payload);

if (j < 1) continue;

i+=j;

}

testError();

if (i != payload)

{

printf ("Receiving: frame format error\n");

return(1);

}



printf("**** Received frame ****\n");

for (j=0;j<63;j++) 

printf("recvFrame[%d]=%c | ",j, sendFrame [j]); // Só para teste: Mostra os caracteres recebidos

printf("recvFrame[%d]=%c\n",j, sendFrame [j]);



printf("*************************************************************\n");

printf("*** Congratulations: your serial port is working properly ***\n");

printf("*************************************************************\n");



return (0);

}


Entao o que eu faço é usar um cabo usb/serie e ligo o Tx ao Rx para usar a mesma porta para ler a para escrever.
O que acontece é que quando começo a ler da porta ainda nao acabei de escrever então da me erro. Se usar um sleep de 2 segundos antes de começar a ler tudo funciona as mil maravilhas. O meu Prof disse me que existia uma flag qualquer para o PC so começar a ler quando ja tiver acabado de escrever mas eu ja tentei tudo o que tinha e nao encontrei a soluçao. O meu objectivo é nao ter de usar o sleep antes de ler...


desde ja obrigado

hulkPT