Close

How it calculates motor speed

A project log for Smart Motor Driver for Robotics

This motor driver is able to control a motor using PID by I2C. Taking precise control of a motor have never been so easy.

danny-frDanny FR 06/24/2018 at 04:400 Comments

In this log I will explain how the microcontroller calculates the motor speed in RPM for be used later in the PID algorithm (spoiler alert, that would be a future topic) .

First let's take a look to that part of the code, shall we??? We will be using MikroC

void interrupt() iv 0x0004 ics ICS_AUTO //interrupts
{
 if (INTCON.f0 == 1 && IOCAF.f4 == 1) //interrupt on change on RA4 triggered
 {
  INTCON.f3 = 0; //disable on change interrupts
  counter ++;  //increment counter one in one
  IOCAF.f4 = 0; //clear interrupt flags
  INTCON.f3 = 1; //enable on change interrupts
 }
 if(PIR1.f0 == 1) //timer1 interrupt, called every 65.536ms
 {
  INTCON.f3 = 0; //disable on change interrupts
  T1CON.f0 =  0; //stop timer1
  rpm = (counter * 300)/gear;  //calculate rpm  (multiplied 15 interrupts in 1 second, divided 3 encoder interrupts per lap, multiplied by 60 to convert to minutes, divided by gear ratio)
  counter = 0;  //clear counter
  if(LATA.f0 == 0) //if motor is running backwards we just turn value negative
  {
    rpm = rpm *-1;
  }
  INTCON.f3 = 1; //enable on change interrupts
  PIR1.f0 = 0; //clear interrutp flag
  T1CON.f0 =  1; //start timer1
 }
}

The first thing you can see is that all process is handled using interrupts, so the microcontroller can do other things and then update once a while. The code is pretty straightforward, we use the pin state CHANGE interrupt to count up every time the hall sensor detects a change in polarity from N to S, easy right?

Next we use a timer to interrupt every 65.5 ms  and do the math, we just use the equation:

where counter is the number of times the hall sensor has changed polarity from N to S and we multiply by 300 (we divide by 3 changes from N to S are equal to one turn of motor shaft, then multiply by 15 because is the number of timer interrupts that should happen in 1 second and finally we multiply by 60 to convert to minutes). After that we now how many turns the motor will do in one minute(aka RPM), now we only divide it by the gear ratio attached and we have the RPM in the output shaft of gearbox.

As you can see is easy to make the RPM measurement in second plane, obviously the value will get updated every 65.5 ms. Not so fast, but consistent enough to run a PID algorithm and also let free time for other process. 

Discussions