Reputation: 11
I connect the Tx and Rx of TTY directly,and i write a string to the TTY, then,i use read() expect to get the same string i wrote before. When i run the program, i find that i could write the whole string to the TTY one time, but i only could read one character at each time when i use read() later.Please help me figure out why this happen,and how can i solve this. The system i use is Ubuntu14.04, and the compiler is gcc 4.8.2.Thank you !
This is the main function i wrote:
int main(){
int fd;
fd = open("/dev/ttyUSB0",O_RDWR);
if(fd == -1)
{
perror("serialport error\n");
}
else
{
printf("open ");
printf("%s",ttyname(fd));
printf(" succesfully\n");
}
set_speed(fd,115200);
if (set_Parity(fd,8,1,'N') == FALSE) {
printf("Set Parity Error\n");
exit (0);
}
char buf[100] = "aaaaaaaaaa";
char buf_r[100]= "12314";
int wl= write(fd,buf,strlen(buf)+1);
printf("write succesfully length %d\n",wl);
int rl=read(fd,buf_r,100);
printf("read succesfully length %d\n",rl);
while (rl<wl){
rl+=read(fd,buf_r+rl,100);
printf("read succesfully length %d\n",rl);
}
printf("buf_r=%s\n",buf_r);
close(fd);
return 0;}
This is the result of program:
open /dev/ttyUSB0 succesfully
write succesfully length 11
read succesfully length 1
read succesfully length 2
read succesfully length 3
read succesfully length 4
read succesfully length 5
read succesfully length 6
read succesfully length 7
read succesfully length 8
read succesfully length 9
read succesfully length 10
read succesfully length 11
buf_r=aaaaaaaaaa
Upvotes: 1
Views: 902
Reputation: 34829
Short answer: computers are fast, serial ports are slow.
With the settings that you are using (8 none 1) each character takes 10 bit times to transmit (1 start bit, 8 data bits, 0 parity bits, 1 stop bit). Since the baud rate is 115200, the character transmission rate is 11520 characters per second. So each character takes 87 microseconds. Sending 11 characters takes 957 microseconds, or about 1 millisecond.
Calling read
on a modern processor (with data waiting) takes only a few microseconds. So the code can read data much faster than the serial port transfers the data.
As a simple test, call usleep(1000)
before the read
and you should get all of the data in one read
.
Upvotes: 2