#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pwm.h" //import file
#define PIR_PIN 2
#define BUZZER_PIN 3
#define BUTTON_PIN 4
/* PWM mode – WOKWI only has a passive buzzer (DC),
which, in comparison to an active buzzer (AC), is
missing important bits that help it function like a buzzer!
You'd think this is a downside, but it actually
makes the passive buzzer more 'customisable'
using PWM. IRL PWM is controlled using MOSFET transistors,
but in WOKWI it's an import file and a few functions
(where you manually code its On/Off function). */
// start buzzer
void buzzer_on() {
gpio_set_function(BUZZER_PIN, GPIO_FUNC_PWM); //PWM mode
uint slice_num = pwm_gpio_to_slice_num(BUZZER_PIN);
pwm_set_wrap(slice_num, 2500); //frequency (~1kHz)
pwm_set_gpio_level(BUZZER_PIN, 1250); //duty-cycle... not sure how it works but in needs to be 50%; 1250/2500
pwm_set_enabled(slice_num, true);
}
//stop buzzer
void buzzer_off() {
pwm_set_gpio_level(BUZZER_PIN, 0); //duty-cycle 0% = off
}
int main() {
stdio_init_all();
gpio_init(PIR_PIN);
gpio_set_dir(PIR_PIN, GPIO_IN);
gpio_init(BUTTON_PIN);
gpio_set_dir(BUTTON_PIN, GPIO_IN);
gpio_pull_up(BUTTON_PIN);
while (true) {
if (gpio_get(PIR_PIN)) { // Motion detected
buzzer_on();
printf("Motion detected!\n");
// Wait until button is pressed
while (gpio_get(BUTTON_PIN)) {
sleep_ms(10);
}
buzzer_off();
printf("Buzzer turned off.\n");
}
sleep_ms(100);
}
}