# Correct way to detect Zero crossing

203 views (last 30 days)
Anirudh Roy on 6 Dec 2019
Edited: Adam Danz on 11 Dec 2019
Hi i am implementing a power-electronics circuit that requires a zero current detector I implemented a crude function that checks if the current (through a current sensor) is more than a small quantity or not but due to this the simulation speed decreased drastically.
function y = ZCD(I)
if(I<1e-8)
y=1;
else
y=0;
end
Is there a more elegant way to find zerocrossings?

Jim Riggs on 10 Dec 2019
Edited: Jim Riggs on 11 Dec 2019
A thought you might want to consider:
if you multiply the current value, y(i) by the previous value y(i-1), this product is only negative when y(i) has crossed zero.
If y(i) and y(i-1) are both positive, the product is positive, likewise, if they are both negative, the product is positive.
zerocross = y(i)*y(i-1) < 0 ;
Now, if you care whether it's rising or falling, you need to test the sign on y(i)
if zerocross
rising = y(i) > 0 ;
falling = y(i) < 0 ; %(or falling = ~rising)
end
You can make this a function :
function zerocross = detectzerocross(x)
persistent last
if isempty(last) % initialize persistent variable
last=0;
end
zerocross = x*last>0; % = TRUE when x crosses zero
last = x;
end
This function "remembers" the last value of x each time you call it.

Adam Danz on 6 Dec 2019
Edited: Adam Danz on 11 Dec 2019
The entire function can be replaced with
y = I<1e-8;
which will return a logical (true | false). If you want a double (1 | 0),
y = double(I<1e-8);
Note that this doesn't necessarily identify zero crossings. It merely identifies values less than 1e-8.