【问题标题】:How to receive strings from Arduino in C++?如何在 C++ 中从 Arduino 接收字符串?
【发布时间】:2014-06-13 12:04:31
【问题描述】:

嘿,我在从 Arduino 接收字符串时遇到问题。我在 linux 上运行,我想使用 C++ fotr。我可以轻松地将字符串从 C++ 代码发送到 arduino。为此,我使用这样的 C++ 代码。

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream arduino("/dev/ttyACM0");
    arduino << "Led on\n";
    arduino.close();

    return 0;
}

那么我如何从 Arduino 接收字符串?

【问题讨论】:

    标签: c++ arduino


    【解决方案1】:

    我不是 Arduino 专家,但从您的代码中我得出结论:

    • 您正在使用串行接口发送数据
    • 您应该将串行接口连接到您的计算机(使用传统的串行电缆或 USB)
    • 编写一个 C++ 应用程序,打开并从串口接收数据。见this
    • 从 Arduino 规范中了解 Arduino 使用了哪些串行通信参数(停止位、奇偶校验位、波特率等),并使用这些参数在 C++ 应用程序中配置串行端口!

    希望有帮助!

    【讨论】:

    • 我看不到他/她接收数据的任何地方。我可以向 Arduino 发送数据,但我无法从 Arduino 接收数据。
    • 是的,你是对的!该代码仅检测到有要接收的字节(使用 select 系统调用)。使用 read(fd, buffer, n) 来接收字节。请参阅阅读规范:read。您接收的 c++ 代码应该在循环中调用 select 和 read 方法
    【解决方案2】:

    使用 boost.asio 与串行设备和 C++ 通信。它就像一个魅力,非常容易使用。请参阅:http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/overview/serial_ports.html 和此:Reading from serial port with Boost Asio

    【讨论】:

    • 如果我使用 boost asio,那么我的控制台输出每次都不同。我将“Data\n”从 Arduino 发送到 pc。但在控制台中我有时什么也得不到,有时只得到一些字母等等。
    【解决方案3】:

    以下代码等待来自 arduino 的响应。如果响应包含“完成”,则返回 1。如果在给定的超时时间内未找到,则返回 -1。

    不应该证明更改此代码以满足您的需要很难。

    int Serial::waitForResponse()
    {
        const int buffSize = 1024;
        char bufferChar[buffSize] = {'\0'};
        int counter = 0;
        std::string wholeAnswer = "";
    
        int noDataTime = 0;
    
        while(wholeAnswer.find("Done") == std::string::npos) //Done string was found.
        {
            if(noDataTime > 10000)
            {
                std::cout << "timeout" << std::endl;
                return -1;
            }
            counter = read(this->hSerial, bufferChar, buffSize - 1);
    
            if(counter > 0)
            {
                noDataTime = 0;
                bufferChar[counter] = '\0';
                wholeAnswer += std::string(bufferChar);
            } else
            {
                noDataTime++;
                usleep(1000);
            }
        }
        if(!wholeAnswer.empty())
        {
            return 1;
        } else
        {
            return -1;
        }
    

    【讨论】:

    • 你包含了哪些库?
    • #include #include #include #include #include 但它是一个更大整体的一部分,所以也可以是不是有一些是多余的。
    • 我收到错误:在非成员函数中无效使用“this”。
    • 就像我说的;它是一段更大的代码的一部分。本例中的hserial是一个int,由open命令(用于打开连接)返回。
    • 如果我使用 boost asio,那么我的控制台输出每次都不同。我将“Data\n”从 Arduino 发送到 pc。但在控制台中,我有时什么也得不到,有时只得到一些字母等等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多