我想通过 ac 程序读取连接到 FTDI 板的笔式驱动器数据的内容。我有以下代码,我可以使用它读取部分数据,但有时并非每次我将板连接到 PC 时都会发生这种情况。你能告诉我应该对代码进行哪些更改吗
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<errno.h>
#include <termios.h>
#include <unistd.h>
#include<string.h>
int n = 0;
struct termios tty;
struct termios tty_old;
main()
{
unsigned char buf[100];
int fd;
fd= open("/dev/ttyUSB0", O_RDWR| O_NOCTTY);
if(fd>0)
{
printf("Port opened\n");
}
memset (&tty, 0, sizeof tty);
printf("set attributes\n");
/* Error Handling */
if ( tcgetattr ( fd, &tty ) != 0 )
{
printf("Error from tcgetattr:%d \n",strerror(errno));
}
/* Save old tty parameters */
tty_old = tty;
memset(&tty,0,sizeof(tty));
tty.c_iflag=0;
tty.c_oflag=0;
tty.c_lflag=0;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( fd, TCIFLUSH );
if (tcsetattr (fd, TCSANOW, &tty) != 0)
{
printf("Error from tcsetattr:%d \n");
}
while(1)
{
printf("Do read and write\n");
n = read(fd,&buf, sizeof buf);
if (n < 0)
{
printf("Error reading:\n ");
break;
}
else if (n == 0)
{
printf("Read nothing!\n");
break;
}
else
{
buf[n]='\0';
printf("%s",buf);
}
}
}