首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在c++中将字符串从pc发送到arduino

在c++中将字符串从pc发送到arduino
EN

Stack Overflow用户
提问于 2014-05-10 17:44:12
回答 2查看 773关注 0票数 0

我正在写一个C++代码来与连接到串口的arduino-uno通信。我想向arduino发送一个这样的字符串:'X20C20‘

我知道如何向arduino发送单个字符,如下所示:

代码语言:javascript
复制
int fd;
char *buff;

int open_port(void)
{

 fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
 if (fd == -1)
 {
  perror("open_port: Unable to open /dev/kittens ");
 }
  else
   fcntl(fd, F_SETFL, 0);

 return (fd);
}

int main( int argc, char** argv )
{
open_port();
    int wr;


    char msg[]="h";

    /* Write to the port */
    wr = write(fd, msg, 1);
    close(fd);
  }

这段代码是用来发送一个字符而不是字符串的,那我该怎么办??

EN

回答 2

Stack Overflow用户

发布于 2014-05-10 17:50:14

我假设您有充分的理由不将write(fd,msg,strlen(msg))与参数length一起使用。所以我定义了函数send_string:

代码语言:javascript
复制
void send_string(int fd, char* s)
{
    while( *s++ )
        write(fd, *s, 1);
}

主要使用它:

代码语言:javascript
复制
int main( int argc, char** argv )
{
open_port();
    int wr;


    char* msg ="Ciao Mondo!";

    /* Write to the port */
    send_string(fd, msg);

    // or use lenght parameter
    write(fd, msg, strlen(msg));

    close(fd);
  }

安吉洛

票数 0
EN

Stack Overflow用户

发布于 2014-05-10 17:56:39

为什么你不正确地使用write呢?

代码语言:javascript
复制
write(fd, s, strlen(s));

您必须指定要在文件描述符上打印的字节数。

也许您可以通过阅读这本关于linux上的高级编程的有趣的书来了解更多信息:http://www.advancedlinuxprogramming.com/alp-folder/alp-apB-low-level-io.pdf

干杯

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23579507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档