在C++ linux中将STRINGS写入串口

hai*_*adi 8 c c++ linux serial-port

我知道这个问题散布在互联网上,但是,到目前为止还没有任何东西让我完全在那里.我想将数据写入C++(linux)中的串行端口,用于Propeller板.程序在从控制台获取输入时工作正常,但是当我向其写入字符串时,总是ERROR - Invalid command从设备返回:我尝试char使用Hex值创建数组然后它工作.这是下面的工作代码.但是我怎样才能提供一个字符串变量的命令并将其发送到串口?也许,如果这是唯一的方法,我如何将其转换为十六进制值?感谢大家

注意:循环是使用来自控制台的用户输入.我需要的是一种将字符串变量发送到串行端口的方法.

#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);
}
Run Code Online (Sandbox Code Playgroud)

hai*_*adi 10

我很高兴能够解决我自己的解决方案,但却很快就没有看到这件小事了.char默认情况下是signedc ++,这使得它保持-128到127的范围.但是,我们期望ASCII值为0到255.因此它就像声明它一样简单,unsigned char str[]其他一切都应该工作.傻我,傻我.

还是,谢谢大家的帮助!


rve*_*rve 2

您确定应该以 '\r' 结尾吗?从控制台输入文本时,返回键将产生“\n”字符(在 Linux 上)而不是“\r”

open()大多数函数( 、fcntl()等)也缺少错误检查。也许这些功能之一失败了。要了解如何检查错误,请阅读手册页(例如man 2 open命令open())。如果open()手册页解释,当无法打开文件/端口时,它将返回 -1。

编辑后您写道:

char str[] = {0x56, 0x45, 0x52, 0x0D}; 
write(tty_fd,str,strlen(str));
Run Code Online (Sandbox Code Playgroud)

这是错误的。strlen需要一个以 '\0' 结尾的字符串,而 str 显然不是,所以现在它会发送您的数据以及内存中的任何内容,直到它看到 '\0'。您需要添加0x00到您的str数组中。