pwm-buzzer-tone-8.ino

Efinix Sapphire RV64 : Configurable 64-bit RISC-V SoC for FPGAs · File : pwm-buzzer-tone-8.ino · Language : C · Use case : Générer des mélodies simples sur un buzzer passif via PWM.

Uses the Sapphire PWM module to drive a passive buzzer and produce musical notes.

Connect a passive buzzer between the GPIO pin set to PWM mode and ground. Configure the PWM base frequency. The example generates a C-E-G triad. Adjust delays for tempo. Requires GPIO multiplexing configuration in the Efinity constraint file.

pwm-buzzer-tone-8.ino

#include "xhal_pwm.h"
#include "xhal_gpio.h"
#include "xhal_timer.h"

#define BUZZER_PIN GPIO_PIN_10 // Pin PWM capable
#define PWM_INSTANCE XHAL_PWM0
#define PWM_CHANNEL 0

// Fréquences musicales (approx)
#define NOTE_C4 262
#define NOTE_E4 330
#define NOTE_G4 392

void play_note(int freq, int duration_ms) {
    if (freq > 0) {
        xhal_pwm_set_duty(PWM_INSTANCE, PWM_CHANNEL, 50); // 50% duty
        xhal_pwm_set_freq(HZ, freq); // Hypothetical API or calculate period
        xhal_pwm_enable(PWM_INSTANCE, PWM_CHANNEL);
    } else {
        xhal_pwm_disable(PWM_INSTANCE, PWM_CHANNEL);
    }
    xhal_timer_delay_ms(duration_ms);
    xhal_pwm_disable(PWM_INSTANCE, PWM_CHANNEL);
}

int main(void) {
    xhal_gpio_init();
    xhal_gpio_config(BUZZER_PIN, GPIO_ALTERNATE); // Set to PWM function
    xhal_pwm_init(PWM_INSTANCE, 1000000); // Base clock
    
    while(1) {
        play_note(NOTE_C4, 200);
        play_note(NOTE_E4, 200);
        play_note(NOTE_G4, 200);
        play_note(0, 200); // Silence
    }
}

← Back to the board