与arduino的C++通信

标签 c++ arduino serial-communication

致力于使用 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/

相关文章:

c++ - 使用 gcc 编译更大的(~6MB)映射初始化 C++ 文件

c++ - Borland 断言在 local_unwind() 中失败

objective-c - Objective-C : Resource busy 中的串行通信错误

c++ - 移除 USB 设备时以编程方式中断串行 I/O - C++

c# - 用C#从串口读取所有缓冲区数据

c++ - 如何调试boost archive异常输入流错误

c++ - 如何在 Windows 中使用相同的套接字获取 ipv4 和 ipv6 数据包,它在 linux 上工作

node.js - 无法从 Arduino 以太网扩展板连接到 Node.js Web 服务器

c++ - 用 double 计算 pow 会给出错误的结果

javascript - JavaScript读取串口数据的方法