如何在 ATtiny84 的快速 PWM 模式下输出与 OC1B 的比较匹配?

How do I output a compare match to OC1B in Fast PWM mode on the ATtiny84?

我的目标是从我的 ATtiny84 输出 PWM 信号,在 50hz 时高 1ms。时钟以 1mhz 运行,因此我设置了比较输出模式,输出引脚应在 19000 个时钟滴答时清除并设置为 1000。

该设备以 5V 供电,我有一个示波器从引脚 A5 (OC1B) 读取平坦的 5V 输出,没有调制。我的代码在这里:

#include <avr\io.h>

void init_pwm_generator()
{
    PORTA &= ~(1 << (PORTA5));

    ICR1  = 20000;

    TCCR1A = (1<<COM1B1) | (1<COM1B0) | (1<<WGM11);
    TCCR1B = (1<<WGM13) | (1<<WGM12) | (1<<CS10); 
}

int main(void)
{
    DDRA |=  (1 << (DDA5));

    init_pwm_generator();

    while(1)
    {   
        OCR1B = ICR1 - 1000;
    }
}

我不明白为什么这不起作用!

参见 the datasheet12.5 输入捕获单元 ,第 91

The ICR1 Register can only be written when using a Waveform Generation mode that utilizesthe ICR1 Register for defining the counter’s TOP value. In these cases the Waveform Genera-tion mode (WGM13:0) bits must be set before the TOP value can be written to the ICR1Register.

所以,正确的初始化顺序如下:

    // Init the timer
    TCCR1A = (1<<COM1B1) | (1<COM1B0) | (1<<WGM11);
    TCCR1B = (1<<WGM13) | (1<<WGM12);

    ICR1  = 19999; // set the top value
    OCR1B = 19000; // set compare match value

    TCCR1B |= (1<<CS10); // start the timer

请注意,要使计时器周期为 20000 个刻度,您必须将 TOP 值设置为 19999(因为计时器从零开始计数)