Play around with this function:
"""
`t1, t2, np = pulse_count(fs, x, xmean, up)`
Counts the number of pulses in a well behaved signal. A pulse begins when the signal crosses the value `xmean` either going up (`up=true`) or down (`up=false`).
The function returns where the first pulse starts (`t1`),
when the last pulse ends (`t2`) and the number of pulses between (`np`).
Arguments:
* `fs` Sampling rate
* `x` vector containing the signal
* `xmean` The trigger level to start counting pulses
* `up` If true, pulses begin when the signal goes up.
To calculate the mean pulse frequency, just compute
`(t2 - t1) / npulses`
"""
function pulse_count(fs, x, xmean, up=true)
n = length(x)
x0 = x .- xmean # Center the signal
# Check where x0 changes signal
sigchg = x0[1:end-1] .* x0[2:end] .< 0
# Check whether the signal is going up or down
if up
slope = x[2:end] .- x[1:end-1] .> 0
else
slope = x[2:end] .- x[1:end-1] .< 0
end
pulses = (sigchg .& slope)
npulses = sum(pulses)-1
idx = (1:n-1)[pulses]
# Interpolate the time where the first pulse starts
i = idx[1]
y1 = x0[i]
y2 = x0[i+1]
t1 = 1/fs * (i-1 - y1/(y2-y1))
# Interpolate the time where the last pulse ends
k = idx[end]
z1 = x0[k]
z2 = x0[k+1]
t2 = 1/fs * (k-1 - z1 / (z2-z1))
return t1, t2, npulses
end