PAM8403 Stereo Amplifier: Difference between revisions
		
		
		
		Jump to navigation
		Jump to search
		
| No edit summary | mNo edit summary | ||
| Line 76: | Line 76: | ||
| <youtube>HPQMvL1SP_c</youtube> | <youtube>HPQMvL1SP_c</youtube> | ||
| [[Category: | [[Category:Actuators]] | ||
Latest revision as of 09:31, 14 June 2024
Description
An amplifier can be used to driver bigger speakers and to generate sound that is louder.
The amplifier is connected (similar to a speaker) to the ESP32/ESP8266, it is also connected to power, and then it has connections for the speakers.
How to connect it electrically
How to control it in MicroPython
Basic code to generate a 500 Hz signal
creating a mono singnal with 500Hz on Pin 27 (connected to the left channel)
from machine import Pin
from time import sleep, sleep_us, sleep_ms 
# assume our amplifier is connected to Pin 27, we use it as output 
myLED = Pin(27, Pin.OUT)
#generate a 500Hz on/off signal
while True:
      # this switcheson for 1ms = 1000 us
      myLED.on()
      sleep_us(1000)
      # this switches off for 1 ms = 1000 us
      myLED.off()
      sleep_us(1000)Code to play a melody - decoding notes
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.
There are some issues with restarting PWM outputs - see Known Issues.
# beeper code from https://micropython-on-esp8266-workshop.readthedocs.io/en/latest/basics.html#beepers
from machine import Pin, PWM
from time import sleep
tempo = 4
#notes and corresponding frequency
tones = {
    'c': 262,
    'd': 294,
    'e': 330,
    'f': 349,
    'g': 392,
    'a': 440,
    'b': 494,
    'C': 523,
    ' ': 0,
}
pin = Pin(27, Pin.OUT)
# Init Beeper without frequency.
beeper = PWM(pin, duty=512)
melody = 'cdefggaaaagaaaagffffeeddddc'
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]
for tone, length in zip(melody, rhythm):
    beeper.freq(tones[tone])
    sleep(tempo/length)
    
beeper.deinit()Related Tutorial Videos