27 enum class NoteName { C = 0, Cs, D, Ds, E, F, Fs, G, Gs, A, As, B };
37 PWM(
int channel,
int frequency_hz = 1000,
float duty_percent = 0.0f,
40 chip_path_ =
"/sys/class/pwm/pwmchip" + std::to_string(chip);
44 if (access(
pwm_path_.c_str(), F_OK) != 0) {
45 FILE* fp = fopen((
chip_path_ +
"/export").c_str(),
"w");
47 (void)(fprintf(fp,
"%d", channel));
61 float midi =
static_cast<float>(
note_) +
62 (
static_cast<float>(
octave_) + 1.0f) * 12.0f;
63 float freq = 440.0f * std::pow(2.0f, (midi - 69.0f) / 12.0f);
88 int duty_ns =
static_cast<int>(percent *
static_cast<float>(
period_ns_));
107 void Beep(uint32_t freq, uint32_t duration_ms) {
111 usleep(duration_ms * 1000);
171 FILE* fp = fopen(path.c_str(),
"w");
175 int result = fprintf(fp,
"%d", value);
PWM driver with Beep and PlayNote functionality.
int channel_
PWM channel number.
NoteName
Musical note names used for MIDI note calculation.
void SetDutyCycle(float percent)
Set the duty cycle of PWM output.
void SetFrequency(uint32_t hz)
Set the output frequency of PWM.
void Enable()
Enable the PWM output signal.
NoteName note_
Current note name.
uint32_t octave_
Current octave.
std::binary_semaphore note_sem_
Semaphore to trigger note play.
uint32_t alarm_freq_
Default alarm frequency in Hz.
std::thread note_thread_
Background thread for playing notes.
void Beep(uint32_t freq, uint32_t duration_ms)
Output a beep with specific frequency and duration.
void SetAlarmConfig(uint32_t freq, uint32_t duration_ms, uint32_t delay_ms)
Set configuration parameters for alarm beep.
int WriteSysfs(const std::string &path, int value) const
Write an integer value to a sysfs file.
PWM(int channel, int frequency_hz=1000, float duty_percent=0.0f, int chip=2)
Constructor: initializes PWM channel, sets initial frequency and duty cycle.
std::string chip_path_
Sysfs path to the PWM chip.
uint32_t alarm_delay_
Default alarm delay in ms.
uint32_t alarm_duration_
Default alarm duration in ms.
~PWM()
Destructor: disables PWM output.
std::string pwm_path_
Sysfs path to the PWM channel.
void PlayNote(NoteName note, uint32_t octave, uint32_t duration_ms)
Play a musical note based on note name and octave.
void Disable()
Disable the PWM output signal.
uint32_t duration_ms_
Duration of note in ms.
int period_ns_
PWM period in nanoseconds.
void TriggerAlarm()
Trigger an alarm sound followed by a delay.