Implementation of PWM music playback function based on STM32 timer

Publisher:EternalSunsetLatest update time:2018-03-25 Source: eefocusKeywords:STM32 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

    Based on the 32-bit STM32F103, the audio signal generated by PWM is used to drive the buzzer to play music, realizing the application design of the music player. The player can realize 21 scales from bass to treble, and can play complete music according to the score. The test results show that the output signal of PWM is basically consistent with the sound frequency corresponding to each scale, and the scheme is feasible. This method can also be used in motor control, electronic piano design and other aspects, and has good practicality.

    In the development of scientific research projects, sometimes there are situations where you need to play phone ringtones, music, etc. The simple way is to buy a dedicated music chip, but the disadvantage of this method is that the content played is immutable and cannot meet the project requirements well. Generally, 89C51 and other single-chip microcomputers can be used to realize music playback, and the content and number of songs played can be modified at any time, which is relatively convenient to use. With the emergence of the STM32 series of microprocessors, its 32-bit flash microcontroller based on the ARM Cortex-M core, up to 72 MHz main frequency, high integration, real-time, digital signal processing, low power consumption, low voltage operation and many other features make it more and more widely used. Based on the STM32 processor, this paper makes music scores for program recognition according to the music score, and uses the internal timer to generate PWM output signals to drive the buzzer to complete the playback of the custom music score. After testing, the playback effect is good.

1 Brief analysis of music scores
1.1 Scale
    The scale is an indispensable element of music, which is mainly determined by the frequency of the sound. Different scales can be generated by giving the buzzer audio pulses of different frequencies. To generate an audio pulse of a certain frequency, the simplest way is to calculate the cycle of the audio, and then divide this cycle by 2 to get the time of half a cycle. By controlling a pin of the microcontroller to be "high" and "low" for half a cycle through program control, the rectangular wave of the frequency can be generated, and the sound of the frequency can be emitted when connected to the buzzer. If you want to change the scale, you only need to change the half cycle time. Table 1 is a comparison table of note frequencies in the key of C, based on which notes of different scales can be generated. "#" represents a semitone, which is used to increase or decrease a half tone. Multiplying by 2 will increase the sound by an octave scale, and halving it will decrease it by an octave.

e.JPG

    1.2 Beat

    To compose music, it is not enough to have a scale, but also a beat, that is, the duration of a note, which is generally expressed in beats. As for how many seconds a beat is, there is no strict rule, as long as the beat is appropriate and the sound is pleasant. If the rhythm of a song is 120 beats per minute, then 1 beat is 0.5 seconds, 1/4 beat is 0.125 seconds, and so on to get the corresponding duration of other beats. In this way, using different frequencies and adding a delay corresponding to the number of beats, a piece of music is composed.

    2 Timers in STM32

    The generation of musical scales is related to the sound frequency. In order to achieve different musical scales, it is necessary to provide the buzzer with pulses of different frequencies. For this reason, the STM32 chip is selected, and its built-in timer is used to generate pulse signals through PWM. There are a total of 11 timers in the STM32, including 2 advanced control timers, 4 ordinary timers, 2 basic timers, 2 watchdog timers and 1 system tick timer SysTiek. Among them, TIM1 and TIM8 are advanced timers, and the clock is generated by the output of APB2. TIM2~TIM5 are ordinary timers, TIM6 and TIM7 are basic timers, and the clocks of these 6 timers are generated by the output of APB1.

    2.1 Calculation of timing duration

    One of the main functions of a timer is to generate an overflow event at a specified time. The setting of this time is related to the timer clock. Pre-division is performed based on the timer clock to set the count overflow size.


    2.1.1 System clock settings

    To ensure the accuracy of timing, we must first ensure that the system clock setting is what we expect. The timer clock distribution is shown in Figure 1. By programming, SYSCLK is 72 MHz, and PCLK1 is 36 MHz after APB1 pre-division, and then TIM2~TIM7 clock 72 MHz is obtained through TIM2~TIM7 multipliers. The clock source mostly uses HSE (external clock source). For STM32F103, its external clock is 8 MHz, while the external clock of STM32F107 is 25 MHz. Therefore, when using HSE as the clock source, the two devices generate different ways of dividing and multiplying SYSCLK, which requires users to pay attention.

f.JPG

    2.1.2 Timer related parameter settings

    The parameters of the timer are defined by the structure TimeBaselnitTypeDef, mainly including pre-scaling coefficient, clock division, counter mode, count overflow size, etc. For example, to generate a timer with a duration of 1 s by TIM3 (timer 3), first, the system clock should be set to get TIM3CLK=72MHz, and then the timer should be set. Among them, the pre-scaling coefficient is 35999. At this time, the TIM3 clock is 72 MHz/36000=2 kHz, and there is no clock division. Set the count overflow size to 1999, that is, an update event is generated every 2000 counts, and the output frequency is 2kHz/2000=1Hz. The code is as follows:

   g.JPG

    2.2 PWM output of STM32

    Pulse Width Modulation (PWM) is a very effective technology that uses the digital output of a microprocessor to control analog circuits. In short, it is to control the pulse width of the output signal, which is generally used to control stepper motors, etc. Except for TIM6 and TIM7, other timers of STM32 can be used to generate PWM outputs. Among them, advanced timers TIM1 and TIM8 can generate 3 pairs of PWM complementary outputs, and TIM2~TIM5 can also generate 4 PWM outputs at the same time.

    2.2.1 PWM output pins

    STM32 assigns different output pins to different timers. Considering the pin multiplexing function, STM32 also proposes a concept of "re-imaging", which is to set some related registers so that PWM waveforms can be output on other non-originally designated pins. However, this re-imaging is not arbitrary. For usage, please refer to the references. For example, when there is no re-imaging, the designated pin of channel 2 of TIM3 is PA7. If partial re-imaging is set, the output is mapped to PB5; if full re-imaging is set, the output is mapped to PC7.

    2.2.2 Calculation of Duty Cycle

    Duty Ratio has the following meaning: in an ideal pulse cycle sequence (such as a square wave), the ratio of the duration of a positive pulse to the total pulse period.

    h.JPG
    When TIM_Period is 1999, if you want to get a duty cycle of 50%, then TIM_Pulse should be set to (1999+1)/2=1000. The specific settings are as follows:
    
   j.JPG

    3 Use PWM to control the buzzer to play music

    3.1 Hardware Circuit Design

    The buzzer circuit is shown in Figure 2. It should be noted that the active buzzer works at a fixed frequency and can beep when powered on, while the passive buzzer can be controlled by input signals of different frequencies. Therefore, a passive buzzer needs to be selected. The core control device is STM32F103VET6, and its pin PB5 is connected to BEEP. It can be seen from the circuit that when PB5 is high , the buzzer can work. As long as the frequency of the rectangular wave formed by the high and low level output of PB5 is controlled, the buzzer can be controlled to play music.a.JPG

    3.2 Programming

    3.2.1 Making Music Score

    The generation of musical scale depends on the frequency of PWM output signal. To simplify the design, we set the timer TIM_Period to 1999 and the duty cycle to 50%. According to formula (1), TIM_Pulse is 1000. At this time, the PWM output signal frequency is only related to the timer pre-scaling coefficient TIM_Prescaler. You only need to adjust this coefficient to get the required signal frequency.

    TIM_Prescaler is obtained by the following formula:

    In formula (2), fsound is the frequency corresponding to the scale, such as the bass Do frequency is 262 Hz. To generate this audio, TIM_Prescaler should be 136.

    The score consists of scales and beats. Every two elements form a group. The former represents the scale and the latter represents the beat. The beat is based on 1/4 beats, and the stored values ​​are multiples of 1/4 beats. The relevant codes are as follows:

   a.JPG


    3.2.2 Main program design

    The program flow is shown in Figure 3. Since the PWM output pin of STM32 is PB5, we use channel 2 of TIM3 to generate PWM output. In the GPIO setting program, the channel 2 pin of TIM3 is partially remapped to PB5, and the GPIO mode is selected as multiplexed push-pull output. The program reads the music score in a loop, modifies the pre-division coefficient of the timer according to the scale, and resets the timer and PWM. At the same time, the internal SysTICk of STM32 is used for precise timing, and the ms-level delay is achieved according to the beat, and the core consumption is reduced. Figure 4 shows the PWM output waveform of the bass So measured by an oscilloscope. According to Table 1, the waveform frequency should be 392 Hz, and the actual measurement is 391.549 Hz. It can be seen that the PWM output error of this scheme is small.


b.JPG

c.JPG

    Conclusion

    STM32 can be used as a microcontroller or as a single- chip microcomputer. It is a processor with high cost performance. This article uses the timer of STM32 to generate PWM audio pulse waveform and realize the music playback function. This method can be used for motor control, electronic piano and electronic key design in wireless telegraphy, etc., and has high practical value.


Keywords:STM32 Reference address:Implementation of PWM music playback function based on STM32 timer

Previous article:Design of low-power speech denoising system based on ARM processor
Next article:Analysis of AT91SAM9261 Advanced Interrupt Controller

Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号