Difference between revisions of "Piezo Speaker"
Jump to navigation
Jump to search
Line 1: | Line 1: | ||
+ | = Description = | ||
+ | A Piezo-Speaker has two connectors and can generate sounds if you apply a frequency. One is + and one is -. If you connect it to the ESP + is connected to the Pin and - to GND. | ||
+ | [[file:Piezo_Speaker_close_up.jpg|300px]] | ||
+ | |||
+ | = How to connect it electrically = | ||
+ | [[File:Piezzo.PNG]] | ||
+ | |||
+ | |||
= How to control it in MicroPython = | = How to control it in MicroPython = | ||
Example code shows how you can play a melody with the speaker. If you want to add higher notes see https://en.wikipedia.org/wiki/Piano_key_frequencies for the needed frequency. The example code was taken and edited from https://micropython-on-esp8266-workshop.readthedocs.io/en/latest/basics.html#beepers. | Example code shows how you can play a melody with the speaker. If you want to add higher notes see https://en.wikipedia.org/wiki/Piano_key_frequencies for the needed frequency. The example code was taken and edited from https://micropython-on-esp8266-workshop.readthedocs.io/en/latest/basics.html#beepers. |
Revision as of 16:09, 20 August 2020
Description
A Piezo-Speaker has two connectors and can generate sounds if you apply a frequency. One is + and one is -. If you connect it to the ESP + is connected to the Pin and - to GND.
How to connect it electrically
How to control it in MicroPython
Example code shows how you can play a melody with the speaker. If you want to add higher notes see https://en.wikipedia.org/wiki/Piano_key_frequencies for the needed frequency. The example code was taken and edited from https://micropython-on-esp8266-workshop.readthedocs.io/en/latest/basics.html#beepers.
1 # beeper code from https://micropython-on-esp8266-workshop.readthedocs.io/en/latest/basics.html#beepers
2 from machine import Pin, PWM
3 from time import sleep
4
5 tempo = 4
6 #notes and corresponding frequency
7 tones = {
8 'c': 262,
9 'd': 294,
10 'e': 330,
11 'f': 349,
12 'g': 392,
13 'a': 440,
14 'b': 494,
15 'C': 523,
16 ' ': 0,
17 }
18 pin = Pin(27, Pin.OUT)
19 # Init Beeper without frequency.
20 beeper = PWM(pin, duty=512)
21 melody = 'cdefggaaaagaaaagffffeeddddc'
22 rhythm = [8, 8, 8, 8, 4, 4, 8, 8, 8, 8, 4, 8, 8, 8, 8, 4, 8, 8, 8, 8, 4, 4, 8, 8, 8, 8, 4]
23
24 for tone, length in zip(melody, rhythm):
25 beeper.freq(tones[tone])
26 sleep(tempo/length)
27
28 beeper.deinit()