2013-05-18 93 views
0

您好,我嘗試編程一個Arduino從C++程序獲取命令時遇到了一些麻煩。我正在使用termios連接到Arduino。 Arduino處於網關模式(基本上它不是自己執行代碼,而是等待我的程序與我連接的硬件進行交互)。termios Arduino讀取/寫入失敗

我的設置termios的是這樣的:

SerialHandler::SerialHandler(char* fPath, int bRate) 
{ 
filePath = fPath; 
baudRate = 0; 

//Open the file, file is of type int 
file = open(filePath, O_RDWR | O_NOCTTY); 
if(file<0) //If there is an error opening the file 
{ 
    perror(filePath); 
    exit(-1); 
} 
//Save the old port settings 
tcgetattr(file, &oldtio); 
bzero(&newtio, sizeof(newtio)); 
//now to load the baudrate 
getBaudRate(bRate, baudRate); 
newtio.c_cflag = baudRate | CRTSCTS | CS8 | CLOCAL | CREAD; 

//IGNPAR ignore bits with parity errors 
//ICRNL map CR to NL ..May have to change to raw input processing 
newtio.c_iflag = IGNPAR; 

//Raw output 
newtio.c_oflag = 0; 

//ICANON - enable canonical input 
//disables echo functionality, doesnt send signals to calling program 
newtio.c_lflag = ICANON; 

//Clean and activate port 
tcflush(file, TCIFLUSH); 
tcsetattr(file, TCSANOW, &newtio); 
} 

而且我的代碼寫入和讀取到Arduino是這樣的:

void SerialHandler::getSerialOutput(char* readBuffer, int& bufferPoint) 
{ 
cout <<"Beginning read\n"; 


bufferPointer = read(file, outputBuffer,255); 
cout <<"Finished Read\n"; 
for(int i=0;i<bufferPointer;i++) 
{ 
    cout << outputBuffer[i]<<endl; 
    readBuffer[i] = outputBuffer[i]; 
} 
bufferPoint = bufferPointer; 
} 


void SerialHandler::writeSerial(char* writeBuffer, int length) 
{ 
cout << "Writing: " << writeBuffer<<endl; 
write(file,writeBuffer,length); 
cout << "Finished Write \n"; 
} 

起初我送Arduino的測試命令(「AT \ r \ n「),並用(」OK「)響應,但在此之後,任何後續的讀取/寫入都會失敗。

在測試命令上,Arduino的RX和TX引腳點亮(意味着它正在接收和發送數據),但是在發送失敗後我發送的命令。當我嘗試寫入Arduino時,Arduino不亮,任何讀取命令都無限期地掛起。

我認爲問題是像文件處理程序關閉的東西,但我不確定如何測試,或者它可能是另一個問題。

+0

總是檢查write()的返回值,處理部分寫操作。 – 2013-05-18 22:02:04

+0

嗨,你是否把返回值賦給int?我剛剛嘗試過,其結果是4爲命令工作,10爲另一個命令。這是有道理的,因爲第一個命令是4個字符長,第二個命令是10個,但程序仍然沒有實際寫入命令給Arduino。 – scrineym

+0

看起來像是一個波特率問題。你如何獲得波特率信息?你知道baudrate參數需要是'BXXXX'常量之一,並且不是任意的? – 2013-05-18 22:10:26

回答

0

嘗試從newtio.c_cflag行刪除CRTSCTS。連接串行連接的所有電纜時需要CRTSCTS。當使用Arduino時,只連接tx rx和gnd線。有關更多信息,請參見termios手冊頁http://linux.die.net/man/3/termios