stm32f103输出正弦波
时间: 2023-08-24 21:08:11 浏览: 69
要在STM32F103上输出正弦波,你需要使用DAC模块和一个正弦波表。以下是一个基本的代码框架:
```c
#include "stm32f10x.h"
#define DAC_DHR12R1_ADDRESS 0x40007408
const uint16_t sinewave[256] = {128,131,134,137,140,143,146,149,152,155,158,161,165,168,171,174,
177,180,183,186,189,192,195,198,201,204,207,210,213,216,218,221,224,227,230,232,235,238,240,243,
245,248,250,252,255,257,259,261,263,265,267,269,271,273,274,276,278,279,281,282,283,285,286,287,
288,289,290,291,292,293,293,294,294,295,295,295,295,295,295,295,295,295,295,295,294,294,293,293,292,
291,290,289,288,287,286,285,283,282,281,279,278,276,274,273,271,269,267,265,263,261,259,257,255,
252,250,248,245,243,240,238,235,232,230,227,224,221,218,216,213,210,207,204,201,198,195,192,189,
186,183,180,177,174,171,168,165,161,158,155,152,149,146,143,140,137,134,131,128,125,122,119,116,
113,110,107,104,101,98,95,91,88,85,82,79,76,73,70,67,64,61,58,55,52,49,46,43,40,37,35,32,29,26,23,
20,17,14,11,8,5,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,29,30,31,31,32,33,33,34,34,35,35,36,36,36,37,37,37,37,37,37,37,37,37,37,37,
36,36,36,35,35,34,34,33,33,32,31,31,30,29,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,
8,7,6,5,4,3,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int main(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
DAC_InitTypeDef DAC_InitStructure;
DMA_InitTypeDef DMA_InitStructure;
/* 初始化DAC通道1 */
DAC_InitStructure.DAC_Trigger = DAC_Trigger_None;
DAC_InitStructure.DAC_WaveGeneration = DAC_WaveGeneration_None;
DAC_InitStructure.DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bit0;
DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Enable;
DAC_Init(DAC_Channel_1, &DAC_InitStructure);
/* 使能DAC通道1 */
DAC_Cmd(DAC_Channel_1, ENABLE);
/* 初始化DMA */
DMA_DeInit(DMA1_Channel3);
DMA_InitStructure.DMA_PeripheralBaseAddr = DAC_DHR12R1_ADDRESS;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)sinewave;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = 256;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel3, &DMA_InitStructure);
/* 使能DMA */
DMA_Cmd(DMA1_Channel3, ENABLE);
while (1)
{
}
}
```
在上面的代码中,我们使用了DAC和DMA模块。DAC模块用于将数字信号转换成模拟信号,而DMA模块用于将正弦波表中的数据传输到DAC缓存寄存器中。在主循环中,我们不需要做任何事情,因为DMA模块已经在后台运行。
需要注意的是,DAC模块和DMA模块的初始化参数可能会因具体的芯片型号而有所不同。因此,在实际编程时,你需要查阅芯片的数据手册来获得正确的参数。
阅读全文