This application note gives examples for generating audio output signals using the Digital to
Analog Converter (DAC) peripheral embedded in the STM32F0xx microcontroller family.
A digital to analog converter, DAC, is a device that has the opposite function to an analog to
digital converter, it converts a digital word to a corresponding analog voltage.
The STM32 DAC module is a 12-bit word converter, with one output channel for supporting
mono audio.
The DAC can be used in many audio applications such as: security alarms, Bluetooth
headsets, talking toys, answering machines, man-machine interfaces, and low-cost music
players.
STM32 DAC can also be used for many other analog purposes, such as analog waveform
generation and control engineering.
The application note is organized in two main sections:
●Section 1 describes the main features of the STM32 DAC module.
●Section 2 presents two examples.
–In the first example, DAC is used to generate a sine wavefom.
–In the second example, the DAC is used to generate audio from .WAV files.
Figure 12.CPU and DMA activities during wave playing process . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
4/18Doc ID 022846 Rev 1
AN4058DAC main features
ai18300
1 DAC main features
1.1 Data format
The DAC accepts data in 3 integer formats: 8-bit, 12-bit right aligned and 12-bit left aligned.
A 12-bit value can range from 0x000 to 0xFFF, with 0x000 being the lowest and 0xFFF
being the highest value.
Figure 1.DAC data format
1.2 Dedicated timers
In addition to the software and External triggers, the DAC conversion can be triggered by
different timers.
TIM6 is a basic timer and is basically designed for DAC triggering.
Each time a DAC interface detects a rising edge on the selected Timer Trigger Output
(TIMx_TRGO), the last data stored in the DAC_DHRx register is transferred to the
DAC_DORx register.
Figure 2.STM32F0xx DAC trigger channel
external trigger
SWTRIGx
TIM6_TRGO
TIM3_TRGO
TIM15_TRGO
TIM2_TRGO
TSELx[2:0] bits
DAC Channel 1 Trigger
Trigger selector x
MS30315V1
Doc ID 022846 Rev 15/18
DAC main featuresAN4058
MS30316V1
DAC
RAM
(Pattern Table 1)
(Pattern Table 2)
Channel 1
Output
DAC Triggers
CPU
1.3 DMA capabilities
The STM32 microcontrollers have a DMA module with multiple channels. The DAC channel
is connected to an independent DMA channel. In the case of STM32F0xx Microcontrollers,
the DAC channel is connected to the DMA channel 3.
When DMA is not utilized, the CPU is used to provide DAC with the pattern waveform.
Generally the waveform is saved in a memory (RAM), and the CPU is in charge of
transferring the data from RAM to the DAC.
Figure 3.DAC interaction without DMA
When using the DMA, the overall performance of the system is increased by freeing up the
core. This is because data is moved from memory to DAC by DMA, without needing any
actions by the CPU. This keeps CPU resources free for other operations.
6/18Doc ID 022846 Rev 1
AN4058DAC main features
Figure 4.DAC interaction with DMA
CPU
1.4 DMA underrun error
When the DMA is used to provide DAC with the pattern waveform, there are some cases
where the DMA transfer is faster than the DAC conversion. In this case, DAC detects that a
part of the pattern waveform has been ignored and was not converted. It then sets the "DMA
underrun Error" flag.
DAC Triggers
RAM
(Pattern Table 1)
(Pattern Table 2)
DAC
Channel 1
Output
DMA
MS30317V1
The underrun error can be handled using a shared IRQ channel with the triggering Timer or
by a dedicated interrupt when DAC is not triggered by TIM6.
1.5 Buffered output
To drive external loads without using an external operational amplifier, the DAC channel has
an embedded output buffer which can be enabled and disabled depending on the user
application.
When the DAC output is not buffered, and there is a load in the user application circuit, the
voltage output will be lower than the desired voltage. Enabling the buffer, the voltage output
and the voltage desired are similar.
Doc ID 022846 Rev 17/18
DAC main featuresAN4058
ai18309
DAC
DAC_Channel_1
DOR = 0xFFF
DAC
DAC_Channel_1
DOR = 0xFFF
3.3V
R = 5.1K
GND
1.2 V1.2 V
3.3 V
3.3 V3.3 V
ai18310
DAC
DAC_Channel_1
DOR = 0xFFF
DAC
DAC_Channel_1
DOR = 0xFFF
3.3V
R = 5.1K
GND
3.3 V3.3 V
3.3 V
3.3 V3.3 V
Figure 5.Non buffered channel voltage (with and without load)
Figure 6.Buffered channel voltage (with and without load)
8/18Doc ID 022846 Rev 1
AN4058Application examples
ai18311
0
1000
2000
3000
4000
5000
0
2468
1
3579
y
SineDigital
0
0.805
1.611
2.147
3.223
4.029
y
SineAnalog
(Volt)
y
SineDigital
xx
2
n
s
------
1+
sin
0xFFF 1+
2
-------------------------------- -
=
2 Application examples
2.1 Using the DAC to generate a sine waveform
2.1.1 Description
This example describes step by step how to generate a sine waveform.
A sine waveform is also called a sine tone with a single frequency, it is known as a pure tone
or sinus tone. The sine tones are traditionally used as stimuli in determining the various
responses of the auditory system.
2.1.2 Digital Sine waveform pattern preparation
To prepare the digital pattern of the waveform, we have to do some mathematics. Our
objective is to have 10 digital pattern data (samples) of a sine wave form which varies from 0
to 2*PI.
Figure 7.Sine wave model samples
The sampling step is (2*PI)/ n
The result value of sin(x) is between -1 and 1, we have to recalibrate it to have a positive
sinewave with samples varying between 0 and 0xFFF (which corresponds to the range from
0 V to 3.3 V).
For right-aligned 8-bit resolution: DAC_MaxDigitalValue = 0xFF
So the analog sine waveform y
Table 1.Digital and analog sample values of the Sine wave
Sample
(x)
SineAnalog
Digital Sample Value
y
SineDigital
can be determined by the following equation:
Analog Sample Value (Volt)
(x)
y
020481.650
132512.620
239953.219
339963.220
432532.622
520511.653
68470.682
71010.081
8980.079
SineAnalog
(x)
98390.676
The table is saved in the memory and transferred by the DMA, the transfer is triggered by
the same timer that triggers the DAC.
10/18Doc ID 022846 Rev 1
AN4058Application examples
f
Sinewave
f
TimerTRGO
n
s
----------------------------- -=
ai18312
0
1
2
3
4
y
SineAnalog
(Volt)
time
ai18313
0
1000
2000
3000
4000
5000
0 51102153204
y
SineDigital
0
0.805
1.611
2.147
3.223
4.029
y
SineAnalog
(Volt)
255
time
2.1.3 Fixing the sine wave frequency
To fix the frequency of the sinewave signal, you have to set the frequency of the Timer
Trigger output.
The frequency of the produced sine wave is:
So, if TIMx_TRGO is 1 MHz, the frequency of the DAC sine wave is 10 kHz.
Note:To have a high quality sinewave curve, it is recommended to use a high number of samples
n
.
s
Figure 8.Sine wave generated with ns = 10
Figure 9.Sine wave generated with ns = 255
Doc ID 022846 Rev 111/18
Application examplesAN4058
TIM6
DAC
DMA
CPU
SPI
RAM
.WAV
2.2 Using the DAC to implement an audio wave player
2.2.1 Description
The purpose of this application demo is to provide an audio player solution for the STM32
microcontroller for playing .WAV files. The approach is optimized to use a minimum number
of external components, and offers the flexibility for end-users to use their own .WAV files.
The audio files are provided to the STM32 from a MicroSD memory card.
Figure 10. Flow of data from MicroSD Flash memory to external speakers
The audio wave player demonstration described in this section is a part of the
STM320518-EVAL demonstration firmware. You can download this firmware and the
associated user manual (UM1520) from the STMicroelectronics website www.st.com.
12/18Doc ID 022846 Rev 1
AN4058Application examples
2.2.2 Audio wave file specifications
This application assumes that the .WAV file to be played has the following format:
●Audio Format: PCM (an uncompressed wave data format in which each value
represents the amplitude of the signal at the time of sampling)
●Sample rate: may be 8000, 11025, 22050 or 44100 Hz
●Bits Per Sample: 8-bit (Audio sample data values are in the range [0-255] )
●Number of Channels: 1 (Mono)
2.2.3 .WAV file format
The .WAV file format is a subset of the Resource Interchange File Format (RIFF)
specification used for the storage of multimedia files. A RIFF file starts with a file header
followed by a sequence of data chunks. A .WAV file is often just a RIFF file with a single
"WAVE" chunk consisting of two sub-chunks:
1.a fmt chunk specifying the data format
2. a data chunk containing the actual sample data
The WAVE file format starts with the RIFF header: it indicates the file length.
Next, the fmt chunk describes the sample format, it contains information about: Format of
the wave audio : (PCM/...), Number of channels (mono/stereo), sample rate (number of
samples per seconds : e.g., 22050), and the sample Data size (e.g. 8bit/16bit). Finally, the
data chunk contains the sample data.
2.3 Audio wave player implementation
The Audio wave player application is based on the SPI, DMA, TIM6, and DAC peripherals.
At start up, the application first uses the SPI to interface with the MicroSD card and parses
its content, using the FatFs file system, looking for available .wav files in the USER folder.
Once a valid .wav file is found, it is read back though the SPI, and the data is transferred
using the CPU to a buffer array located in the RAM. The DMA is used to transfer data from
RAM to the DAC peripheral. TIM6 is used to trigger the DAC which will convert the Audio
digital data to an analog waveform.
Before the audio data can be played, the header of the WAV file is parsed so that the
sampling rate of the data and its length can be determined.
The task of reproducing audio is achieved by using sampled data (data contained in the
.WAV file) to update the value of the DAC output, this data is coded in 8 bits (with values
from 0 to 255),
The DAC Channel 1 is triggered by TIM6 at regular intervals specified by the sample rate of
the .WAV file header.
The .WAV files are read from the MicroSD Memory using a DosFS file system.
In the Demo code, code files handling the waveplayer demo are:
waveplayer.c
waveplayer.h
The wave player demo is called using the WavePlayerMenu_Start() function which has
the following flowchart.
Doc ID 022846 Rev 113/18
Application examplesAN4058
ai18315
Enable DMA,TIM6,DAC clocks
WavePlayer_menuStart
()
Config DAC channel 1 to be triggered
by TIM6 TRGO
Config DMA ch3 to transfer 512 bytes
from wavBuffer1 to DAC ch1 8bit
DHR register
Enable DAC channel 1 and DMA
connection
Enable DAC channel 1 output
Parse the .wav file to Check if it is a
Valid file and Get all needed
information from the .wav header.
Display Error
if .wav file status OK
Connect TIM6 TRGO to its update
event
Enable TIM6
(start the Transfer from RAM to DAC)
Enable DMA channel3
Configure the TIM6 frequency to have
the correct .wav sample rate
Initialize WaveDataLength with .wav
file audible data size
if WaveDataLength!= 0
Read
512 next bytes from the .wav file
and Save them in wavBuffer2
(*)
If DMA transfer from
wavBuffer1
to
DAC ch1 is completed
(*)
Clear DMA channel3 flag
Decrement the WaveDataLength by 512
and if WaveDataLength < 512 then
WaveDataLength = 0
Disable DMA , Config DMA to transfer 512
bytes from wavBuffer2 to DAC ch1 8bit
DHR register, and enable DMA
Read
512 next bytes from the .wav file
and Save them in wavBuffer1
(*)
If DMA transfer from
wavBuffer2
to
DAC ch1 is completed
(*)
Decrement the WaveDataLength by 512
and if WaveDataLength < 512 then
WaveDataLength = 0
Clear DMA channel3 flag
Disable DMA, Configure DMA transfer 512
bytes from wavBuffer1 to DAC ch1 8bit
DHR register, and Enable DMA
Disable DMA
Exit
Yes
Yes
Yes
No
No
No
Figure 11. Wave Player flowchart
(*) when DMA is transferring data from one RAM buffer, CPU is transferring data from the
MicroSD Flash memory to the other RAM buffer.
Decrement the WaveDataLength
counter and DMA reconfi guration
In this application, coprocessing is mandatory to permit a simultaneous Wave read (from the
external memory source) and write (in the DAC register).
Figure 12. CPU and DMA activities during wave playing process
Doc ID 022846 Rev 115/18
ConclusionAN4058
3 Conclusion
The first part of this application note and both examples given in Section 2 of this document
have been provided to help you get familiar with the DAC’s main features. The first example
(in Section 2.1) shows how to generate an analog waveform, using the example of a sine
waveform.
The second example (in Section 2.2) offers a straightforward and flexible solution for using
the STM32, to play .WAV files, stored in an SPI MicroSD Flash memory.
You can use these examples as starting points for developing your own solution using the
STM32 DAC.
16/18Doc ID 022846 Rev 1
AN4058Revision history
4 Revision history
Table 2.Document revision history
DateRevisionChanges
02-May-20121Initial release
Doc ID 022846 Rev 117/18
AN4058
Please Read Carefully:
Information in this document is provided solely in connection with ST products. STMicroelectronics NV and its subsidiaries (“ST”) reserve the
right to make changes, corrections, modifications or improvements, to this document, and the products and services described herein at any
time, without notice.
All ST products are sold pursuant to ST’s terms and conditions of sale.
Purchasers are solely responsible for the choice, selection and use of the ST products and services described herein, and ST assumes no
liability whatsoever relating to the choice, selection or use of the ST products and services described herein.
No license, express or implied, by estoppel or otherwise, to any intellectual property rights is granted under this document. If any part of this
document refers to any third party products or services it shall not be deemed a license grant by ST for the use of such third party products
or services, or any intellectual property contained therein or considered as a warranty covering the use in any manner whatsoever of such
third party products or services or any intellectual property contained therein.
UNLESS OTHERWISE SET FORTH IN ST’S TERMS AND CONDITIONS OF SALE ST DISCLAIMS ANY EXPRESS OR IMPLIED
WARRANTY WITH RESPECT TO THE USE AND/OR SALE OF ST PRODUCTS INCLUDING WITHOUT LIMITATION IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE (AND THEIR EQUIVALENTS UNDER THE LAWS
OF ANY JURISDICTION), OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.
UNLESS EXPRESSLY APPROVED IN WRITING BY TWO AUTHORIZED ST REPRESENTATIVES, ST PRODUCTS ARE NOT
RECOMMENDED, AUTHORIZED OR WARRANTED FOR USE IN MILITARY, AIR CRAFT, SPACE, LIFE SAVING, OR LIFE SUSTAINING
APPLICATIONS, NOR IN PRODUCTS OR SYSTEMS WHERE FAILURE OR MALFUNCTION MAY RESULT IN PERSONAL INJURY,
DEATH, OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE. ST PRODUCTS WHICH ARE NOT SPECIFIED AS "AUTOMOTIVE
GRADE" MAY ONLY BE USED IN AUTOMOTIVE APPLICATIONS AT USER’S OWN RISK.
Resale of ST products with provisions different from the statements and/or technical features set forth in this document shall immediately void
any warranty granted by ST for the ST product or service described herein and shall not create or extend in any manner whatsoever, any
liability of ST.
ST and the ST logo are trademarks or registered trademarks of ST in various countries.
Information in this document supersedes and replaces all information previously supplied.
The ST logo is a registered trademark of STMicroelectronics. All other names are the property of their respective owners.