Skip to content

Commit

Permalink
add delay function
Browse files Browse the repository at this point in the history
  • Loading branch information
Uwe Fechner committed Nov 19, 2024
1 parent cf9fa0f commit 3b25190
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
41 changes: 41 additions & 0 deletions examples/test_delay.jl
Original file line number Diff line number Diff line change
@@ -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")
11 changes: 10 additions & 1 deletion src/DiscreteFilters.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

0 comments on commit 3b25190

Please sign in to comment.