Add averaging over multiple windows for frequency measurement; optimize task yielding for USB stability.
This commit is contained in:
@@ -466,15 +466,22 @@ async fn worker(
|
|||||||
let low_th: u16 = (ADC_MAX as u16) / 3; // ~1/3 Vref
|
let low_th: u16 = (ADC_MAX as u16) / 3; // ~1/3 Vref
|
||||||
let high_th: u16 = ((ADC_MAX as u32 * 2) / 3) as u16; // ~2/3 Vref
|
let high_th: u16 = ((ADC_MAX as u32 * 2) / 3) as u16; // ~2/3 Vref
|
||||||
|
|
||||||
|
const AVG_WINDOWS: u32 = 4;
|
||||||
|
const YIELD_EVERY: u32 = 64;
|
||||||
|
let probe_duration = Duration::from_millis(100);
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
let mut total_pulses: u32 = 0;
|
||||||
|
|
||||||
|
for _ in 0..AVG_WINDOWS {
|
||||||
// Count rising edges of Q in a 100 ms window
|
// Count rising edges of Q in a 100 ms window
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
let mut pulses: u32 = 0;
|
let mut pulses: u32 = 0;
|
||||||
let mut last_q = q_high;
|
let mut last_q = q_high;
|
||||||
|
let mut iter_count: u32 = 0;
|
||||||
|
|
||||||
probe_gnd.set_as_output(Speed::Low);
|
probe_gnd.set_as_output(Speed::Low);
|
||||||
probe_gnd.set_low();
|
probe_gnd.set_low();
|
||||||
let probe_duration = Duration::from_millis(100);
|
|
||||||
while Instant::now()
|
while Instant::now()
|
||||||
.checked_duration_since(start)
|
.checked_duration_since(start)
|
||||||
.unwrap_or(Duration::from_millis(0))
|
.unwrap_or(Duration::from_millis(0))
|
||||||
@@ -506,19 +513,26 @@ async fn worker(
|
|||||||
}
|
}
|
||||||
last_q = q_high;
|
last_q = q_high;
|
||||||
|
|
||||||
// Yield to allow USB and other tasks to run
|
// Yield every YIELD_EVERY samples to keep USB alive without
|
||||||
|
// disrupting per-sample timing
|
||||||
|
iter_count += 1;
|
||||||
|
if iter_count % YIELD_EVERY == 0 {
|
||||||
yield_now().await;
|
yield_now().await;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
probe_gnd.set_as_input(Pull::None);
|
probe_gnd.set_as_input(Pull::None);
|
||||||
|
total_pulses = total_pulses.saturating_add(pulses);
|
||||||
|
}
|
||||||
|
|
||||||
let freq_hz: u32 = pulses * (1000 / probe_duration.as_millis()) as u32; // pulses per 0.1s => Hz
|
let avg_pulses = total_pulses / AVG_WINDOWS;
|
||||||
|
let freq_hz: u32 = avg_pulses * (1000 / probe_duration.as_millis()) as u32;
|
||||||
|
|
||||||
let mut msg: heapless::String<128> = heapless::String::new();
|
let mut msg: heapless::String<128> = heapless::String::new();
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
&mut msg,
|
&mut msg,
|
||||||
"555 window={}ms pulses={} freq={} Hz (A1->Q on PB0) id={:?}\r\n",
|
"555 window={}ms avg_pulses={} freq={} Hz (A1->Q on PB0) id={:?}\r\n",
|
||||||
probe_duration.as_millis(),
|
probe_duration.as_millis() * AVG_WINDOWS as u64,
|
||||||
pulses,
|
avg_pulses,
|
||||||
freq_hz,
|
freq_hz,
|
||||||
identify_id.as_raw()
|
identify_id.as_raw()
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user