2016-11-20 127 views
0

我使用SerialClass.h和Serial.cpp在此鏈接:http://playground.arduino.cc/Interfacing/CPPWindowsArduino的和C++串行通信同步

我的main.cpp:

#include <stdio.h> 
#include <tchar.h> 
#include "SerialClass.h" // Library described above 
#include <string> 

// application reads from the specified serial port and reports the collected data 
int main(int argc, _TCHAR* argv[]) 
{ 

    printf("Welcome to the serial test app!\n\n"); 

    Serial* SP = new Serial("COM4"); // adjust as needed 

    if (SP->IsConnected()) 
     printf("We're connected\n"); 

    char incomingData[256] = "hello"; 
    int dataLength = 255; 
    int readResult = 0; 

    while(SP->IsConnected()) 
    { 
     readResult = SP->ReadData(incomingData,dataLength); 
     incomingData[readResult] = 0; 

     if(readResult != 0){ 
      printf("%s",incomingData); 
      printf("---> %d\n",readResult); 
     } 
     Sleep(500); 
    } 
    return 0; 
} 

我的Arduino代碼:

int mySize = 5; 
char incomingData[256] = "hello"; 

void setup(){ 
    Serial.begin(9600); // Seri haberleşmeyi kullanacağımızı bildirdik 
    pinMode(LedPin, OUTPUT); //LedPini çıkış olarak tanımlıyoruz. 
} 

void loop(){ 

    incomingData[mySize] = 't'; 
    ++mySize; 

    Serial.write(incomingData); 

    delay(500); 
} 

Arduino寫入字符數組,C++讀取它。問題是有時cpp缺少數據。我的輸出:

output

我的第一個問題是我能爲這個做什麼?如何在Arduino和C++之間進行同步? C++應該等待,直到arduino完成寫作。我認爲我應該使用鎖定系統或類似的東西。

等問題。我想讓我的Arduino和C++程序不斷溝通。我想這樣做:「Arduino寫道」在「Arduino讀取」之後的「C++寫入」之後的「C++讀取」之後,「Arduino寫入」之後。所以,我不使用睡眠和延遲。我的第二個問題是我該如何做這個同步?我認爲答案與第一個問題的答案相同。

回答

1

您正在使用的C++類未實現自己的內部緩衝區,它依賴於硬件緩衝區和OS驅動程序緩衝區。 OS驅動程序緩衝區可以增加(設備管理器 - >端口 - >驅動程序屬性 - >端口設置)

​​

。在你接收代碼Sleep(500)延遲。現在想象一下,在這樣一個500ms延遲期間,UART硬件和軟件驅動程序緩衝區被填滿。但是,你的代碼是'睡覺',並沒有讀取緩衝數據。在此期間收到的任何數據都將被丟棄。由於Windows不是實時操作系統,因此您的Windows進程不時會得到足夠的時間片(因爲還有很多其他進程),並且在此類擴展活動期間數據可能會丟失。所以刪除Sleep(500)

爲確保可靠的通信,接收部分必須在檢測到新數據(通常在單獨的線程中,可能具有更高的優先級)後立即緩衝數據。主處理邏輯應該與緩衝數據一起工作。

你也應當實行某種協議,至少有以下2種:

  • 消息格式(開始,結束,大小等)
  • 消息完整性(是沒有腐敗接收到的數據,可以是簡單校驗和)

此外某種傳輸控制會很好(超時,回覆/確認,如果有的話)。

UPD:在Arduino代碼中Serial.write(incomingData);確保incomingData正確地以零終止。併爲mySize添加上限檢查...