Determine Motor RPM algorithm

Hi guys,

Im wondering if someone here can confirm what im trying to do is correct. Basically im trying to find the RPM of a motor (specifically the pololu 19:1 gear motor with encoder). Using an Atmega162 to control Qik2s12v10 which drives the motor and the mcu also reads the encoder channels.

I’l give as much of the code as I can here. Thanks in advance

#define INVTICK 7812    // this is 1 / 128us, to avoid using floating point math
#define RPM ((60L * INVTICK) / 64) // 64 CPR

void calc_enc_rpm(ROBOT *w)
{
   if (w->enc_read)
   {
      w->enc_period = w->enc_period_diff = w->enc_period_end - w->enc_period_start; // calculate period since last update
      if (w->enc_ticks > 1)
      {
         w->enc_period /= w->enc_ticks; // average period of all ticks during sampling interval
      }
      if (w->enc_period)
      {
         w->enc_speed = (int16_t)(RPM / w->enc_period);
      }
      else
      {
         w->enc_speed = 0;                                 // no speed
      }
      w->enc_period_start = w->enc_period_end;             // it starts from timer tick of last one
      w->enc_ticks = 0;                                    // need at least one new tick to measure period
   }
}

void motor_rpm_test(void)
{
   printf("\r*Motor RPM Test*\r");

   for (int i = 0; i < 2000;) // get 2000 samples
   {
      if (rwheel.enc_read)
      {
            calc_enc_rpm(rw);
            rwheel.enc_read = FALSE;
            printf("R: EncSpd %d, enc_period %ld, enc_period_diff %ld\r", rwheel.enc_speed, rwheel.enc_period, rwheel.enc_period_diff);
            i++;
      }
   }
}

void motorRightFwd(uint8_t speed)
{
   if (speed > 127)
   {
      sendByte(MOTOR1FORWARDFASTPACKET);
      sendByte(speed - 128);
   }
   else
   {
      sendByte(MOTOR1FORWARDPACKET);
      sendByte(speed);
   }
}

int main(void)
{
   setup();

#if DEBUG
   printf("\r\r********** Odometry Control v0.3 **********\r\r");
#endif

   motorRightFwd(60);
   motor_rpm_test();

   while(1);
}

Hello,

I am sorry we took so long to respond to your question. I looked over your code, but I am not sure how you came up with your speed calculation. What is INVTICK? (What is the significance of 1/128 us?) Where is the value of w->enc_period_end assigned?

- Kevin