# Extract rpm from tachometer signal

**URL:** <https://discourse.julialang.org/t/extract-rpm-from-tachometer-signal/77329>\
**Category:** Signal and Image Processing\
**Tags:** question, dsp, unitful\
**Created:** [March 2, 2022, 11:49pm UTC](https://discourse.julialang.org/t/extract-rpm-from-tachometer-signal/77329 "2022-03-02T23:49:36Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![Paulo\_Jabardo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/paulo_jabardo/32/3196_2.png) [@Paulo\_Jabardo](https://discourse.julialang.org/u/Paulo_Jabardo)\
**Post date:** [March 3, 2022, 2:11pm UTC](https://discourse.julialang.org/t/extract-rpm-from-tachometer-signal/77329/12 "2022-03-03T14:11:22Z")

</div>

Play around with this function:

```julia
"""
`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

```

---

_[View the full topic](https://discourse.julialang.org/t/extract-rpm-from-tachometer-signal/77329)._
