【发布时间】:2019-11-01 05:21:56
【问题描述】:
我有一个简单的问题,我认为更有经验的固件开发人员能够帮助我解决这个问题。所以我对这段代码的主要目标是:
运行一个循环(检测),该循环将“监听”发生的事情,然后在达到该阈值后增加一个变量(在本例中为伏特计数)。一旦在指定时间内达到 voltscount 两次,采样循环内的第一个 while 循环将更仔细地听(通过 FFT)。
当检测循环中的阈值在特定时间段内(本例中为 3 秒)未达到时,我想退出 while 循环(停止使用 FFT 侦听)。
数字 1 已实现,但数字 2 有问题。代码似乎保留在采样内部的第一个 while 循环中(串行窗口继续显示 FFT 值而不是 0,1 或 2 -voltscount 值)在 3 秒后,该电压阈值仍低于 4.8。
我没有包括我的 void 设置和所有爵士乐,请告诉我是否需要这样才能回答我的问题。
void loop(){
detect();
sampling();
}
void detect(){
unsigned long startMillis= millis(); // Start of sample window
unsigned int peakToPeak = 0; // peak-to-peak level
unsigned int signalMax = 0;
unsigned int signalMin = 1024;
// collect data for 50 mS
while (millis() - startMillis < sampleWindow)
{
sample = analogRead(0);
if (sample < 1024) // toss out spurious readings
{
if (sample > signalMax)
{
signalMax = sample; // save just the max levels
}
else if (sample < signalMin)
{
signalMin = sample; // save just the min levels
}
}
}
peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude
volts = (peakToPeak * 5.0) / 1024; // convert to volts
Serial.println(voltscount);
}
void sampling(){
unsigned long currentMillis = millis();
if(volts >=4.8){
voltscount++;
previousMillis = millis();
}
while(voltscount >= 2){
/////SAMPLING
for(int i=0; i<samples; i++)
{
microseconds = micros(); /* Overflows after around 70 minutes! */
vReal[i] = analogRead(0);
vImag[i] = 0;
while(micros() < (microseconds + sampling_period_us)){
}
}
double x;
double v;
FFT.MajorPeak(vReal, samples, samplingFrequency, &x, &v);
Serial.print(x, 0);
Serial.print(", ");
Serial.println(v, 0);
delay(10); /* Repeat after delay */
/*
// 3 tests for smoke detector chirps and code to light up the LEDs
if (x > 4000 and x < 4900 and v > 80) {
digitalWrite(blueLEDpin, HIGH);
digitalWrite(uvLEDpin, HIGH);
delay(blueLEDdelay);
digitalWrite(blueLEDpin, LOW);
delay(uvLEDdelay);
digitalWrite(uvLEDpin, LOW);
}
if (x > 1700 and x < 1800 and v > 40) {
digitalWrite(blueLEDpin, HIGH);
digitalWrite(uvLEDpin, HIGH);
delay(blueLEDdelay);
digitalWrite(blueLEDpin, LOW);
delay(uvLEDdelay);
digitalWrite(uvLEDpin, LOW);
}
*/
if (v > 1400) {
digitalWrite(blueLEDpin, HIGH);
digitalWrite(uvLEDpin, HIGH);
delay(blueLEDdelay);
digitalWrite(blueLEDpin, LOW);
delay(uvLEDdelay);
digitalWrite(uvLEDpin, LOW);
}
if (currentMillis - previousMillis > 3000){
voltscount = 0;
break;
}
}
}
【问题讨论】:
-
好吧,如果您的意思是它在
while(micros() < (microseconds + sampling_period_us))循环中停留超过 3 秒,那么该条件成立超过 3 秒。micros(), 是什么,以微秒为单位获取当前时间?您的代码未显示分配sampling_period_us的位置。看起来sampling_period_us分配不正确。
标签: c++ while-loop arduino break