Page 285 - Programming Microcontrollers in C
P. 285
270 Chapter 5 Programming Large 8-Bit Systems
We will see the look-up table in some detail in Chapter 6.
We will probably run into overflow problems if care is not exercised
in the calculation of the correction ∆p . In Equation 5-1 above, p is the
c
time of a shaft rotation in milliseconds. This number can vary from 1000
to 20000 depending on the motor speed. The best approach we could
use is to divide the constant -3809500 by the value of p. Then multiply
the result by ∆p and finally divide the result by p a second time. This
approach will minimize the overflow problems. In the expression be
low, p is the measured_period, pc is the PWM_count, and ∆p is
the calculated difference motor_period - measured_period.
FOREVER
{
if(old_motor_speed!=motor_speed)
{
motor_period=30000000lu/motor_speed;
old_motor_speed=motor_speed;
PWM_count= ((motor_speed+12528)/63)*8;
PWM_count=limit(PWM_count);
delpc=(3809500/motor_period);
delpc=delpc*(motor_period-measured_period)/p;
PWM_count -= delpc;
/* read in the motor speed; */
}
}
Recall that division by 7.875 is needed in the calculation of
PWM_Count. This floating-point operation is avoided by dividing
the expression by 63/8. Most often, floating point operations can be
approximated by integer operations with sufficient accuracy.
It was mentioned earlier that it is possible to extend the maximum
measurable time to something greater than the time required to clock
the timer counter register 65535 times. If the longest time exceeds
this value, the timer overflow interrupt can be used to an advantage.
Suppose that you want to measure a long time with input capture 1.
When this measurement is started, the value in the TCNT will be
saved, and the timer overflow interrupt will be enabled. Also a counter
will be reset to zero. In the timer overflow interrupt service routine,
the counter will be incremented. Eventually, an input capture will
occur, and the time between inputs is calculated as the time remaining