Code

Zero Crossing Counter

July 9, 20119 comments Coded in Matlab

In some DSP applications, it can be very helpful to know how many times your signal has crossed the zero-line (amplitude origin). 

How is this helpful?  Well, zero-crossings can tell you very quickly if your signal is composed of high frequency content or not.  Let's say your sample rate is 50kHz and over a small window of 1,000 samples there are 500 zero-crossings.  That would mean that every two samples crosses the zero-line (i.e. 12.5kHz)

In speech processing, the zero-crossing counts can help distinguish between voiced and un-voiced speech.  Un-voiced sounds are very noise-like ('Shh' and 'Sss' for example).  In addition, zero-crossings could also be used to determine if your signal has a DC offset.  If you signal is 'muted' and you are not seeing alot of zero-crossings might mean that your signal is offset from the zero-line

One nice thing about the matlab code below is that it is implemented in a very DSP-friendly way.  It ports very easily into C-Code and does minimizes the amount of conditional statements for faster processing time.

 

function count = zero_crossings(x)
% Count the number of zero-crossings from the supplied time-domain
% input vector.  A simple method is applied here that can be easily
% ported to a real-time system that would minimize the number of
% if-else conditionals.
%
% Usage:     COUNT = zero_crossings(X);
%
%            X     is the input time-domain signal (one dimensional)
%            COUNT is the amount of zero-crossings in the input signal
%
% Author:    sparafucile17 06/27/04
%

% initial value
count = 0;

% error checks
if(length(x) == 1)
    error('ERROR: input signal must have more than one element');
end

if((size(x, 2) ~= 1) && (size(x, 1) ~= 1))
    error('ERROR: Input must be one-dimensional');
end
    
% force signal to be a vector oriented in the same direction
x = x(:);

num_samples = length(x);
for i=2:num_samples

    % Any time you multiply to adjacent values that have a sign difference
    % the result will always be negative.  When the signs are identical,
    % the product will always be positive.
    if((x(i) * x(i-1)) < 0)
        count = count + 1;
    end
    
end