我从C ++开始,具有“ chrono”功能,我想用它来获得电动机的速度。
为此,我有一个与电机相连的编码轮,使用光耦合器来收集由编码轮产生的平方信号。
因此,我的树莓派会收到一个平方信号,该信号的速度取决于电机的速度。
我使用计时功能来尝试计算平方信号频率的持续时间。我实现了每个信号的持续时间(几乎)为7ms。我想简单地通过公式1 / F提取频率(因此,1 / 0.007 = 142.85)。
我已经吃了一个chrono函数的文档了一个星期,但我还是一无所获...
显然,所有答案都在这里,但我不明白,我仍然是C ++的初学者:( [https://en.cppreference.com/w/cpp/chrono
这确实很有用,但仅限于https://www.code57.com/cplusplus-programming-beginners-tutorial-utilities-chrono/
如果我理解正确,则7ms的“值”存储在一个“对象”中...我怎样才能简单地将其放入标准变量中,以便对它进行除法,乘法和做任何我想做的事情?
这里是C ++代码最有趣的部分:
#include <iostream>
#include <wiringPi.h>
#include <cstdio>
#include <csignal>
#include <ctime>
#include <chrono>
// global flag used to exit from the main loop
bool RUNNING = true;
bool StartTimer = false;
//int timer = 0;
std::chrono::steady_clock::time_point BeginMeasurement; //chrono variable representing the beginning of the measurement of a motor speed
//some more code in here, but nothing exceptionnal, just calling the interruption when needed
//interruption function for counting the motor speed
void RPMCounter(){
using namespace std;
using namespace std::chrono;
if (StartTimer == true){
StartTimer = false;
steady_clock::duration result = steady_clock::now()-BeginMeasurement;
if (duration_cast<milliseconds>(result).count() < 150){
double freq;
//cout.precision(4);
std::cout << "Time = " << duration_cast<milliseconds>(result).count() << " ms" << '\n';
// I would like the next line to work and give me the frequency of the detection...
freq = 1/(duration_cast<milliseconds>(result).count()/1000);
std::cout << "Frequency = " << freq << " Hz" << '\n';
}
}
else{
BeginMeasurement = steady_clock::now();
StartTimer = true;
}
}
这是我的命令提示符中的结果:
由于我停止了电动机,所以7ms的值增加了,因此,它转得慢了才停止;)
if (duration_cast<milliseconds>(result).count() < 150){
您可以使用以下方法简化它:
if (result < 150ms)
或者如果您使用的是C ++ 11:
if (result < milliseconds{150})
优点是您不必将结果截断为粗略的精度,并且代码更易于阅读。
freq = 1/(duration_cast<milliseconds>(result).count()/1000);
代替:
using dsec = duration<double>; // define a double-based second
auto freq = 1/dsec{result}.count();
也可以写成:
auto freq = 1/duration<double>{result}.count();
无论如何,这会将result
直接转换为基于双秒的秒数,并使用浮点算术将其值反转。原始代码使用整数除法,得到的积分结果始终四舍五入为0。 1/10 == 0
,而1/10. == 0.1
。