我正在写一个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);
}这段代码是用来发送一个字符而不是字符串的,那我该怎么办??
发布于 2014-05-10 17:50:14
我假设您有充分的理由不将write(fd,msg,strlen(msg))与参数length一起使用。所以我定义了函数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);
}安吉洛
发布于 2014-05-10 17:56:39
为什么你不正确地使用write呢?
write(fd, s, strlen(s));您必须指定要在文件描述符上打印的字节数。
也许您可以通过阅读这本关于linux上的高级编程的有趣的书来了解更多信息:http://www.advancedlinuxprogramming.com/alp-folder/alp-apB-low-level-io.pdf。
干杯
https://stackoverflow.com/questions/23579507
复制相似问题