簡體   English   中英

Arduino和C ++串行通信同步

[英]Arduino and C++ Serial communication synchronization

我在以下鏈接中使用SerialClass.h和Serial.cpp: http ://playground.arduino.cc/Interface/CPPWindows

我的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缺少數據。 我的輸出:

輸出

我的第一個問題是我該怎么做? 如何在Arduino和C ++之間進行同步? C ++應該等待,直到arduino完成編寫。 我想我應該使用鎖系統或類似的東西。

還有其他問題。 我想讓我的Arduino和C ++程序不斷交流。 我想做的是:“ Arduino寫”在“ C ++讀”之后,在“ C ++寫”之后,在“ Arduino讀”之后又是“ Arduino寫”。 因此,我不使用睡眠和延遲。 我的第二個問題是如何進行同步? 我認為答案與第一個問題的答案相同。

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

在此處輸入圖片說明

您的接收代碼中存在Sleep(500)延遲。 現在想象一下,在500ms的延遲時間內,UART硬件和軟件驅動器緩沖區已滿。 但是您的代碼“正在休眠”,並且沒有讀取緩沖的數據。 在此期間收到的任何數據都將被丟棄。 由於Windows不是實時操作系統,因此Windows進程有時會沒有足夠的時間切片(因為還有許多其他進程),並且在這種長時間的不活動狀態下,數據可能會丟失。 因此,刪除該Sleep(500)

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

另外,您還應實施某種協議,至少應遵循以下2項:

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

同樣,某種傳輸控制也會很好(超時,回復/確認(如果有))。

UPD:用Arduino代碼Serial.write(incomingData); 確保傳入數據正確以零結尾。 並為mySize添加上限檢查...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM