gpt4 book ai didi

与arduino的C++通信

转载 作者:太空宇宙 更新时间:2023-11-04 13:50:42 34 4
gpt4 key购买 nike

致力于使用 C++ 在 arduino 和 PC (Win 7) 之间进行通信。使用 WriteFile 和 ReadFile 创建通信或简单地发送或接收数据没有问题。但是当我想以某种方式“协调”沟通时,我遇到了问题。目标是循环(简单):

for (int i=0; i < 310; i++)
{
com->send(micro[i]);
}

调用程序,应该向 arduino 发送数据,现在只接收返回的数据。

int send(string input)
{
DWORD written, read;
char buffer[7] = {' ',' ',' ',' ',' ',' ',' '};
input.append("$");


if(!WriteFile(this->comMotor, input.c_str(), input.size(), &written, NULL))
qDebug() << "WriteFile failed"

if(written != input.c_str())
qDebug() << "write problem";


do
{
if(!ReadFile(this->comMotor, buffer, sizeof(buffer), &read, NULL))
qDebug() << "ReadFile failed";
if (read)
qDebug() << "buffer: " << buffer;
}while(!read);

我预计它会将 input 发送到 arduino,然后接收像 input 这样的字符串,而不返回 $。但它不起作用.. 它有时会读取“无”或真的延迟,我没​​想到会使用主动等待响应。我认为下一个发送的字符串应该等待响应,但显然它没有。

为了完成,这里是 arduino 中的代码:

void loop() 
{
if (Serial.available())
{
char c = Serial.read();
if (c == '$')
{
if (readString.length() >0)
{
Serial.println(readString); //prints string to serial port out
int n = readString.toInt(); //convert readString into a number
}

readString=""; //clears variable for new input
}
else
{
readString += c; //makes the string readString
}
}
}

关于如何解决这个问题的任何建议,或者知道我做错了什么?非常感谢。

编辑:编辑代码

最佳答案

已解决 - Ulrich 是对的,但遗憾的是,我只编辑了一个函数。我的错。所以问题确实在 sizeof(input.c_str()) 中,在将它到处更改为 input.size() 之后它起作用了。

关于与arduino的C++通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23546329/

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