Page 216 - Programming Microcontrollers in C
P. 216
Pulse Width Modulator System 201
The assembly code created by the compiler for this approach is
in the address range $11d to $130. This code uses 21 bytes of
memory. Careful examination of this code will show that the instruc
tion at $122 is unneeded, so the code could have been completed in
17 bytes.
The assembly version of the same routine merely adds the two
unsigned numbers, and then rotates the result right 1 bit to accom
plish the divide by 2. The 1-bit rotate accomplishes the same thing as
a right shift by 1 bit with the exception that the carry bit is shifted
into the most significant bit of the result. The only way the carry bit
could be set is by the most significant bits of both addends being 1.
The assembly version of the code resides in $132 to $13c and re
quires 12 bytes of code.
Here is a case where judicious choice of assembly code will
provide a significant improvement in the amount of code needed to
execute a specific program. The main reason that the assembly ver
sion is shorter is that the carry bit in the condition code register is
available to the programmer from assembly. This bit is completely
hidden from the programmer in any high-level language. Therefore,
tricks like rotating a bit from the carry into a register are not avail
able in the high-level language.
EXERCISE
1. Write a routine to average readings from the ADC on a
microcontroller, but weight the current reading three times that of
the past average.
Pulse Width Modulator System
In this section on programming of the timers, two approaches to
the generation of a pulse width modulation (PWM) signal will be
discussed. These approaches both use the output compare system of
the 16-bit timer.
What is a PWM system? A PWM signal is a periodic signal where
the signal is set high for a calculated duty factor, and then the output
goes low for the remainder of the period. If you measure a PWM
signal with an averaging voltmeter it will have a value equal to the
peak voltage times the duty factor of the PWM. Here the duty factor
is defined as the ratio of the on time to repetition period of the signal.