簡體   English   中英

如何在C ++中從Arduino接收字符串?

[英]How to receive strings from Arduino in C++?

嘿,我在從Arduino接收字符串時遇到問題。 我在linux上運行,我想使用C ++。 我很容易將字符串從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接收字符串呢?

我不是Arduino專家,但是根據您的代碼,我得出的結論是:

  • 您正在使用串行接口發送數據
  • 您應該將串行接口連接到計算機(使用傳統的串行電纜或USB)
  • 編寫一個C ++應用程序,該應用程序將打開並從串行端口接收數據。 看到這個
  • 從Arduino規范中找出Arduino使用了哪些串行通信參數(停止位,奇偶校驗位,波特率等),並使用這些參數在C ++應用程序中配置串行端口!

希望有幫助!

使用boost.asio與串行設備和C ++通信。 它的工作原理很像,非常易於使用。 請參閱: http : //www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/overview/serial_ports.html以及以下內容: 使用Boost Asio從串行端口讀取

以下代碼等待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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM