I have an Arduino due, I am trying to keep track of ticks on two wheel encoders, polling in an infinite loop results in terrible performance. Have any suggestions?
It looks like the due might have an internal counter but I don't know how to use it, is there a library?
-
3please add your code to the post ... the performance issue may be caused by bad codejsotola– jsotola2021年06月27日 23:35:39 +00:00Commented Jun 27, 2021 at 23:35
1 Answer 1
You can use an interrupt handler to measure frequency. Works quite well.
volatile int32_t _ticks = 0;
public void FrequencyIsr()
{
_ticks++;
}
// Add this to setup()
// Mode can be FALLING, RISING or CHANGE
attachInterrupt(digitalPinToInterrupt(pin), FrequencyIsr, mode);
// Add this to loop()
int32_t currentTime = millis();
// Clear the interrupt flag, so that we can read out the counter
noInterrupts();
int32_t ticks = _ticks;
interrupts();
// and then calculate the amount of ticks since the last update (if you need the speed)
int32_t timeDelta = currentTime - _lastTime;
int32_t tickDelta = ticks - _lastTicks;
double ticksPerMs = (double)tickDelta/timeDelta;
_lastTime = currentTime;
_lastTicks = ticks;