To do this, we create a project called buzzer. You can see that the project structure in figure 3-11. The buzzer.c file is our main program:
Figure 3-11: Project structure for the buzzer
Firstly, we declare all required header files and define IO27 for the sound buzzer:
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#define BUZZER 27
We also define the main entry on the app_main() function. This function will execute the buzzer_task() function:
void app_main()
{
xTaskCreate(&buzzer_task, "buzzer_task", configMINIMAL_STACK_SIZE, NULL, 5, NULL);
}
Technically, we generate sound on the sensor by giving HIGH on IO27. We can use the gpio_set_level() function for this. The following is an implementation of the buzzer_task() function:
void buzzer_task(void *pvParameter)
{
// set gpio and its direction
gpio_pad_select_gpio(BUZZER);
gpio_set_direction(BUZZER, GPIO_MODE_OUTPUT);
int sounding = 1;
while(1) {
if(sounding==1){
gpio_set_level(BUZZER, 1);
sounding = 0;
}
else {
gpio_set_level(BUZZER, 0);
sounding = 1;
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
Once you have saved this program, you can compile and flash the program onto the ESP32 board.
When this has successfully completed, you should hear a sound from the buzzer device.