c++ - 在 C++ linux 中将字符串写入串口

标签 c++ c linux serial-port

我知道这个问题遍布整个互联网,但仍然没有什么能让我完全解决这个问题。我想用 C++ (linux) 将数据写入 Propeller 板的串行端口。从控制台获取输入时,程序工作正常,但当我向它写入字符串时,它总是返回:ERROR - Invalid command from the device。我尝试用十六进制值创建 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[] 一样简单,其他一切都应该有效。傻我,傻我。

还是谢谢大家的帮助!!!

关于c++ - 在 C++ linux 中将字符串写入串口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340388/

相关文章:

linux - 在标题中搜索模式并打印整列

c++ - 如何更新已在 C++ 中使用 TrackPopupMenu 显示的上下文菜单

c - Swig + Lua : call m(int argv, char **argc)

c++ - 将字节写入文件

c - 在 Visual Studio 的宏中设置断点

c - 如何用宏调用只有后缀不同的函数?

arrays - bash:如何删除函数内的列表条目?

PHP 警告 : Xdebug MUST be loaded as a Zend extension

c++ - 无法围绕单个单词的输出及其相应的行号

c++ - Eclipse C++ 默认 "Hello World"错误