From 3b251901addff6b2df196d6f9bb012a5ec168c6c Mon Sep 17 00:00:00 2001 From: Uwe Fechner Date: Tue, 19 Nov 2024 21:28:10 +0100 Subject: [PATCH] add delay function --- examples/test_delay.jl | 41 +++++++++++++++++++++++++++++++++++++++++ src/DiscreteFilters.jl | 11 ++++++++++- 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 examples/test_delay.jl diff --git a/examples/test_delay.jl b/examples/test_delay.jl new file mode 100644 index 0000000..d168ea0 --- /dev/null +++ b/examples/test_delay.jl @@ -0,0 +1,41 @@ +using DiscreteFilters, ControlPlots + +# Define the cut-off frequency in Hz +cut_off_freq = 2.0 + +# Define the sampling time in seconds +dt = 0.05 +sim_time = 4.0 +N = Int(sim_time / dt) + +# Design the filter +butter = create_filter(cut_off_freq; order=4, dt) +cheby1 = create_filter(cut_off_freq; order=4, type=:Cheby1, dt) + +# Create an array of measurements +measurements = zeros(N) +for i in Int(N/2):N + measurements[i] = 1.0 +end + +results = zeros(N) + +# Apply the EMA filter +last_measurement::Float64 = 0.0 +for i in 1:N + global last_measurement + results[i] = ema_filter(measurements[i], last_measurement, cut_off_freq, dt) + last_measurement = results[i] +end + +# Apply the Butterworth filter +buffer = zeros(N) +results_delay = zeros(N) +for i in 1:N + results_delay[i] = apply_delay(measurements[i], buffer, i; delay=5) +end + + +# Plot the results +plot((1:N)*dt, [measurements, results, results_delay]; xlabel="Time (s)", ylabel="Amplitude", + fig="Delay of 5 samples") \ No newline at end of file diff --git a/src/DiscreteFilters.jl b/src/DiscreteFilters.jl index 3bb4a6c..8be82aa 100644 --- a/src/DiscreteFilters.jl +++ b/src/DiscreteFilters.jl @@ -2,7 +2,7 @@ module DiscreteFilters using DSP -export ema_filter, create_filter, apply_filter +export ema_filter, create_filter, apply_filter, apply_delay """ ema_filter(measurement, last_measurement, cut_off_freq, dt) @@ -66,4 +66,13 @@ function apply_filter(butter, measurement, buffer, index) return res[index] end +function apply_delay(measurement, buffer, index; delay=1) + buffer[index] = measurement + if index-delay < 1 + return measurement + else + return buffer[index-delay] + end +end + end