C++ ifstream 从 linux 到 arduino [英] C++ ifstream from linux to arduino
问题描述
原始代码
#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;
但如果我这样做,它会起作用:
but if I do this instead it works:
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循环浪费时间)
So how do I make my fast computer able to read the slow output from the arduino? (Without using for-loops to waste time)
这里说一些关于回调的事情 http://www.cplusplus.com/reference/ios/ios_base/register_callback/ 但我永远无法让它工作.它说它支持 3 个事件,但没有一个是:如果输入缓冲区不为空,则调用此函数".
Here it says some things about callback http://www.cplusplus.com/reference/ios/ios_base/register_callback/ but I could never get it to work. It says it supports 3 events, and none of them are: "If input buffer is not empty, call this function".
因为最终的解决方案是在输入缓冲区不为空时使用回调函数.
Because the ultimate solution would be a callback function for whenever the input buffer is not empty.
可接受的解决方案是 arduino 版本Serial.available()"的 C++ 等效版本.
An acceptable solution would be a c++ equivalent version of the arduino version "Serial.available()".
另一个可接受的解决方案是任何迫使我不依赖两个 for 循环的东西.如果这就是您的想法,那么 3 个 for 循环是不可接受的.
Another acceptable solution would be anything that forces me to not rely on two for-loops. 3 for-loops is not acceptable if that's what you're thinking.
显示原始代码
我正在使用 linux(lubuntu)
有人对代码的编写位置感到困惑.奇怪.
Showed the original code
I am using linux(lubuntu)
Someone got confused where the code was written. Strange.
推荐答案
你的问题很奇怪.一般来说,问题在于较慢的一方无法读取较快的一方发送的内容.所以,您这里似乎有一个更根本的问题.
Your problem is weird. In general, the problem is that the slower party can't read what the faster party sends. So, it seems you have a more fundamental problem here.
如果 arduino_output
是串行端口 (UART) 的表示,我建议使用特定于平台的访问方式.在 Windows 上,有 UART 函数,在 Linux 上有 termios
(可能在大多数其他类似 POSIX 的系统上也是如此).这将为您提供一种方法来控制通信参数,并获取有关事件(包括奇偶校验/帧错误)的信息和/或通知.
If arduino_output
is a representation of a serial port (UART), I suggest to use a platform specific way of accessing it. On Windows, there are UART functions, and on Linux there's termios
(probably on most other POSIX-like, too). This will give you a way to control the parameters of communication, and get information and/or notification about events (including parity/framing errors).
这篇关于C++ ifstream 从 linux 到 arduino的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!