gpt4 book ai didi

c++ - Arduino与C++串口通信同步

转载 作者:行者123 更新时间:2023-11-28 05:25:08 30 4
gpt4 key购买 nike

我在此链接中使用了 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 会丢失数据。我的输出:

output

我的第一个问题是我能为此做些什么?如何在Arduino和C++之间进行同步? C++应该等待,直到arduino写完。我想我应该使用锁定系统或类似的东西。

还有其他问题。我想让我的 Arduino 和 C++ 程序不断地通信。我想做的是:“Arduino 写入”在“C++ 读取”之后“C++ 写入”之后“Arduino 读取”之后再次“Arduino 写入”。所以,我不使用 sleep 和延迟。我的第二个问题是我该如何做这个同步?我认为答案与第一个问题的答案相同。

最佳答案

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

enter image description here

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

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

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

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

还有某种传输控制会很好(超时、回复/确认(如果有))。

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

关于c++ - Arduino与C++串口通信同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40702893/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com