[英]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專家,但是根據您的代碼,我得出的結論是:
希望有幫助!
使用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.