[英]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.