USING OUTPUT COMPARE ON THE HC12

With output compare can change state of a pin on Port T (set, clear or toggle) at a particular time (when TCNT equals a desired value).

1.
In the main program:
(a)
Turn on timer subsystem (1 -> Bit 7 of TSCR reg)
(b)
Set prescaler (TMSK2 reg)
(c)
Set up PTx as OC (1 -> bit x of TIOS reg)
(d)
Set action on compare (TCTL 1-2 regs, OMx OLx bits)

OMx OLx  
0 0 Disabled
0 1 Toggle
1 0 Clear
1 1 Set

(e)
Clear Flag (1 -> bit x of TFLG1 reg; 0 -> all other bits)
(f)
Enable OC interrupt (1 -> bit x of TMSK1 reg)
(g)
Enable maskable interrupts (cli or enable();)
2.
In interrupt service routine
(a)
Set time for next action to occur (write TCx reg)
  • For periodic events add time to TCx register
            TC2 = TC2 + delta_T;
    
(b)
Clear Flag (1 -> bit x of TFLG1 reg; 0 -> all other bits)

To generate square wave at a particular frequency (e.g., 1 kHz square wave on OC2):

1.
Determine the period (period = 1/frequency) (for 1 kHz, period = 1 ms)
2.
Determine the half-period (period/2) (for 1 kHz, period = 0.5 ms)
3.
Determine number of T-clock cycles to make a half-period - you may have to adjust timer prescaler to make sure number of cycles less than 0xffff (for 1 kHz and prescaler of 0, number of cycles = 0.5ms/0.125 $\mu$s per cycle = 4000 cycles)
4.
Set of OCx pin to toggle on successful compare.
5.
In ISR, add half period to TCx (for 1 kHz square wave on OC2 and prescaler of 0,
    TC2 = TC2 + 4000;

Can generate a pulse-width-modulated signal using a single OC channel. However it is much easier to generate a PWM signal using the PWM subsystem, or using an OC channel together with OC7.



Bill Rison
2000-02-28