... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//省去無(wú)關(guān)代碼
for (Idx = 0; Idx < 64; Idx++)
{
Sine12bit[Idx] = Sine12bit[Idx]*8/10+500; ? ? ? ?//防止出現(xiàn)底部失真
}
... ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//省去無(wú)關(guān)代碼
}
為什么要這么處理呢?在講到DAC的配置時(shí)還會(huì)再提到這一點(diǎn),在這里先不做解釋。經(jīng)過(guò)處理后的正弦波數(shù)據(jù)可以直接傳送到DMA通道,等TIM2的觸發(fā)時(shí)間一到,就可以依次把數(shù)據(jù)給到DAC,轉(zhuǎn)換成正弦波輸出。筆者用DAC通道2(對(duì)應(yīng)PA5引腳)輸出波形,所以需要使能和配置DMA2通道4,DMA的配置如下:
?
#define DAC_DHR12R2_Address ? ? ?0x40007414
void DMAx_Init(void)
{
DMA_InitTypeDef DMA_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
/* DMA1 clock enable */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA2, ENABLE);
/* GPIOA Periph clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
/* DAC Periph clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE);
?
/* Once the DAC channel is enabled, the corresponding GPIO pin is automatically?
connected to the DAC converter. In order to avoid parasitic consumption,?
the GPIO pin should be configured in analog */
GPIO_InitStructure.GPIO_Pin = ?GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;//配置為模擬輸入,抗噪聲干擾
GPIO_Init(GPIOA, &GPIO_InitStructure);
?
/* DMA1 channel4 configuration */
DMA_DeInit(DMA2_Channel4);
DMA_InitStructure.DMA_PeripheralBaseAddr = DAC_DHR12R2_Address;//DAC通道2的12位右對(duì)齊寄存器地址
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&Sine12bit;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = 64;//采樣64點(diǎn),故緩存大小為64
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(DMA2_Channel4,&DMA_InitStructure);
DMA_Cmd(DMA2_Channel4, ENABLE);
}
TIM2和DAC的配置如下:
void TIM2_DAC_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef ?TIM_TimeBaseStructure;
DAC_InitTypeDef DAC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);?
TIM_TimeBaseStructure.TIM_Period = arr; ? ? ? ? ?
TIM_TimeBaseStructure.TIM_Prescaler = psc; ? ? ??
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0; ? ?
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Down; ?//設(shè)為向下計(jì)數(shù)
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_SelectOutputTrigger(TIM2, TIM_TRGOSource_Update);
DAC_InitStructure.DAC_Trigger = DAC_Trigger_T2_TRGO;
DAC_InitStructure.DAC_WaveGeneration = DAC_WaveGeneration_None;
DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Enable; ?//使能輸出緩存
DAC_Init(DAC_Channel_2, &DAC_InitStructure);
DAC_Cmd(DAC_Channel_2, ENABLE);
DAC_DMACmd(DAC_Channel_2, ENABLE);? ? ? ??
TIM_Cmd(TIM2, ENABLE); ? ? ? ?
}
評(píng)論
查看更多