3

我想通过 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);
        }
    }   
}
4

2 回答 2

2

当您使用 FTDI USB 到串行转换器时,必须注意连接设备的顺序。

将 FTDI 连接到计算机后,操作系统会看到一个新的串行设备。通常,这将使它尝试与串行设备握手(您可以在某些 FTDI 适配器板上看到用于 rx/tx 的闪烁 LED)。

但是,您的外围设备可能无法处理该握手并进入不一致或未知(对您而言)状态。

因此,重要的是首先将 FTDI 连接到计算机,然后将外围设备(您的笔式驱动器)连接到 FTDI。这可以确保设备看不到握手,并且您的程序可以直接与之对话。

于 2013-11-23T10:34:26.837 回答
1

Check the timing. Run the code with no device connected: it will end because n==0. I suppose the program is running after the data has been sent and the OS was not receiving data because port was not open. When it's running ok is because you got the timing between starting program and switch on the device.

To avoid this, don't stop the loop when 0 is returned. Put a condition like a key being pressed or after some time running. And remove some printf's to avoid see too many messages on console.

于 2013-11-23T09:38:55.087 回答