SunFounder ESP32 Starter Kit
We use the duty() function to set the duty cycle to 512(about 50%). It can be other numbers, and it only needs to
generate a discontinuous electrical signal to oscillate.
Learn More
We can simulate specific pitches and thus play a complete piece of music.
Note:
• Open the 3.2_custom_tone_music.py file located in the esp32-starter-kit-main\micropython\codes
path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.
• Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.
import machine
import time
# Define the GPIO pin that is connected to the buzzer
buzzer = machine.PWM(machine.Pin(14))
# Define the frequencies of the notes in Hz
C5 = 523
D5 = 587
E5 = 659
F5 = 698
G5 = 784
A5 = 880
B5 = 988
# Define the durations of the notes in milliseconds
quarter_note = 250
half_note = 300
whole_note = 1000
# Define the melody as a list of tuples (note, duration)
melody = [
(E5, quarter_note),
(E5, quarter_note),
(F5, quarter_note),
(G5, half_note),
(G5, quarter_note),
(F5, quarter_note),
(E5, quarter_note),
(D5, half_note),
(C5, quarter_note),
(C5, quarter_note),
(D5, quarter_note),
(E5, half_note),
(E5, quarter_note),
(D5, quarter_note),
(D5, half_note),
(E5, quarter_note),
(E5, quarter_note),
(F5, quarter_note),
(continues on next page)
3.15. 3.2 Custom Tone 343