微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将STRINGS写入C linux中的串口

我知道这个问题散布在互联网上,但仍然没有让我完全在那里.我想将数据写入C( linux)中的串行端口以获得Propeller板.程序在从控制台获取输入时工作正常,但是当我向其写入字符串时,总是返回:错误 – 来自设备的无效命令.我尝试使用Hex值创建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,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,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,&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,1);

    while (c!='q')
    {
            if (read(tty_fd,1)>0)        write(STDOUT_FILENO,1); // if new data is available on the serial port,print it out
            if (read(STDIN_FILENO,1)>0) 
                if(c!='q')
                    write(tty_fd,1);        // if new data is available on the console,send it to the serial port
    }

    close(tty_fd);
}

解决方法

我很高兴能够解决我自己的解决方案,但却很快就没有看到琐碎的事情了. char认使用c进行签名,这使得它保持-128到127的范围.但是,我们期望ASCII值为0到255.因此,它就像声明为unsigned char str []和其他所有内容一样简单.应该管用.傻我,傻我.

不过,谢谢大家的帮助!

原文地址:https://www.jb51.cc/c/119024.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐