PIC18 Robot – Travelling exact distance straight using two wheel encoders problems

cmobile robotpicroboticswheel

(EDIT: Added TMR0 & TMR1 set-up code)

I have a small robot vehicle controlled by a PIC18f4585. It has two wheels (ball bearing on the front) as well as two rotary encoders. The following function is supposed to travel a specified distance in inches perfectly straight. It travels straight enough, the problem is the distance. the travelled distance has an error of up to 2cm. I was just wondering whether anyone else could see an error I have missed.

Additional info: The PIC is clocked at 40MHz. I am counting the encoder ticks using TMR0 and TMR1 in 8-bit mode.

Any help/suggestions would be greatly appreciated, thanks.

TMR CONFIG:

TRISAbits.TRISA4 = IO_INPUT; 
    OpenTimer0( TIMER_INT_OFF &
            T0_8BIT &
            T0_SOURCE_EXT &
            T0_EDGE_RISE &
            T0_PS_1_1   );

TRISCbits.TRISC0 = IO_INPUT;
OpenTimer1( TIMER_INT_OFF &
        T1_8BIT_RW &
        T1_SOURCE_EXT &
        T1_PS_1_1 & 
        T1_OSC1EN_OFF &
        T1_SYNC_EXT_ON  );

MOVE STRAIGHT FUNCTION:

void moveForwardDistance(double distance, int power)
{
int tickGoal = distance * 5.13348;      //This seems to get ~the correct distance

int masterPower = power;
int slavePower = power;
int error = 0;
int kp = 50;            //error factor
int totalTicks = 0;     //used to keep track of total ticks

resetEncoder();

while(totalTicks < tickGoal)
{
    SetRightMotor(masterPower);
    SetLeftMotor(slavePower);

    error = TMR1L - TMR0L;
    slavePower = power + (error / kp);

    resetEncoder();
    DelayMs(100);
    totalTicks += TMR1L;
}
SetRightMotor(0);
SetLeftMotor(0);

DelayS(1);
}

Best Answer

Sounds like you are missing encoder ticks when your CPU is busy with other tasks.

Your Robot is executing code in a loop and the loop times are approximately constant so you are missing the same number of ticks (roughly) in each loop. You've calibrated this error out of your system.

However, occasionally, you get unlucky and the loop runs longer and you miss more ticks than average.

It is impossible to decode/debug/double-check your firmware with the snippet provided since the register-level configuration of the hardware input capture unit is omitted. I'd look there.