Arduino与C++串口通信同步

Arduino and C++ Serial communication synchronization

我在这个link中使用SerialClass.h和Serial.cpp:http://playground.arduino.cc/Interfacing/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 writes" "C++ reads" 之后 "C++ writes" 之后 "Arduino reads" 之后再次 "Arduino writes"。所以,我不使用睡眠和延迟。我的第二个问题是我该如何做这个同步?我认为答案与第一个问题的答案相同。

您使用的 C++ class 没有实现自己的内部缓冲区,它依赖于硬件缓冲区和 OS 驱动程序缓冲区。 OS 可以增加驱动程序缓冲区(设备管理器 -> 端口 -> 驱动程序属性 -> 端口设置)

您的接收码有 Sleep(500) 延迟。现在想象一下,在这样一个 500 毫秒的延迟期间,UART 硬件和软件驱动程序缓冲区被填满。但是您的代码是 'sleeping' 并且没有读取缓冲数据。在此期间收到的任何数据都将被丢弃。由于 Windows 不是实时的 OS,有时您的 windows 进程没有获得足够的时间片(因为有许多其他进程)并且在这种扩展的不活动数据期间可能会丢失。所以删除 Sleep(500).

为了保证可靠的通信,接收部分必须在检测到新数据时立即缓冲数据(通常在单独的线程中,可以有更高的优先级)。主要处理逻辑应使用该缓冲数据。

你还应该实现某种协议,至少有以下 2 个:

  • 消息格式(开始、结束、大小等)
  • 消息完整性(接收到的数据没有损坏,可以是简单的校验和)

还有一些传输控制会很好(超时,回复/确认,如果有的话)。

UPD:在 Arduino 代码中 Serial.write(incomingData);确保 incomingData 正确地以零终止。并为 mySize 添加上限检查...