原始代码
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream arduino_output("/dev/ttyACM0");
ifstream arduino_input("/dev/ttyACM0");
int value;
string txt;
while(cin >> value){
arduino_output << value << endl;
arduino_input >> txt;//I never recieve the "OK" (Which I should get)
cout << txt;
}
arduino_input.close();
arduino_output.close();
return(0);
}
问题是这样的:
cin >> value;
arduino_output << value << endl;
arduino_input >> txt;//I never recieve the "OK" (Which I should get)
cout << txt;
但如果我这样做,它会起作用:
cin >> value;
arduino_output << value << endl;
for(int i=0;i<10000;++i)
for(int j=0;j<10000;++j){ //Waste a lot of time
++value;
--value;
}
arduino_input >> txt; //I always recieve the "OK"
cout << txt; //I can see the "OK"
那么如何让我的快速计算机能够读取 arduino 的慢速输出呢? (不使用for循环浪费时间)
这里说了一些关于回调的事情http://www.cplusplus.com/reference/ios/ios_base/register_callback/但我永远无法让它发挥作用。它说它支持 3 个事件,但没有一个是:“如果输入缓冲区不为空,则调用此函数”。
因为最终的解决方案是输入缓冲区不为空时的回调函数。
可接受的解决方案是 arduino 版本“Serial.available()”的 C++ 等效版本。
另一个可接受的解决方案是任何迫使我不依赖两个 for 循环的解决方案。如果您这么想的话,3 个 for 循环是不可接受的。
EDIT1:显示原始代码
编辑2:我正在使用linux(lubuntu)
EDIT3:有人对代码的编写位置感到困惑。奇怪的。