#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pwm.h"
#define BUZZER_PIN 15 // Pin connected to the buzzer
void play_tone(uint16_t frequency, uint16_t duration_ms) {
// Configure PWM slice for the buzzer pin
uint slice_num = pwm_gpio_to_slice_num(BUZZER_PIN);
pwm_set_wrap(slice_num, 125000000 / frequency - 1);
pwm_set_gpio_level(BUZZER_PIN, (125000000 / frequency - 1) / 2);
pwm_set_enabled(slice_num, true);
sleep_ms(duration_ms);
pwm_set_enabled(slice_num, false); // Turn off the tone
}
int main() {
stdio_init_all();
// Initialize the GPIO pin for PWM
gpio_set_function(BUZZER_PIN, GPIO_FUNC_PWM);
printf("Buzzer Tone Test Initialized\n");
while (true) {
// Play a 1kHz tone for 500ms
play_tone(1000, 500);
// Wait for 500ms before the next tone
sleep_ms(500);
}
}
/*simple buzzer on/off
#include <stdio.h>
#include "pico/stdlib.h"
#define BUZZER_PIN 15 // Pin connected to the buzzer
int main() {
stdio_init_all();
gpio_init(BUZZER_PIN);
gpio_set_dir(BUZZER_PIN, GPIO_OUT);
printf("Buzzer Test Initialized\n");
while (true) {
// Turn the buzzer ON
gpio_put(BUZZER_PIN, 1);
printf("Buzzer ON\n");
sleep_ms(500);
// Turn the buzzer OFF
gpio_put(BUZZER_PIN, 0);
printf("Buzzer OFF\n");
sleep_ms(500);
}
}
*/