3 ms·
This simple code produces a square wave which can sound ok when fed through a buzzer which has a string resonant frequency. The harmonics are attenuated enough
by barbegal 5y ago
This simple code produces a square wave which can sound ok when fed through a buzzer which has a string resonant frequency. The harmonics are attenuated enough that it sounds ok playing notes close to the resonant frequency. For anything else you'll want a separate DAC (digital to analog converter) which can use I2C, I2S or SPI digital signals and outputs an analogue signal.
You can also use a scheme a little bit like PWM called PCM where the GPIO pin can be switched on and off at a frequency much higher than audio (typically 2Mhz or higher) and the duty cycle is varied at the sample rate. This can be implemented on an Arduino using code like https://github.com/damellis/PCM/blob/master/PCM.c https://github.com/damellis/PCM/blob/master/PCM.c
- colanderman 5y agoNote also that one of the main benefits of a dedicated DAC is that many implement digital oversampling: they use a high-quality digital antialiasing filter to upsample the audio to the 100 kHz-1 MHz range, so that a simpler (= cheaper) analog antialiasing filter can be used on the output.