![](/img/trans.png)
[英]How do I use termios.h to configure a serial port to pass raw bytes?
[英]Linux Serial Port Blocked using termios.h configuration
我正在编写一个嵌入式Linux应用程序,该应用程序(1)打开与另一台设备的串行连接,(2)发送一个已知命令,(3)检查端口是否有传入字符(响应),直到检测到预期的响应短语或字符为止,(4 )重复步骤2和3,直到发送了一系列命令并接收到响应为止,(5)然后关闭端口。
我的应用程序会经历上述序列的某些循环,并且有时会不时地等待响应(读取),此时通讯突然停止并且由于内置的超时逻辑,我的软件出现了故障。
我的端口配置中是否有任何内容会由于发送的特定字节(可能是由于电气噪声)而导致端口被阻塞?
这是我打开端口的方式(通过termios.h显示配置):
struct termios options;
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) {
debug() << "Port open failed!"
return FAIL;
}
debug() << "Port Opened Successful"
fcntl(fd, F_SETFL, 0); // This setting interacts with VMIN and VTIME below
// Get options
tcgetattr(fd, &options);
// Adjust Com port options
options.c_cflag |= (CLOCAL | CREAD); // Program will not "own" port, enable reading on port
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Sets RAW input mode (does not treat input as a line of text with CR/LF ending)
options.c_oflag &= ~ OPOST; // Sets RAW ouput mode (avoids newline mapping to CR+LF characters)
options.c_iflag &= ~(IXON | IXOFF | IXANY); // Turns off SW flow c
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
// Set options
tcsetattr(fd, TCSANOW, &options);
//return fd;
return SUCCEED;
我无法弄清楚为什么在重新接通设备电源后突然间通讯会冻结然后消失。 谢谢大家!
更多信息-这是我的读写功能:
int Comm::Receive(unsigned char* rBuf)
{
int bytes;
ioctl(fd, FIONREAD, &bytes);
if (bytes >= 1)
{
bytes = read(fd, rBuf, 1);
if (bytes < 0)
return READ_ERR;
return SUCCEED;
}
else
return NO_DATA_AVAILABLE;
}
int Comm::Send(int xCt, unsigned char* xBuf)
{
int bytes;
if (fd == -1)
return FAIL;
bytes = write(fd, xBuf, xCt);
if (bytes != xCt)
return FAIL;
else
return SUCCEED;
}
欢迎来到串口的欢乐...
思想1:用select()包装您的读取调用
思考2:在tcsetattr中取消设置ICANON标志,并为故意的超时设置VTIME属性(然后显然可以处理它)
思考3:关于串行通讯的一切都无法完美地发挥作用。
在向设备发送命令并从设备读取响应时,我也遇到了类似的问题。 请参阅下面的SOF帖子,这是解决我的问题的答案。
在这些情况下,我们必须关心将用于设备通信(发送和接收)的协议。 如果我们可以成功发送命令,并且没有收到来自设备的噪音响应,则表明发送到设备的数据包中存在错误。 首先,首先检查协议规范,并为一个简单的命令(例如发出哔声)创建一个字节数组,然后发送它。
如果您可以在输出中发布完整的源代码,那么我可以为您做些事情。
享受代码。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.