Dynamic voltage restorers (DVRs) are a cost-effective solution to protect sensitive loads against voltage sags in mediumand high-power applications because the power required for the compensation is only a fraction of the load rated power. Voltage sag compensation with DVRs requires a robust sag detector that has to be able to address distorted grid conditions. Also, sags should be detected fast in order to guarantee adequate load protection. In this paper, a sag detection algorithm for a DVR is proposed and comprehensively analyzed. It is shown that this algorithm provides harmonic cancellation properties when the parameters are adequately tuned. Implementation aspects are addressed carefully and a method to adapt the algorithm when the grid frequency fluctuates is explained. The proposed algorithm was experimentally tested in a 5 kVA prototype of a DVR that protected a sensitive load (linear and non-linear) against voltage sags and voltage harmonics. The proposed algorithm was compared with three alternatives already proposed in the literature in terms of detection time, performance against voltage harmonics, and computational burden.