4.2.2 PWM Configuration

The previous section initializes the timer so that channels A, B and C are set up for PWM. However, as the program runs, it can change the duty cycle of the PWM channels. This is done by setting OCR1A, OCR1B and OCR1C.

Each of these OCR (Output Compare Register) is a 16-bit number. So to initialize them, we need to write to the high byte first, then the low byte.

It is best to write a small subroutine to initialize these OCRs. You can write one for each channel, I am using channel A as an example:

void setOCR1A(unsigned value)
{
  OCR1AH = value >> 8;
  OCR1AL = value & 0xff;
}

Note that this code is not interrupt safe. All 16-bit timer registers use the same internal 8-bit buffer to store the high byte value. If an interrupt occurs between the two statements, and use the 8-bit buffer in the ISR, then OCR1A will be corrupted because when the low byte is written, the buffered high byte is already corrupted by the ISR.


Copyright © 2006-02-15 by Tak Auyeung