【发布时间】:2017-08-11 10:07:21
【问题描述】:
unsigned long t;
boolean isHigh;
#define BUZZER_PIN 3
void setup() {
// put your setup code here, to run once:
pinMode(BUZZER_PIN, OUTPUT);
isHigh = false;
t = micros();
}
void loop() {
playNote('c');
}
void playNote(char note) {
unsigned long timeToWait;
unsigned long timeToPlayTheNote = millis();
while (timeToPlayTheNote - millis() < 1000) {
if (note == 'c') {
timeToWait = 1911;
}
if (micros() - t > timeToWait) {
if (!isHigh) {
digitalWrite(BUZZER_PIN, HIGH);
isHigh = true;
} else {
digitalWrite(BUZZER_PIN, LOW);
isHigh = false;
}
t = micros();
}
}
}
我不知道为什么这不起作用。我曾经每 1,000 微秒播放一次频率,但有什么方法可以让这更简单吗?此外,使用这种方法,我必须执行 (1/f)/2,然后将该值从秒转换为微秒,并将其用作 timeToWait 的值。
【问题讨论】:
-
代码从不循环调用
playNote函数,也不会注册为ISR -
它现在可以工作了,但无论如何我都需要为每个笔记添加很多 else if 语句来提高效率
-
另一种方法是使用
Timmer Interrupts代替等待时间。 -
一个更简单的方法是将切换
BUZZER_PIN的逻辑替换为:digitalWrite(BUZZER_PIN, isHigh);isHigh=!isHigh; -
我的方法效率低吗?
标签: c++ arrays if-statement arduino