The common timer of stm32 has four outputs: timx_timer, timx_ch2, timx_ch3, and timx_c4. you can use the output comparison method to generate the square wave output of different frequencies. The simple method is as follows:
1) set the counter to the up counting mode, and set the automatic reload register to 0 xFFFF. This way, the counter will be counted cyclically.
2) set each timer channel to the output comparison mode, and set the output pin to flip the output when the comparison matches.
3) calculate a value named half_cyc according to the half-wave cycle of the output waveform. For example, if the timer clock frequency is 72 MHz and a square wave of 3456hz needs to be generated, half_cyc = 72 m/(3456*2) = 41667; if a square wave of kHz needs to be generated, then half_cyc = 72 m/(200 K * 2) = 180.
4) set each channel to interrupt when the output comparison matches. In the interrupt, read the value of the comparison register and add the value of half_cyc, if the calculated value exceeds 16 bits, the excess part will be discarded, and the new value will be written back to the corresponding comparison register. In this way, the next comparison will happen just after a half-wave period, the corresponding PIN is flipped.
The above method is very effective when the frequency is not high, but if frequent interruptions occur when the frequency is high, DMA can be used to improve it.
The basis of the above method is to constantly change the matching points of the output comparison to generate the pin flip output. We can calculate these matching points in advance, in addition, the content of the comparison register is updated one by one during each matching through DMA:
Method 1: Two DMA buffers are used. When the DMA controller operates on one buffer zone, the program calculates the data in the other buffer zone, and then switches the buffer zone of the DMA Operation during the interrupt processing after the DMA transmission ends.
Method 2: Use a large DMA buffer, calculate the content of the half buffer, start the DMA as a loop mode, and set it to interrupt when the DMA transfer is half done and completed; after the DMA is started, the content of the other half of the buffer is calculated. When a DMA interrupt occurs, the half of the buffer zone becomes empty. In this case, the half of the buffer zone is calculated in the interrupt processing.
As long as the DMA buffer is large enough, method 2 ensures that the CPU has sufficient time for data processing and continuously outputs waveforms.