我正在编写一个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,那我该怎么办?
答案 0 :(得分:0)
我假设你有充分的理由不使用带参数长度的write(fd,msg,strlen(msg))。所以我定义了函数send_string:
void send_string(int fd, char* s)
{
while( *s++ )
write(fd, *s, 1);
}
在主要使用它:
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);
}
安吉洛
答案 1 :(得分:0)
为什么不正确使用写入?
write(fd, s, strlen(s));
您必须指定要在文件描述符上打印的字节数。
也许你可以看到更多有关它的信息,阅读这本关于linux高级编程的有趣书籍:http://www.advancedlinuxprogramming.com/alp-folder/alp-apB-low-level-io.pdf
干杯