背景:我有一个IOIO,我用它来测量光电二极管的输出,这是转换成数字输出。我需要找出信号在1和0之间变化的频率。到目前为止,我尝试的所有东西都挂起了我的测试应用程序,有什么建议吗?
当前代码:
if(diode == 1 && frequencyFound == false){
startTime = System.currentTimeMillis();
while((frequencyFound == false)){
if(diode == 0){
while(frequencyFound == false){
if(diode == 1){
double endTime = System.currentTimeMillis();
time = endTime - startTime;
frequency = (long) (1.0 / time);
frequencyFound = true;
}
Thread.sleep(100);
}
}
Thread.sleep(100);
}
}发布于 2012-05-13 01:03:22
这里有几个问题。
首先,Android是一个多任务系统,你可能会发现你的计时线程处于睡眠状态的时间足够长,以至于错过了一些信号转换。除了在循环中对输入进行采样之外,还有没有办法通知前沿(或尾部)边缘转换?
你看到的是哪种频率?100ms的采样间隔就足够了吗?
不要指望Thread.sleep()完全按照您指定的时间休眠。如果间隔太短,系统可能会决定立即返回,或者将睡眠时间向上舍入到更大的值。
您的计时循环不会将时间记录到优于100ms的任何精度(充其量),因此您对频率的估计将非常差。
Zapl是对的,你必须从一个独立于你的UI线程的线程中运行它。
观察一个单一的转换将给你一个非常不精确的频率估计。试试下面这样的代码:
// Find frequency to the nearest hz (+/- 10%)
// It's assumed that some other process is responsible for updating the "diode"
// variable. "diode" must be declared volatile.
long duration = 1000; // 1 second
final int interval = 100; // sampling inteval = .1 second
int oldState = diode;
int count = 0;
final long startTime = System.currentTimeMillis();
final long endtime = startTime + duration;
while (System.currentTimeMillis() < endtime) {
// count all transitions, both leading and trailing
if (diode != oldState) {
++count;
oldState = diode;
}
Thread.sleep(interval);
}
// find the actual duration
duration = System.currentTimeMillis() - startTime;
// Compute frequency. The 0.5 term is because we were counting both leading and
// trailing edges.
float frequency = 0.5 * count / (duration/1000);发布于 2012-05-13 02:10:09
对于Edward提出的一些计时精度问题,有两个更极端的建议:
https://stackoverflow.com/questions/10565144
复制相似问题