I have an incoming stream of time-series data which looks like in the below figure :-

enter image description here

I want to detect the end of each cycle in real-time (marked with red arrows) using C language. What would be the best mathematical way to do it?

Edit:- I have some liberty for delay here. I know I can't do it in a sample by sample basis. A data buffer size that is up to say one-fourth the size of the repeating pattern can be accommodated

  • $\begingroup$ What do you mean by real-time? What are your delay requirements? You won't be able to do this on a sample-by-sample basis. You need a little bit of wiggle room. $\endgroup$
    – Jdip
    Jan 25, 2023 at 14:16

1 Answer 1


If the data consistently looks like this (specifically a low frequency sinusoidal variation in the presence of noise), then low pass or bandpass filter the signal according to the known limits of its spectral occupancy and tolerable filter delay (the tighter the filter the cleaner the result if the signal is narrow band but this will be at the expense of delay and number of samples needed). If it's a sinusoid that will always be within a narrow frequency range, a 2nd order IIR resonator would be a good choice. Once filtered, take a digital derivative (which on its own will enhance high frequency noise, hence the importance to filter first), to find the inflection points. When the derivative is crossing zero and going positive, this is the location desired. Average these results to make best estimate of center crossing and blank false positives for the estimate duty cycle. If post processing consider using zero-phase filtering such as filtfilt for both the initial low pass filter and post derivative filter for avoiding having to compensate for filter delay (which optionally correcting for is not a big deal). Also see this nice summary by Richard Lyons on options for different digital differentiators.

Another robust and relatively simple approach if the source is sinusoidal (even if it a slowly varying frequency that can be over a large range) is to use an all digital Phase Lock Loop by phase locking a Numerically Controlled Oscillator (NCO). This would essentially be a narrow band frequency tracking filter, and then from the NCO phase accumulator directly we have the information of when the bottom of the sine wave is transitioned without having to do any other differentiation / filtering for detection.

  • $\begingroup$ @nitin did this answer help you? $\endgroup$ Feb 26, 2023 at 4:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.