Pot*_*mer 6 c linux serial-port
这是我的第一个C程序.你好,世界!我相信这对于高中程序员来说这不是问题,但是当我在高中时他们没有编程.:)
我想写一个串口,直到我写的字符串回显给我.然后做其他的事情.我的下面的代码运行了几秒钟,然后声称看到字符串并结束,即使它实际上没有看到字符串.它无论如何都表现得一样,我显然有一些非常错误.
是的,串行设备/ dev/kittens是真实的,当端口循环时,从终端接收(回送)串行端口上的bash回显字符串到/ dev/kittens.
我会非常感谢能够纠正错误的人.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int fd;
char *buff;
int open_port(void)
{
fd = open("/dev/kitens", 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 wr,rd;
open_port();
char msg[]="There are mice in the wire.\r";
do
{
/* Read from the port */
fcntl(fd, F_SETFL, FNDELAY);
rd=read(fd,buff,sizeof(msg));
/* Write to the port */
wr = write(fd, msg, sizeof(msg));
printf("debugging - Wrote to port\n");
usleep(10000);
if (wr < 0) {
fputs("write() to port /dev/kittens failed!\n", stderr);
break;
}
} while (buff != msg);
if (buff=msg)
printf(buff, "String Found! Now do the work.");
/*
system("dostuff.sh);
*/
/* Close the port on exit. */
close(fd);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第一,
if (buff=msg)
Run Code Online (Sandbox Code Playgroud)
是作业,而不是比较:)后者是==.
第二,
if (buff == msg)
Run Code Online (Sandbox Code Playgroud)
实际上是指针比较,而不是字符串比较.有关字符串比较,请参阅strcmp()C标准库.
第三,
char *buff;
...
rd=read(fd,buff,sizeof(msg));
Run Code Online (Sandbox Code Playgroud)
buff 没有初始化 - 没有为它分配内存,所以你很高兴它根本没有崩溃.
好吧,还有更多要检查,但上面列出的已经足以阻止程序正常运行.
作为建议:尝试在线printf下方进行调试,read以查看从端口实际读取的内容.请记住,从端口读取的数据不保证是零终止的(参见zero-terminated strings参考资料),因此您还必须注意这一点(在实际数据之后添加零,或以某种方式限制缓冲区上的字符串操作,喜欢用strncmp()而不是strcmp()).