在Ubuntu上使用USB转串口转换器进行串行通信

时间:2011-10-19 18:54:31

标签: ubuntu serial-port

我有一个基于USB到串行转换的FTDI芯片,我将在某一时刻尝试通过RS232与电视进行通信。我正在运行Ubuntu Maverick。

我是串口通讯的新手,无法弄清楚为什么我不能简单地从端口读取字节。

串行环回测试成功。我将Tx和Rx短接在一起并运行以下C程序,我的键盘在屏幕上回显。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

int main(int argc,char** argv)
{
    struct termios tio;
    struct termios stdio;
    int tty_fd;
    fd_set rdset;

    unsigned char c='D';

    printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]);
    memset(&stdio,0,sizeof(stdio));
    stdio.c_iflag=0;
    stdio.c_oflag=0;
    stdio.c_cflag=0;
    stdio.c_lflag=0;
    stdio.c_cc[VMIN]=1;
    stdio.c_cc[VTIME]=0;
    tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
    tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
    fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);       // make the reads non-blocking




    memset(&tio,0,sizeof(tio));
    tio.c_iflag=0;
    tio.c_oflag=0;
    tio.c_cflag=CS8|CREAD|CLOCAL;           // 8n1, see termios.h for more information
    tio.c_lflag=0;
    tio.c_cc[VMIN]=1;
    tio.c_cc[VTIME]=5;

    tty_fd=open(argv[1], O_RDWR | O_NONBLOCK);
    cfsetospeed(&tio,B115200);            // 115200 baud
    cfsetispeed(&tio,B115200);            // 115200 baud

    tcsetattr(tty_fd,TCSANOW,&tio);
    while (c!='q')
    {
            if (read(tty_fd,&c,1)>0)        write(STDOUT_FILENO,&c,1);              // if new data is available on the serial port, print it out
            if (read(STDIN_FILENO,&c,1)>0)
            {
              write(tty_fd,&c,1);                     // if new data is available on the console, send it to the serial port
            }
    }

    close(tty_fd);
}

然后我将USB端插入PC上的USB(/ dev / ttyUSB0)端口,并将电缆的9针侧插入串口(/ dev / ttyS0)。

我在/ dev / ttyUSB0上运行了上一个程序并输入了另一个终端窗口:

echo "Hello world!" > /dev/ttyS0

什么都没有出现。我还尝试在/ dev / ttyUSB0和/ dev / ttyS0上的两个独立终端中运行程序,我无法从一个终端进行通信。

有谁知道我在这里做错了什么?

提前致谢!

1 个答案:

答案 0 :(得分:0)

我认为你需要配置usb serial和db9串口。 (即波特率,硬件,流量控制等)stty或setserial是两个可以实现此目的的linux命令,请在线检查手册页或示例。

之后你应该能够将字符串传递给设备,它应该可以工作。