c - 如何在 C 中从串口打开、读取和写入?

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

我认为用 C 语言打开和读取/写入它很简单。我知道波特率和奇偶校验信息,但似乎没有标准?

我是否遗漏了什么,或者有人能指出我正确的方向吗?

最佳答案

这是我很久以前写的(from years 1985-1992, with just a few tweaks since then),只需将所需的部分复制并粘贴到每个项目中。

您必须调用 cfmakerawtty来自 tcgetattr .您不能将 struct termios 归零,配置它,然后设置ttytcsetattr .如果您使用归零方法,那么您将遇到无法解释的间歇性故障,尤其是在 BSD 和 OS X 上。“无法解释的间歇性故障”包括卡在 read(3) 中。 .

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

int
set_interface_attribs (int fd, int speed, int parity)
{
        struct termios tty;
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tcgetattr", errno);
                return -1;
        }

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

        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // disable break processing
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
        tty.c_oflag = 0;                // no remapping, no delays
        tty.c_cc[VMIN]  = 0;            // read doesn't block
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                error_message ("error %d from tcsetattr", errno);
                return -1;
        }
        return 0;
}

void
set_blocking (int fd, int should_block)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tggetattr", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                error_message ("error %d setting term attributes", errno);
}


...
char *portname = "/dev/ttyUSB1"
 ...
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
        error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
        return;
}

set_interface_attribs (fd, B115200, 0);  // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0);                // set no blocking

write (fd, "hello!\n", 7);           // send 7 character greeting

usleep ((7 + 25) * 100);             // sleep enough to transmit the 7 plus
                                     // receive 25:  approx 100 uS per char transmit
char buf [100];
int n = read (fd, buf, sizeof buf);  // read up to 100 characters if ready to read

速度值为B115200 , B230400 , B9600 , B19200 , B38400 , B57600 , B1200 , B2400 , B4800等。奇偶校验的值为0 (表示无奇偶校验),PARENB|PARODD (启用奇偶校验并使用奇数),PARENB (启用奇偶校验并使用偶数),PARENB|PARODD|CMSPAR (标记奇偶校验)和PARENB|CMSPAR (空间奇偶校验)。

“阻塞”设置是否 read()在端口上等待指定数量的字符到达。设置不阻塞意味着read()返回但是有许多字符可用,而无需等待更多字符,直到缓冲区限制。


附录:

CMSPAR仅用于选择标记和空间奇偶校验,这是不常见的。对于大多数应用程序,它可以省略。我的头文件/usr/include/bits/termios.h启用 CMSPAR 的定义仅当预处理器符号 __USE_MISC被定义为。该定义出现(在 features.h 中)与

#if defined _BSD_SOURCE || defined _SVID_SOURCE
 #define __USE_MISC     1
#endif

<features.h> 的介绍性评论说:

/* These are defined by the user (or the compiler)
   to specify the desired environment:

...
   _BSD_SOURCE          ISO C, POSIX, and 4.3BSD things.
   _SVID_SOURCE         ISO C, POSIX, and SVID things.
...
 */

https://stackoverflow.com/questions/6947413/

相关文章:

python - 如何实现有序的默认字典?

python - pip 相当于 `npm install package --save-dev`

linux - 如何通过脚本创建 crontab

linux - 递归列出目录中的所有文件,包括符号链接(symbolic link)目录中的文件

python - 你如何在 django 网站上记录服务器错误

linux - Linux 环境变量名称中允许的字符

python - 如何使用 python smtplib 向多个收件人发送电子邮件?

linux - 如何使用 sed 删除文件的最后 n 行

python - 如何打开一个文件进行读写?

python - 如何避免 __init__ 中的 "self.x = x; self.y = y;