Search code examples
cbinarydivision8051

What is the fastest way to do division in C for 8bit MCUs?


I am working on the firmware for a device that uses an 8bit mcu (8051 architecture). I am using SDCC (Small Device C Compiler). I have a function that I use to set the speed of a stepper motor that my circuit is driving. The speed is set by loading a desired value into the reload register for a timer. I have a variable, MotorSpeed that is in the range of 0 to 1200 which represents pulses per second to the motor. My function to convert MotorSpeed to the correct 16bit reload value is shown below. I know that float point operations are pretty slow and I am wondering if there is a faster way of doing this...

void SetSpeed()
{
    float t = MotorSpeed;
    unsigned int j = 0;
    t = 1/t ;
    t = t / 0.000001;
    j = MaxInt - t;
    TMR3RL = j;      // Set reload register for desired freq
    return;
}

Solution

  • If I understand correctly what's going on You want to calculate the expression

    MaxInt - 1000000/MotorSpeed
    

    where MotorSpeed is a number form 0 to 1200 and represents number of pulses per second.

    If Your compiler supports floating point arithmetic it must support integer division. Why don't You try that. If the speed is > 15 There is no problem, but for speeds in the range 0 to 15 the result is negative. It means that it's simply impossible to generate pulses with lower frequency than 16 Hz, if the counter is 16 bit wide and it's incremented at the rate of 1MHz. Do you have an additional prescaler that allows to reduce the frequency of increments? (I don't know 8051).