HC12 Microcontroller: Timer and PWM

Timer

Main (free-running) timer is a 16-bit register TCNT. It increases every clock period, and when it overflows (from 0xFFFF to 0x0000) it will set the overflow flag register TFLG2. Any access (read or write) to TCNT will reset the TFLG2 if fast flag clear all bit of system control register TSCR1 is set.

Two main use of TSCR1 is to enable main timer and enable fast flag clear.

Two main use of TSCR2 is overflow interrupt enabling and prescaler selection. The prescaler range of HC12 is from 2^0 = 1 to 2^7 = 128.

Then we should choose how to use the timer by assigning value to register TIOS. There are 8 timer channels from 0 to 7. For each channel, 0 means input capture and 1 means output compare.

Input Capture

Input capture means “when something S1 happens on this pin, do something S2.” S1 can be either rising-edge, falling-edge or both edges. To control what event will trigger input capture, assign value to register TCTL3 and TCTL4. S2 can be setting a flag or generating an interrupt. When an event occurs, it will set the timer flag accordingly. If interrupt is enabled, an interrupt will be generated.

Output Compare

Output compare means “when TCNT is equal to some value V1, do something S2”. V1 is set by register TCx. Since there are 8 channels, there are eight 16-bit registers TC0 to TC7, and each register is consist of higher part 8-bit TCxH and lower part 8-bit TCxL. That is, when TCNT reach the value TCx, channel x will do S2. S2 can be set to high, set to low, or toggle. S2 is determined by TCTL1 and TCTL2. When an event occurs, it will set the timer flag accordingly. If interrupt is enabled, an interrupt will be generated.

PWM

PWM stands for Pulse Width Modulation, that is, the output of PWM will be a square wave with customized period and duty cycle.

To use PWM in HC12, first step is to select clock source by assigning value to register PWMCLK. There are two independent prescaler to the system clock which output two independent clock A and B. Either of them can be further divided, and the output is SA and SB. Channel 0, 1, 4, 5 uses clock A/SA, and channel 2, 3 uses clock B/SB. For each channel, assigning 0 to the corresponding bit in PWMCLK will choose A (or B), 1 will choose SA (or SB).

PWMPRCLK will set prescale. PWMSCLA and PWMSCLB will set the clock divider.

PWMCTL will choose 8-bit mode or 16-bit mode. 16-bit mode is concatenating channel k and k+1. k is the higher-order channel, k+1 is the lower-order channel. Outputs will come out from channel k+1.

PWMPOL will choose the value at the beginning of the period.

PWMCAE chooses align mode (left or center). If center mode is selected, period and duty cycle value is actually half of the real value.

PWMPERx and PWMDTYx are the most important registers. PWMPERx will set the length of the period of channel x and PWMDTYx will set the length of duty cycle of channel x.

PWME will enable the PWM channel.