如何使用C++在mbed设备上减慢不同频率的速度

How to slow the tempo down for different frequencies on a mbed device using C++

本文关键字:频率 速度 C++ 何使用 mbed      更新时间:2023-10-16

嗨,我正在尝试在mbed应用程序盾上使用不同的声音频率来从歌曲中创建音调。虽然我已经得到了所有的频率,但我似乎无法放慢节奏,因为它只是在所有频率中循环得非常快。我尝试使用等待();函数,但这似乎无法正常工作。我将不胜感激有关如何纠正此解决方案或替代解决方案的一些想法。

这是我的代码

#include "mbed.h"
#include "C12832.h"   // for the LCD
#include "LM75B.h"   //for the temperature sensor
#include "MMA7660.h" //For the accelerometer
/***************************************************************************
Global Variables
***************************************************************************/
C12832 shld_lcd (D11, D13, D12, D7, D10);   // LCD on the application shield
PwmOut spkr(D6); //speaker
float c = 262.0; //These are the different frequencies
float d = 294.0;
float e = 330.0;
float f = 349.0;
float g = 392.0;
float a = 440.0;
float b = 494.0;
float C = 523.0;

void hotLineBling() {
    //Here I am trying to use the frequencies to play the tone
    spkr.period(1/e);
    spkr.period(1/e);
    spkr.period(1/e);
    wait(0.5f);
    spkr.period(1/C);
    spkr.period(1/a);
    spkr.period(1/e);
    wait(0.5f);
    spkr.period(1/d);
    spkr.period(1/a);
    spkr.period(1/d);
    wait(1.0);
    spkr.period(1/C);
    spkr.period(1/a);
    spkr.period(1/e);
    wait(0.5f);
    spkr.period(1/d);
    spkr.period(1/a);
    spkr.period(1/d);
    spkr.period(1/c);
    wait(1.0);
    spkr.period(1/C);
    spkr.period(1/a);
    spkr.period(1/e);
    wait(0.5f);
    spkr.period(1/d);
    spkr.period(1/a);
    spkr.period(1/d);
    wait(5.0);
}
int main()
{
    hotLineBling();
    while (1) {
        spkr = 0.5;
        wait(0.2f); //wait a little
    }
}
您需要

将PWM引脚的值设置为要播放的内容,也可以通过这种方式控制音量。第二件事是,您需要在设置period之间等待,否则音符没有时间在该频率上实际执行任何操作。试试这个:

#include "mbed.h"
PwmOut spkr(D3);
float c = 262.0; //These are the different frequencies
float d = 294.0;
float e = 330.0;
float f = 349.0;
float g = 392.0;
float a = 440.0;
float b = 494.0;
float C = 523.0;
float _ = 0.0;
void hotLineBling() {
    float notes[] = { e, e, e, _, C, a, e, _, d, a, d, _, _,
                      C, a, e, _, d, a, d, c, _, _, C, a, e,
                      _, d, a, d };
    for (int i = 0; i < sizeof(notes) / sizeof(float); i++) {
        if (notes[i] == _) {
            spkr = 0.0f;
        }
        else {
            spkr = 0.3f;
            spkr.period(1 / notes[i]);
        }
        wait(0.5f);
    }
    spkr = 0.0f;
}
int main() {
    hotLineBling();
}

虽然我不知道这听起来是否像你想要它听起来一样:-)

我对mbed和您使用的环境都不是很熟悉 - 但有些事情似乎很明显:

  • 您正在与PWM发生器交谈并设置频率
  • 您似乎在笔记组之间等待(暂停)-至少您想要。您并没有告诉PWM在这些时间段内保持沉默(频率= 0)。
  • 您似乎还设置了PWM占空比(我假设" spkr = 0.5"线可以做到这一点)

一切都可以,但是: - 您似乎没有等待PWM实际播放音符,这取决于您希望音调存在多长时间(为每个音符设置PWM频率后应该有延迟 - 这就像将手指放在锡哨的孔上而不是吹

...你

绝对应该在spkr.period()行之间散布一些wait(),这取决于你希望每个音符播放多长时间。

如果您想要一段时间的静默,您还应该将 PWM 频率设置为 0。

我不知道的是mbed是否需要您实际"启动"PWM,或者它是否是自由运行的。