【问题标题】:Arduino and C++ Serial communication synchronizationArduino与C++串口通讯同步
【发布时间】:2016-11-20 20:21:32
【问题描述】:

我在此链接中使用 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++ arduino serial-communication data-synchronization


    【解决方案1】:

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

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

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多