Atmega 1284P 扬声器输出音调频率错误

问题描述

我的课程作业给出了以下代码来编程 ATmega 1284P 芯片以通过扬声器输出声音。但是由于某种原因,输出音调(调谐?)或频率不正确——偏离了。我试了好几个喇叭,都是一样的调错。有人可以帮忙吗?代码本身可以工作,但在调用例如 set_PWM(500) 函数 (500 Hz) 后突出输出,我听到频率调低得多的声音。

预先感谢您的帮助!

void set_PWM(double frequency) {
    // Keeps track of the currently set frequency
    // Will only update the registers when the frequency
    // changes,plays music uninterrupted.
    static double current_frequency;
    if (frequency != current_frequency) {

        if (!frequency) TCCR3B &= 0x08; //stops timer/counter
        else TCCR3B |= 0x03; // resumes/continues timer/counter
        
        // prevents OCR3A from overflowing,using prescaler 64
        // 0.954 is smallest frequency that will not result in overflow
        if (frequency < 0.954) OCR3A = 0xFFFF;
        
        // prevents OCR3A from underflowing,using prescaler 64                 // 31250 is largest frequency that will not result in underflow
        else if (frequency > 31250) OCR3A = 0x0000;
        
        // set OCR3A based on desired frequency
        else OCR3A = (short)(8000000 / (128 * frequency)) - 1;

        TCNT3 = 0; // resets counter
        current_frequency = frequency;
    }
}

void PWM_on() {
    TCCR3A = (1 << COM3A0);
    // COM3A0: Toggle PB6 on compare match between counter and OCR3A
    TCCR3B = (1 << WGM32) | (1 << CS31) | (1 << CS30);
    // WGM32: When counter (TCNT3) matches OCR3A,reset counter
    // CS31 & CS30: Set a prescaler of 64
    set_PWM(0);
}

void PWM_off() {
    TCCR3A = 0x00;
    TCCR3B = 0x00;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)