在C++linux中将字符串写入串行端口
Writing STRINGS to serial port in C++ linux
我知道这个问题散布在互联网上,但仍然没有什么能让我完全做到这一点。我想在C++(linux)中为Propeller板的串行端口写入数据。当从控制台获取输入时,程序运行良好,但当我向它写入字符串时,它总是从设备返回:ERROR - Invalid command
。我尝试用十六进制值创建char
数组,然后它就成功了。下面是一个工作代码。但是,我如何才能提供一个字符串变量的命令,并将其发送到串行端口?也许,如果这是唯一的方法,我该如何将其转换为十六进制值?感谢大家
注意:循环使用来自控制台的用户输入。我需要的是一种将字符串变量发送到串行端口的方法
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main(int argc,char** argv){
struct termios tio;
struct termios stdio;
int tty_fd;
fd_set rdset;
unsigned char c='D';
printf("Please start with %s /dev/ttyS1 (for example)n",argv[0]);
memset(&stdio,0,sizeof(stdio));
stdio.c_iflag=0;
stdio.c_oflag=0;
stdio.c_cflag=0;
stdio.c_lflag=0;
stdio.c_cc[VMIN]=1;
stdio.c_cc[VTIME]=0;
tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
memset(&tio,0,sizeof(tio));
tio.c_iflag=0;
tio.c_oflag=0;
tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
tio.c_lflag=0;
tio.c_cc[VMIN]=1;
tio.c_cc[VTIME]=5;
tty_fd=open(argv[1], O_RDWR | O_NONBLOCK);
cfsetospeed(&tio,B115200); // 115200 baud
cfsetispeed(&tio,B115200); // 115200 baud
tcsetattr(tty_fd,TCSANOW,&tio);
//char str[] = {'V','E','R','r'};
//the above str[] doesn't work although it's exactly the same as the following
char str[] = {0x56, 0x45, 0x52, 0x0D};
write(tty_fd,str,strlen(str));
if (read(tty_fd,&c,1)>0)
write(STDOUT_FILENO,&c,1);
while (c!='q')
{
if (read(tty_fd,&c,1)>0) write(STDOUT_FILENO,&c,1); // if new data is available on the serial port, print it out
if (read(STDIN_FILENO,&c,1)>0)
if(c!='q')
write(tty_fd,&c,1); // if new data is available on the console, send it to the serial port
}
close(tty_fd);
}
我很高兴能解决自己的解决方案,但又很失望没有早点看到这件小事。默认情况下,char
是c++中的signed
,这使其保持-128到127的范围。但是,我们期望的ASCII值是0到255。因此,只需将其声明为unsigned char str[]
就可以了,其他一切都可以了。愚蠢的我,愚蠢的我。
尽管如此,还是要感谢大家对我的帮助!!!
您确定应该以'\r'结尾吗?当从控制台输入文本时,返回键将产生一个"\n"字符(在Linux上),而不是"\r"
此外,大多数函数(open()
、fcntl()
等)都缺少错误检查。也许其中一个函数失败了。要了解如何检查错误,请阅读手册页(例如open()
命令的man 2 open
。在open()
的情况下,手册页解释说,当无法打开文件/端口时,它会返回-1。
编辑后,您写道:
char str[] = {0x56, 0x45, 0x52, 0x0D};
write(tty_fd,str,strlen(str));
这是错误的。strlen
需要一个以"\0"结尾的字符串,而str显然不是,所以现在它会发送您的数据和内存中的任何内容,直到它看到"\0"为止。您需要将0x00
添加到str
阵列中。
- Qt Q串行端口未编程设备未关闭
- 在 linux c++ 中没有通过串行端口发送的数据
- 检查串行端口Linux中是否有传入数据(cbInQue for linux)
- 在不传输的情况下更改 Win32 中的串行端口波特率
- 增强 ASIO 和串行端口异步读取
- 串行端口写入究竟如何从缓冲区实际写入数据?
- 如何将参数这些串行端口传递到函数中
- 从 C/C++ 访问 Android 中的串行端口
- Qt两个串行端口发送和接收
- 通过串行端口从GPS传感器读取
- 提升 asio 串行端口"end of file"
- 通过串行端口发送多个值
- 与QSerialPort配合使用的串行端口仿真
- 使用来自串行端口的字符串数据来操作振镜扫描仪在更高的速度下会出错
- 从串行端口(带整数的字符串)解码数据
- 通过串行端口发送字符串
- Qt串行端口不能很好地读取字符串
- 将标准字符串转换为 ascii 字符并通过串行端口 c++ 发送
- 通过Raspberry Pi串行端口c++发送和接收QStrings字符串
- 在C++linux中将字符串写入串行端口