Jump to content

serial port problem

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
sandro76

sandro76

    Newbie

  • Members
  • Pip
  • 2 posts
Hi,
I'm programming a serial port in a Linux system.
My program send a hexadecimal values sequence on serial.
Another pc receives the message, then send to me within 100ms an ack (1 byte) and, within another 100ms the same sequence.

this is my port configuration:
tcgetattr(fd, &options);

	cfsetispeed(&options, B19200);

	cfsetospeed(&options, B19200);

	options.c_cflag |=(CLOCAL|CREAD);

	

	options.c_cflag&=~CSIZE;	

	options.c_cflag|=CS8;

	options.c_cflag|=PARENB;

	

		options.c_cflag &= ~PARODD;


	options.c_cflag&=~CSTOPB;

	//options.c_lflag=0;

	options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG | ECHONL | ECHONL);	

	options.c_cc[VTIME]=100;

	options.c_cc[VMIN]=0;

	options.c_iflag &= ~(INLCR | ICRNL);

	options.c_oflag &= ~(ONLCR);

	

	tcflush(fd, TCIFLUSH);

	tcsetattr(fd,TCSANOW,&options);				//applico le impostazioni subito	*/

}


in the program I send my messagge

write(fd, &buffer_uscita[0], 9);

			tcdrain(fd);

the I wait ack (1byte):

if (read(fd,buffer_ingresso,1))	

					{

			

						switch (buffer_ingresso[0])

							{

							case ACK:

if I receive the ack i read the response:
(the first byte it's the message's length, and I use it to know many byte i wait)

if(read(fd,buffer_ingresso,1))

			{		

			    read(fd,&buffer_ingresso[1],buffer_ingresso[0]);
.

I haven't the complete message on the buffer.
If I wait a message like this:
08 b1 03 00 01 00 00 C5

I read on my buffer_ingresso[] I read
08 b1 03 00 01 00 00 00

In another read on the program I have the rest of the message:

C5 00 00...
What can I do?
thanks

#2
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts
read() only reads as many bytes as are in the buffer at the time it's called. You will need to keep calling it until it returns zero.
sudo rm -rf /

#3
sandro76

sandro76

    Newbie

  • Members
  • Pip
  • 2 posts
	read(fd,&buffer_ingresso[0],1);		//leggo il messaggio (max 09byte) sulla seriale 

	count=1;

			while (count<buffer_ingresso[0])

				{	

					count=count+(read(fd,&buffer_ingresso[count],1));

											

				}

this works... thank you dargueta :)

#4
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts
No problem! I'd suggest doing this, though:
int bytesread = 0, totalbytesread = 0;

while( totalbytesread < BUFFER_SIZE ) {
    bytesread = read(fd, &buffer[totalbytesread], BUFFER_SIZE - totalbytesread);
    if(bytesread < 0) {
        /*some error has occurred, handle it here*/
    }
    else
        totalbytesread += bytesread;
}
This way you don't have the overhead of reading for every single byte you read - you can read multiple bytes with a single call.
sudo rm -rf /