On Thu, Jan 13, 2022 at 9:50 AM Petro Karashchenko <petro.karashche...@gmail.com> wrote: > > Thank you. I would appreciate that, but I think that will work only if > there is no complete cycle between two reads, so it is potentially a > possibility to get wrong position.
Yes, that is correct. If you know what the application will be, you know the maximum speed at which pulses can be counted, then you can calculate the sample rate that guarantees this will not happen. For example a 1000 RPM motor with a 1000 line encoder x 4 (quadrature) sampled at 1 KHz will count approximately 66-67 counts per sample, so will never come close to losing complete cycles. Of course, if you don't know the application, then you cannot control this. The same is true, though, if you attempt to trigger on 0->0xffff / 0xffff->0. If you miss this single pulse, the count will be corrupted. So maybe it is better to risk missing a full cycle than to risk missing a single pulse. The code I mentioned is basically as follows (indentation is getting messed up in the email): static uint16_t Prev = 0; static uint16_t Curr = 0; static uint16_t Delta = 0; static int32_t Position = 0; . . . Prev = Curr; Curr = READ_QENCODER_COUNTER_HERE(); Delta = Curr - Prev; if (Delta > 0x7fff) { Delta = (0 - Delta); Position -= (int32_t)(Delta); } else { Position += (int32_t)(Delta); } return Position; Cheers, Nathan