我正在使用mbed平台对ARM MCU上的运动控制器进行编程。我需要确定while循环的每次迭代的时间,但我正在努力想出最好的方法来做到这一点。
我有两种可能的方法:
1)定义每秒可以完成多少次迭代,并使用"wait“,这样每次迭代都会在固定的时间间隔之后发生。然后我可以递增一个计数器来确定时间。
2)在进入循环前捕获系统时间,然后连续循环,从原始系统时间减去当前系统时间,即可确定时间。
我是沿着正确的轨道思考,还是完全搞错了?
发布于 2014-09-16 05:54:12
你的第一个选择并不理想,因为等待和计数器部分会抛出数字,你最终会得到关于迭代的不太准确的信息。
第二种选择是可行的,这取决于您如何实现它。mbed有一个名为"Timer.h“的库,可以很容易地解决您的问题。计时器功能是基于中断的(如果你使用LPC1768,使用Timer3 )你可以在这里查看手册: mbed .org/ handbook /Timer。ARM支持32位地址作为Cortex-M3处理器的一部分,这意味着定时器是32位int微秒计数器。这对你的可用性意味着这个库可以保持最多30分钟的时间,所以他们是在微秒和秒之间的理想时间(如果需要更多的时间,那么你将需要一个实时时钟)。如果您想知道以毫秒或微秒为单位的计数,这取决于您。如果你想使用micro,你需要调用函数read_us(),如果你想使用micro,你可以使用read_ms()。计时器中断的使用将影响您的时间1-2微秒,因此,如果您希望跟踪到该级别而不是毫秒,您必须牢记这一点。
以下是您尝试实现的示例代码(基于LPC1768并使用在线编译器编写):
#include "mbed.h"
#include "Timer.h"
Timer timer;
Serial device (p9,p10);
int main() {
device.baud(19200); //setting baud rate
int my_num=10; //number of loops in while
int i=0;
float sum=0;
float dev=0;
float num[my_num];
float my_time[my_num]; //initial values of array set to zero
for(int i=0; i<my_num; i++)
{
my_time[i]=0; //initialize array to 0
}
timer.start(); //start timer
while (i < my_num) //collect information on timing
{
printf("Hello World\n");
i++;
my_time[i-1]=timer.read_ms(); //needs to be the last command before loop restarts to be more accurate
}
timer.stop(); //stop timer
sum=my_time[0]; //set initial value of sum to first time input
for(i=1; i < my_num; i++)
{
my_time[i]=my_time[i]-my_time[i-1]; //making the array hold each loop time
sum=sum+my_time[i]; //sum of times for mean and standard deviation
}
sum = sum/my_num; //sum of times is now the mean so as to not waste memory
device.printf("Here are the times for each loop: \n");
for(i=0; i<my_num; i++)
{
device.printf("Loop %d: %.3f\n", i+1, my_time[i]);
}
device.printf("Your average loop time is %.3f ms\n", sum);
for(int i=0; i<my_num; i++)
{
num[i]= my_time[i]-sum;
dev = dev +(num[i])*(num[i]);
}
dev = sqrt(dev/(my_num-1)); //dev is now the value of the standard deviation
device.printf("The standard deviation of your loops is %.3f ms\n", dev);
return 0;
} 您可以使用的另一个选项是Cortex计时器函数,它可以实现与上面看到的函数类似的功能,并且由于它基于微处理器的系统计时器(请在此处阅读更多信息:http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0497a/Babieigh.html),它将使您的代码更容易移植到任何具有Cortex-Mx的ARM设备上。这真的取决于你希望你的项目有多精确和可移植性!
原文来源:http://community.arm.com/groups/embedded/blog/2014/09/05/intern-inquiry-95
https://stackoverflow.com/questions/24468359
复制相似问题