[英]Communication with Arduino using Linux
这是我第一次使用计算机与Arduino通信。 我使用Ubuntu 14.04。 这是用于写入文件的C程序。 Arduino显示ttyACM0。
使用gcc进行编译时,编译器显示错误消息:
分段故障(核心已转储)
如何纠正此错误。
#include<unistd.h>
#include<stdio.h>
int main() {
char data[] = {'f','b','r'}; //Random data we want to send
FILE *file;
file = fopen("/dev/ttyACM0","w"); //Opening device file
int i = 0;
for(i = 0 ; i < 3 ; i++) {
fprintf(file,"%c",data[i]); //Writing to the file
fprintf(file,"%c",','); //To separate digits
sleep(1);
}
fclose(file);
}
原谅我的无知。 我试图对此进行研究。 无法运作。 在此先感谢您的帮助。
从fopen()
获得的NULL
返回是将NULL
传递给fprintf()
,它期望有效的FILE *并弄乱了SEGV
。
如果使用fopen
,则应检查它返回的内容,以便为用户提供比“分段错误”更有用的功能。
fopen()
失败的可能原因是您无权使用串行端口。
通常,您需要使用组dialout
才能访问串行端口。
以root身份执行:
usermod -a -G dialout
用户名
然后注销并重新登录,以便获得新的组。
考虑使用minicom或microcom(在其他几个串行终端程序中的任何一个上)访问串行端口,而不用自己编写。
我还建议您让Arduino在启动时发送问候消息,以确保您具有正确的波特率等。
您没有对fopen("/dev/ttyACM0","w");
的返回值进行任何成功检查fopen("/dev/ttyACM0","w");
。 如果fopen()
失败,则进一步使用file
是未定义的行为,从而导致分段错误。 做类似的事情
file = fopen("/dev/ttyACM0","w"); //Opening device file
if (file)
{
//do something with file
}
else
return 0;
另外,在结束main()
之前添加return 0
。
发生故障时, fopen
返回NULL
,因此您可能在取消引用NULL
指针,正确的做法是检查fopen
的结果。 但是我建议针对此类情况使用低级IO
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main()
{
char data[] = {'f','b','r'}; //Random data we want to send
int fd;
int i;
fd = open("/dev/ttyACM0", O_WRONLY); //Opening device file
if (fd == -1)
{
perror("cannot open /dev/ttyACM0");
return -1;
}
for(i = 0 ; i < 3 ; i++)
{
write(fd, &(data[i]), 1);
write(fd, ",", 1);
sleep(1);
}
close(fd);
return 0;
}
错误open
返回一个特殊值-1
因此您应该中止对其的写入。
我很确定在您的情况下会出现一个permission denied
错误,因为通常/dev/tty*
属于组dialout
并且默认情况下它们具有组写权限,但是由于您的用户可能不属于该组,没有对/dev/ttyACM0
写权限。
// the following code:
// compiles cleanly
// performs appropriate error checking
// has proper return statement
#include <unistd.h> // sleep()
#include <stdio.h> // fopen(), fclose(), fprintf(), perror()
#include <stdlib.h> // exit() and EXIT_FAILURE
int main()
{
char data[] = {'f','b','r'}; //Random data we want to send
FILE *file;
if( NULL == (file = fopen("/dev/ttyACM0","w") ) ) //Opening device file
{ // then fopen failed
perror("fopen failed for ttyACM0" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
int i = 0;
for(i = 0 ; i < 3 ; i++)
{
if( 0 >= fprintf(file,"%c",data[i]) ) //Writing to the file
{ // fprintf failed
perror("fprintf data failed" );
exit( EXIT_FAILURE );
}
// implied else, fprintf successful for data
if( 0 >= fprintf(file,"%c",',') ) //To separate digits
{ // then, fprintf failed
perror( "fprintf for comma failed");
exit( EXIT_FAILURE );
}
// implied else, fprintf successful for comma
sleep(1);
} // end for
fclose(file);
return(0);
} // end function: main
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.