2025-05-20 13:26:40 +12:00
|
|
|
#ifdef PIN_BUZZER
|
|
|
|
|
#include "buzzer.h"
|
|
|
|
|
|
|
|
|
|
void genericBuzzer::begin() {
|
2025-05-20 19:33:21 +12:00
|
|
|
// Serial.print("DBG: Setting up buzzer on pin ");
|
|
|
|
|
// Serial.println(PIN_BUZZER);
|
2025-05-20 13:26:40 +12:00
|
|
|
#ifdef PIN_BUZZER_EN
|
|
|
|
|
pinMode(PIN_BUZZER_EN, OUTPUT);
|
|
|
|
|
digitalWrite(PIN_BUZZER_EN, HIGH);
|
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
|
pinMode(PIN_BUZZER, OUTPUT);
|
2025-06-06 21:55:03 +12:00
|
|
|
digitalWrite(PIN_BUZZER, LOW); // need to pull low by default to avoid extreme power draw
|
2025-05-20 13:26:40 +12:00
|
|
|
startup();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void genericBuzzer::play(const char *melody) {
|
2026-05-11 21:17:31 +02:00
|
|
|
if (isPlaying()) rtttl::stop();
|
2025-05-20 13:26:40 +12:00
|
|
|
if (_is_quiet) return;
|
2026-05-11 21:17:31 +02:00
|
|
|
rtttl::begin(PIN_BUZZER, melody);
|
2025-05-20 13:26:40 +12:00
|
|
|
// Serial.print("DBG: Playing melody - isQuiet: ");
|
|
|
|
|
// Serial.println(isQuiet());
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-11 21:17:31 +02:00
|
|
|
void genericBuzzer::playForced(const char *melody) {
|
|
|
|
|
if (isPlaying()) rtttl::stop();
|
|
|
|
|
rtttl::begin(PIN_BUZZER, melody);
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-20 13:26:40 +12:00
|
|
|
bool genericBuzzer::isPlaying() {
|
|
|
|
|
return rtttl::isPlaying();
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-12 09:17:37 +02:00
|
|
|
void genericBuzzer::applyVolume() {
|
|
|
|
|
// After tone() sets 50% duty, analogWrite overrides duty cycle on the same PWM channel.
|
|
|
|
|
// Level 4 = 50% (leave tone as-is), lower levels reduce duty = quieter output.
|
|
|
|
|
static const uint8_t duty[] = { 6, 20, 50, 90, 128 };
|
|
|
|
|
uint8_t d = duty[_volume_level < 5 ? _volume_level : 4];
|
|
|
|
|
if (d < 128) analogWrite(PIN_BUZZER, d);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void genericBuzzer::setVolume(uint8_t level) {
|
|
|
|
|
_volume_level = level < 5 ? level : 4;
|
|
|
|
|
if (isPlaying()) applyVolume();
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-20 13:26:40 +12:00
|
|
|
void genericBuzzer::loop() {
|
2026-05-12 09:17:37 +02:00
|
|
|
if (!rtttl::done()) {
|
|
|
|
|
rtttl::play();
|
|
|
|
|
if (_volume_level < 4) applyVolume();
|
|
|
|
|
}
|
2025-05-20 13:26:40 +12:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void genericBuzzer::startup() {
|
|
|
|
|
play(startup_song);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void genericBuzzer::shutdown() {
|
|
|
|
|
play(shutdown_song);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void genericBuzzer::quiet(bool buzzer_state) {
|
|
|
|
|
_is_quiet = buzzer_state;
|
2025-07-08 14:01:31 +02:00
|
|
|
#ifdef PIN_BUZZER_EN
|
|
|
|
|
if (_is_quiet) {
|
|
|
|
|
digitalWrite(PIN_BUZZER_EN, LOW);
|
|
|
|
|
} else {
|
|
|
|
|
digitalWrite(PIN_BUZZER_EN, HIGH);
|
|
|
|
|
}
|
|
|
|
|
#endif
|
2025-05-20 13:26:40 +12:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bool genericBuzzer::isQuiet() {
|
|
|
|
|
return _is_quiet;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#endif // ifdef PIN_BUZZER
|