Buzzer
1. Learning Objectives
2. Hardware Construction
This Lesson.
Active buzzer1
220Ω resistor1
The circuit wiring diagram is shown in the figure below: (replace the LED with a buzzer, and the buzzer + sign is connected to the resistor end)
3. Program Analysis
C programming
For the use of SDK in C, please refer to the previous courses related to environment building.
x
int main()
{
const uint BUZZER_PIN = 15;
gpio_init(BUZZER_PIN);
gpio_set_dir(BUZZER_PIN, GPIO_OUT);
while (1) {
for(int i = 0;i<80;i++)
{
gpio_put(BUZZER_PIN, 1);
sleep_ms(1);
gpio_put(BUZZER_PIN, 0);
sleep_ms(1);
}
for(int i = 0;i<100;i++)
{
gpio_put(BUZZER_PIN, 1);
sleep_ms(2);
gpio_put(BUZZER_PIN, 0);
sleep_ms(2);
}
}
}
#include "pico/stdlib.h" This library includes common hardware and high-level libraries like hardware_gpio and pico_time, it also introduces components like pico_standard_link.
gpio_init(BUZZER_PIN); Initializes the buzzer pin, clears its output enable, clears any of its output values.
gpio_set_dir(BUZZER_PIN,GPIO_OUT); Set the buzzer pin to output mode.
Through the While loop, two different for loops make the buzzer sound at different frequencies.
4. Program creation and burning To create a project, please refer to the previous tutorial on creating a project, which will not be repeated here. After writing the program, you need to add the standard library to the build according to the program you wrote before compiling, open CMakeLists.txt in the project, and check target_link_libraries(buzzer pico_stdlib), It can be seen that since the previous program only uses the pico_stdlib library, only pico_stdlib is added here. If other libraries are added to the functions used, the corresponding libraries need to be added. If you do not know where to add the libraries, you can go to the official pico-examples case downloaded earlier, which contains the cases of each function and the corresponding CMakeLists.txt file for reference. After the modification is completed, save and exit, and enter the bulid path of the project. Enter the command to compile
xxxxxxxxxx
cmake .. && nmake
Need attention This routine only provides source code. If you want to compile, please create a new project by yourself, and put the source code files into the new project.
Burning After compiling, you can generate files in formats such as .bin .hex .elf .uf2 in the build directory. Drag the u2f in the above file to the disk recognized by Pico to burn. (Note: When programming for the first time, it is an empty code. Connect Pico W to the USB to directly identify the disk. When there is an executable program in it, you need to press and hold the BOOTSEL button before connecting to the USB)
5. Experimental phenomenon
After the program is downloaded, we can hear the buzzer playing different frequencies.