问题描述
我需要通过 USB 虚拟串行设备与硬件进行通信.我所需要的只是以正确的 UART 设置以速度来回传递原始字节,我不想使用终端.使用 termios 的概念验证软件没有配置正确的位,除非我在运行之前通过 stty 输入一个神奇的配置字符串,否则它不会工作.
I need to communicate with a piece of hardware over a USB virtual serial device. All I need is it to pass raw bytes back and forth at speed with the right UART settings, I do not ever want to use a terminal. The proof of concept software using termios isn't configuring the right bits and doesn't work unless I feed in a magic config string over stty before running.
我试图从 stty 复制出现在 termios.h 的 POSIX 手册页中的每个设置,但它仍然不起作用,现在屏幕上充满了样板标志设置代码.
I attempted to replicate every setting from stty that appears in the POSIX man page for termios.h and it still doesn't work, and now has a screen full of boilerplate flag setting code.
使用 termios.h 获得无终端串口的最低配置应该是什么?如果有专门针对 Linux 的任何补充,我需要知道这些.
What should be the minimum configuration using termios.h to get a terminal-less serial port? And if there's any additions for Linux specifically I'll need to know those.
推荐答案
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
int serial_open(char *port, int baud)
{
int fd;
struct termios tty;
if((fd = open(port, O_RDWR | O_NOCTTY | O_SYNC)) < 0)
{
return -1;
}
if(tcgetattr(fd, &tty) < 0)
{
return -1;
}
cfsetospeed(&tty, (speed_t)baud);
cfsetispeed(&tty, (speed_t)baud);
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~PARENB;
tty.c_cflag |= CSTOPB;
tty.c_cflag &= ~CRTSCTS;
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if(tcsetattr(fd, TCSANOW, &tty))
{
return -1;
}
return fd;
}
/* example usage */
int fd = serial_open("/dev/ttyUSB0", B9600);
这篇关于如何使用 termios.h 配置串行端口以传递原始字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!