2015-05-01 146 views
0

我一直在用Gird-Eye進行學校項目。 我使用Arduino Uno來訪問Grid-Eye數據表單。 現在我想用C++實現一個串行通信測試程序。 我使用圖書館的形式在這裏:Arduino使用visual studio C++的串行通信

http://playground.arduino.cc/Interfacing/CPPWindows

這裏是Arduino的代碼:

int data[64]; 

void setup() { 
    // put your setup code here, to run once: 
    Serial.begin(115200); 
    for (int i = 0; i < 64; ++i) { 
     data[i] = i; 
    } 
} 

void loop() { 
    // put your main code here, to run repeatedly: 
    if (Serial.available() > 0) { 
     char c = Serial.read(); 
     if (c == 'h') { Serial.write("Hello\r\n"); } 
     else if (c == 'i') { 
      for (int i = 0; i < 64; ++i) 
       Serial.println(data[i]); 
     } 
    } 
} 

這裏是main.cpp中的代碼:

int main() { 
    Serial* port = new Serial("COM5"); 

    if (port->IsConnected()) cout << "Connection established!!!" << endl; 

    char data[256] = ""; 
    int datalength = 256; 
    int readResult = 0; 

    for (int i = 0; i < 256; ++i) { data[i] = 0; } 

    string str; 
    char command[] = "i"; 
    int msglen = strlen(command); 
    port->WriteData(command, msglen); 
    while (1) { 
     while (port->ReadData(data, 256) != -1) { 
      printf("%s", data); 
     } 
    } 
    system("pause"); 
    return 0; 
} 

我能順利拿到價值與此接口。 但窗口附加顯示額外的價值。例如,程序應該像這樣結束。

.... 
61 
62 
63 

,但我得到

... 
61 
62 
63 
50 
51 
52 
53 

我不知道爲什麼會有額外的價值。 有誰能告訴我爲什麼? 謝謝!

回答

0

我相信,你需要終止您放入數據緩衝區中的每個循環迭代字符串:

while ((n = port->ReadData(data, 256)) != -1) { 
    data[n] = 0; 
    printf("%s", data); 
} 
+0

謝謝!你的建議工作! – riviera1020