首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在C中打开、读、写串口?

如何在C中打开、读、写串口?
EN

Stack Overflow用户
提问于 2011-08-05 03:26:18
回答 1查看 466.8K关注 0票数 155

我对串行端口的读写有点困惑。我在Linux中有一个USB设备,它使用FTDI USB串行设备转换器驱动程序。当我插入它时,它会创建: /dev/ttyUSB1。

我认为它应该是简单的打开和读/写它在C。我知道波特率和奇偶校验信息,但它似乎没有标准?

是我错过了什么,还是有人给我指了个正确的方向?

EN

回答 1

Stack Overflow用户

发布于 2016-07-12 09:47:25

对于符合Setting Terminal Modes ProperlySerial Programming Guide for POSIX Operating Systems中描述的POSIX标准的演示代码,提供了以下内容。

在x86和ARM (甚至CRIS)处理器上使用Linux时,这段代码应该可以正确执行。

它本质上是从另一个答案派生出来的,但不准确和误导性的评论已经被更正。

此演示程序打开并初始化一个115200波特的串行终端,用于尽可能便携的非规范模式。

该程序将硬编码的文本串传输到另一终端,并在执行输出时延迟。

然后程序进入无限循环,以接收和显示来自串行终端的数据。

默认情况下,接收的数据显示为十六进制字节值。

要使程序将接收到的数据视为ASCII码,请使用符号DISPLAY_STRING编译程序,例如

代码语言:javascript
复制
 cc -DDISPLAY_STRING demo.c

如果接收到的数据是ASCII文本(而不是二进制数据),并且您希望将其读取为以换行符结尾的行,那么请参见this answer中的示例程序。

代码语言:javascript
复制
#define TERMINAL    "/dev/ttyUSB0"

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

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

有关为接收的数据提供缓冲但允许逐字节处理输入的有效程序的示例,请参阅this answer

票数 57
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6947413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档