Lun*_*999 42 c linux serial-port tty
我正在尝试使用FTDI通过USB端口发送/接收数据,因此我需要使用C/C++处理串行通信.我正在使用Linux(Ubuntu).
基本上,我连接到正在侦听传入命令的设备.我需要发送这些命令并读取设备的响应.命令和响应都是ASCII字符.
使用GtkTerm一切正常,但是当我切换到C编程时,我遇到了问题.
这是我的代码:
#include <stdio.h> // standard input / output functions
#include <stdlib.h>
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitions
/* Open File Descriptor */
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NONBLOCK | O_NDELAY );
/* Error Handling */
if ( USB < 0 )
{
cout << "Error " << errno << " opening " << "/dev/ttyUSB0" << ": " << strerror (errno) << endl;
}
/* *** Configure Port *** */
struct termios tty;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 )
{
cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << endl;
}
/* Set Baud Rate */
cfsetospeed (&tty, B9600);
cfsetispeed (&tty, B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
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_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
tty.c_iflag &= ~(IXON | IXOFF | IXANY);// turn off s/w flow ctrl
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
tty.c_oflag &= ~OPOST; // make raw
/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0)
{
cout << "Error " << errno << " from tcsetattr" << endl;
}
/* *** WRITE *** */
unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};
int n_written = write( USB, cmd, sizeof(cmd) -1 );
/* Allocate memory for read buffer */
char buf [256];
memset (&buf, '\0', sizeof buf);
/* *** READ *** */
int n = read( USB, &buf , sizeof buf );
/* Error Handling */
if (n < 0)
{
cout << "Error reading: " << strerror(errno) << endl;
}
/* Print what I read... */
cout << "Read: " << buf << endl;
close(USB);
Run Code Online (Sandbox Code Playgroud)
会发生什么是read()返回0(根本没有读取字节)或阻塞直到timeout(VTIME).我假设发生这种情况是因为write()不发送任何东西.在这种情况下,设备将不会收到命令,我无法收到响应.事实上,当我的程序在读取时被阻止时关闭设备实际上成功获得响应(设备在关闭时发送一些东西).
奇怪的是,添加这个
cout << "I've written: " << n_written << "bytes" << endl;
Run Code Online (Sandbox Code Playgroud)
write()电话结束后,我收到:
I've written 6 bytes
Run Code Online (Sandbox Code Playgroud)
这正是我所期待的.只有我的程序不能正常工作,就像我的设备无法接收我实际在端口上写的东西一样.
我尝试了不同的东西和解决方案,也有关于数据类型(我尝试过使用std :: string,比如cmd = "INIT \r"或const char),但没有真正有效.
谁能告诉我哪里错了?
先感谢您.
编辑: 此代码的以前版本使用
unsigned char cmd[] = "INIT \n"
而且cmd[] = "INIT \r\n".我更改了它,因为我的设备的命令sintax被报告为
<command><SPACE><CR>.
我也尝试过O_NONBLOCK在阅读时避开国旗,但后来我才会阻止直到永远.我尝试过使用select()但没有任何反应.只是尝试一下,我创建了一个等待循环,直到数据可用,但我的代码永远不会退出循环.顺便说一句,等待或是usleep()我需要避免的事情.报告的只是我的代码的摘录.完整的代码需要在实时环境(特别是OROCOS)中工作,所以我真的不想要类似睡眠的功能.
Lun*_*999 67
我已经解决了我的问题,所以我在这里发布正确的代码以防有人需要类似的东西.
打开端口
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );
Run Code Online (Sandbox Code Playgroud)
设置参数
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
写
unsigned char cmd[] = "INIT \r";
int n_written = 0,
spot = 0;
do {
n_written = write( USB, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
Run Code Online (Sandbox Code Playgroud)
绝对没有必要每字节写字节,也int n_written = write( USB, cmd, sizeof(cmd) -1)工作得很好.
最后,阅读:
int n = 0,
spot = 0;
char buf = '\0';
/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);
do {
n = read( USB, &buf, 1 );
sprintf( &response[spot], "%c", buf );
spot += n;
} while( buf != '\r' && n > 0);
if (n < 0) {
std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
std::cout << "Read nothing!" << std::endl;
}
else {
std::cout << "Response: " << response << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这个对我有用.谢谢你们!