read() is not reading the whole data
Hi all,
I am doing serial port programming very first time.
what i am trying to do is some machine is there which is communicating to the computer(LINUX) through serial port. whatever data machine writes comes on a device file "/dev/ttyS0".
now after setting all the configuration settings, i am trying to read the file.
suppose machine writes 240 bytes on the file. but when i read that file in a buffer it gives only first 8 bytes. rest of data doesnt comes.
one thing i would also like to say that , the behavior of this program is very confusing to me. :confused:
like sometime after doing some manipulation it goes working in right way. but as i close the terminal and restart the program again it shows only 8 bytes of data. machine is inserting some carriage return ,linefeed also.
with read even EOF is not working.
Code:
int main(){
struct termios new_options;
int fd; /* File descriptor for the port */
int i,t=0,b_read=0;
char c[240];
char *outbuf=NULL,cr;
cr='\xd';
outbuf=(char*)malloc(10);
bzero(c,240);
//Open the first serial port, read/write, no controlling terminal,
// not care about the Data Carrier Detect signal
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY |O_ASYNC);
if (fd == -1){
// Could not open the port.
perror("Unable to open /dev/ttyS0\n");
}
else {
// Set all flags to 0 for the read call to be blocking!???
fcntl(fd, F_SETFL, 0);
// Get the current options for the port...
tcgetattr(fd, &new_options);
// Set the baud rates to 2400...
cfsetispeed(&new_options, B2400);
cfsetospeed(&new_options, B2400);
// Enable the receiver and set local mode...
new_options.c_cflag |= (CLOCAL | CREAD);
// Set the option for 8N1
new_options.c_iflag |= IGNPAR;
new_options.c_cflag &= ~PARENB;
new_options.c_cflag &= ~CSTOPB;
new_options.c_cflag &= ~CSIZE;
new_options.c_cc[VTIME]=20;
new_options.c_cflag |= CS8;
//Set the option for raw input
new_options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// Set the option for raw output
new_options.c_oflag &=~OPOST;
// Set the new options for the port...
tcsetattr(fd, TCSANOW, &new_options);
//we r sending password to the machine to active for furthe communication.
bzero(outbuf,10);
sprintf(outbuf,"$U876",5);
write(fd,outbuf,5);
write(fd,&cr,1);
}
do{
t=read(fd,c,sizeof(c));
printf("%d\n",t);
}while(t==240);
for(i=3; i<=240; i++){
printf("%c",c[i]);
}
close(fd);
return 0;
}
thanks in advance.