在C++linux中将字符串写入串行端口

Writing STRINGS to serial port in C++ linux

本文关键字:串行端口 字符串 C++linux      更新时间:2023-10-16

我知道这个问题散布在互联网上,但仍然没有什么能让我完全做到这一点。我想在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阵列中。