C++ C++;串行通信
我正在运行Ubuntu9.10,我似乎在使用termios时遇到了问题。 所以我可以启动minicom,打开57600波特的串行端口,8N1,无需硬件或软件流量控制,效果很好。我输入@17 5,我的设备就会响应。当我试图在我的C++代码中设置我的串口时,我没有得到响应。我知道软件正在与端口通信,因为led亮起 以下是我的主要观点:C++ C++;串行通信,c++,serial-port,C++,Serial Port,我正在运行Ubuntu9.10,我似乎在使用termios时遇到了问题。 所以我可以启动minicom,打开57600波特的串行端口,8N1,无需硬件或软件流量控制,效果很好。我输入@17 5,我的设备就会响应。当我试图在我的C++代码中设置我的串口时,我没有得到响应。我知道软件正在与端口通信,因为led亮起 以下是我的主要观点: int main(void) { int fd; /* File descriptor for the port */ fd = open("/dev/ke
int main(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/keyspan1", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
/*
* Could not open the port.
*/
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
fcntl(fd, F_SETFL, 0);
/*****************************CHANGE PORT OPTIONS***************************/
struct termios options;
/*
* Get the current options for the port...
*/
tcgetattr(fd, &options);
/*
* Set the baud rates to 57600...
*/
cfsetispeed(&options, B57600);
cfsetospeed(&options, B57600);
/*
* Enable the receiver and set local mode...
*/
options.c_cflag |= (CLOCAL | CREAD);
/*
* Set the new options for the port...
*/
tcsetattr(fd, TCSANOW, &options);
/***********************************END PORT OPTIONS***********************/
int n;
n = write(fd, "@17 5 \r", 7);
if (n < 0)
fputs("write() of 8 bytes failed!\n", stderr);
char buff[20];
sleep(1);
n = read(fd, buff, 10);
printf("Returned = %d\n", n);
close(fd);
return(0);
}
int main(无效)
{
int fd;/*端口的文件描述符*/
fd=打开(“/dev/keyspan1”,O|RDWR | O|NOCTTY | O|NDELAY);
如果(fd==-1)
{
/*
*无法打开端口。
*/
perror(“打开_端口:无法打开/dev/ttyS0-”;
}
其他的
fcntl(fd,F_SETFL,0);
/*****************************更改端口选项***************************/
结构termios选项;
/*
*获取端口的当前选项。。。
*/
tcgetattr(fd和选项);
/*
*将波特率设置为57600。。。
*/
cfsetispeed(和选项,B57600);
cfsetospeed(和选项,B57600);
/*
*启用接收器并设置本地模式。。。
*/
选项c|u cflag |=(CLOCAL | CREAD);
/*
*为端口设置新选项。。。
*/
tcsetattr(fd、TCSANOW和选项);
/***********************************端端口选项***********************/
int n;
n=写入(fd,“@17 5\r”,7);
if(n<0)
fputs(“写入8字节的()失败!\n”,stderr);
字符buff[20];
睡眠(1);
n=读取(fd,buff,10);
printf(“返回=%d\n”,n);
关闭(fd);
返回(0);
}
如有任何建议,将不胜感激。谢谢。您可能需要将终端初始化为原始模式。我建议您使用
cfmakeraw()
初始化术语选项结构。其中,cfmakeraw将确保流控制被禁用,奇偶校验被禁用,并且输入可以逐个字符地使用
cfmakeraw不是Posix。如果您关心可移植性,请在cfmakeraw手册页中查找它正在进行的设置。也许您只需要在发送的字符串末尾添加一个\n?如果不是这样,你可以看看我在Linux下工作的RS-232代码:在这个文件中搜索TceTattr(etc)(忽略Windows位,它们与你的情况无关)不需要
\n
…这是对一个无缓冲文件的无缓冲操作。这完全取决于串行线另一端监听的内容,不管它是否在寻找\n,我认为。@Potatoswatter:Unbuffered表示描述符的内核端处理。write()函数可以(并且至少使用glibc)执行用户端缓冲,以限制发出的系统调用的数量。确保在每个write()块之后使用fsync()。