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的值。C++蜂鳴器彈鋼琴音符爲Arduino
代碼從不會在循環中調用'playNote'函數,也不會將其註冊爲'ISR' – Sma
它現在可以正常工作,但無論如何它可以提高效率,因爲我需要很多其他的方法if statement for each note – Billy
使用'Timmer Interrupts'來代替等待時間。 – Sma