EasyManuals Logo

SunFounder ESP32 User Manual

Default Icon
771 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Page #348 background imageLoading...
Page #348 background image
SunFounder ESP32 Starter Kit
Open the 3.2_custom_tone.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 frequencies of several musical notes in Hz
C4 = 262
D4 = 294
E4 = 330
F4 = 349
G4 = 392
A4 = 440
B4 = 494
# Create a PWM object representing pin 14 and assign it to the buzzer variable
buzzer = machine.PWM(machine.Pin(14))
# Define a tone function that takes as input a Pin object representing the buzzer, a
˓frequency in Hz, and a duration in milliseconds
def tone(pin, frequency, duration):
pin.freq(frequency) # Set the frequency
pin.duty(512) # Set the duty cycle
time.sleep_ms(duration) # Pause for the duration in milliseconds
pin.duty(0) # Set the duty cycle to 0 to stop the tone
# Play a sequence of notes with different frequency inputs and durations
tone(buzzer, C4, 250)
time.sleep_ms(500)
tone(buzzer, D4, 250)
time.sleep_ms(500)
tone(buzzer, E4, 250)
time.sleep_ms(500)
tone(buzzer, F4, 250)
time.sleep_ms(500)
tone(buzzer, G4, 250)
time.sleep_ms(500)
tone(buzzer, A4, 250)
time.sleep_ms(500)
tone(buzzer, B4, 250)
How it works?
If the passive buzzer given a digital signal, it can only keep pushing the diaphragm without producing sound.
Therefore, we use the tone() function to generate the PWM signal to make the passive buzzer sound.
This function has three parameters:
pin: The pin that controls the buzzer.
frequency: The pitch of the buzzer is determined by the frequency, the higher the frequency, the higher the
pitch.
Duration: The duration of the tone.
342 Chapter 3. For MicroPython User

Table of Contents

Questions and Answers:

Question and Answer IconNeed help?

Do you have a question about the SunFounder ESP32 and is the answer not in the manual?

SunFounder ESP32 Specifications

General IconGeneral
BrandSunFounder
ModelESP32
CategoryController
LanguageEnglish