用c++将字符串从PC发送到arduino

sending string from pc to arduino in c++

本文关键字:arduino PC c++ 字符串      更新时间:2023-10-16

我正在编写一个c++代码与arduino-uno连接到串口进行通信。我想发送这样一个字符串到arduino: 'X20C20'

我知道如何像这样发送单个字符到arduino:

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);
  }

这个代码用来发送一个char而不是一个String,那么我该怎么做呢??

你为什么不正确使用write ?

write(fd, s, strlen(s));

你必须指定你想要在文件描述符上打印多少字节。

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

欢呼

我假设您有很好的理由不使用write(fd, msg, strlen(msg))作为参数长度。所以我定义了函数send_string:

void send_string(int fd, char* s)
{
    while( *s++ )
        write(fd, *s, 1);
}

在main中使用:

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);
  }

安吉洛