2015-06-22 126 views
0

我無法使用串口從C++進行Arduino通信。我使用了Salil Kapur在這裏討論的方法:https://salilkapur.wordpress.com/2013/03/08/communicating-with-arduino-using-c/。我已經調整了使用C++直接寫入Arduino文件的策略,對於我的具體任務,我需要向Arduino發送一串char(它是用於arduino處理的命令)。我已經從C++程序中的一個文件中讀取了字符,但由於某種原因,當我發送它時,我從Arduino串口監視器上沒有收到任何信息。我認爲波特率可能是問題,但我不積極。我會給你我的代碼,以獲得特定的幫助。如果有人能告訴我如何讓C++寫的字符到串行監視器閱讀:修復Arduino和C++之間的通信Mac OS X

C++: 
#include 
#include //For sleep() 
#include //For FILE 
#include //For ifstream 
#include //For assert() 
#include //For string 
using namespace std; 

int main() 
{ 
    //Setting up the output to the Arduino 
    FILE *arduino; 
    arduino = fopen(「/dev/tty.usbmodem1411″,」w」); //Declare the file in write mode 
    if (arduino == NULL) perror (「Error opening file」); 

    //Setting up the file input stream 
    ifstream inFile (「input.txt」); 
    assert(inFile.is_open()); 

    char input = '\0'; //Starts out as NULL 

    while (input!= EOF) { 
     fprintf(arduino,」%c 「, input); //Writing to the file 
     inFile >> input; //Getting the file input to make sure it isn’t the EOF 
     sleep(1); 
    } 
    fclose(arduino); 
} 

的Arduino代碼:

:從input.txt中

void setup() 
{ 
    Serial.begin(9600); 
} 

void loop() 
{ 
    char input; 
    if(Serial.available()) //If anything is in the Serial 
    { 
     input=Serial.read(); 

     Serial.println(input); //Print out any input 
    } 
} 

樣品輸入

wadswdaasdw

字符的字符串,這將提供一個直接的根據WASD離子(上,下,左,右)。

+0

您是否嘗試過使用串口控制檯(例如PuTTY)與Arduino對話? –

+0

我的問題是通過使用boost asio庫解決的。它允許我從.txt文件讀取文本,然後通過串行將其發送到arduino。 – z4chB

回答

1

可以使用文件句柄將數據寫入串行設備,但首先嚐試使用本地Unix串行通信API作爲完整性檢查可能會有幫助。

就以todbot.com看看這篇文章:Arduino-serial: C code to talk to Arduino

的todbot.com後介紹了其串行連接交談一個Arduino的通用程序。源代碼有很多用於從命令行獲取設置的代碼,並且有點嚇人,因爲它很健壯,但是如果您想了解他是如何做到這一點的話,串行通信的業務端就相當簡單。

我寫了我自己的一系列關於這個話題的帖子,用一些輕量級的代碼(在第3部分和第4部分中)來演示如何做幾乎完全你正在做的事情。

How to read serial data from an Arduino in Linux with C: Part 1

我希望在東西這些鏈接幫助!串行通信很困難,所以如果不按照自己的方式進行,就不要打得太多。