DAC—数模转换器
STM32的DAC使用起来非常简单,首先将连接DAC通道的GPIO引脚配置为模拟状态,然后初始化DAC,一共只有四个参数需要初始化,其中最重要的是触发源:这个参数的作用是,每来一个触发源信号,DAC就刷新一次输出,也就是将需要转换的数字量转换为电压输出,这里选择定时器2作为触发源。
代码:
void DAC_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
DAC_InitTypeDef DAC_InitStructure;
DAC_TRIGTIM_Config();//定时器配置,见第2点
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC1,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN; //模拟
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA,&GPIO_InitStructure);
DAC_InitStructure.DAC_Buffer_Switch=DAC_BufferSwitch_Disable; //增大电流的,不需要
DAC_InitStructure.DAC_Trigger=DAC_Trigger_T2_TRGO; //定时器2做触发源
DAC_InitStructure.DAC_WaveGeneration=DAC_WaveGeneration_None; //不需要
DAC_InitStructure.DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bits2_0;//这个是针对上一个参数的,所以也不重要
DAC_Init(DAC1,DAC_Channel_2,&DAC_InitStructure);
DAC_SetChannel2Data(DAC1,DAC_Align_12b_R,0);//设置一下初始值,其实也可以不用
DAC_Cmd(DAC1,DAC_Channel_2,ENABLE);
}
void DAC_TRIGTIM_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(DAC_TRIGTIM_CLK, ENABLE);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = 36000-1; //定时1ms
TIM_TimeBaseStructure.TIM_Prescaler = 2-1; //二分频,计时器频率36M
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(DAC_TRIGTIM, &TIM_TimeBaseStructure);
TIM_SelectOutputTrigger(DAC_TRIGTIM, TIM_TRGOSource_Update);//选择输出Trigger信号
TIM_Cmd(DAC_TRIGTIM, ENABLE);
做好上面两步,DAC就可以使用了,下面是使用DMA模式的配置
uint16_t OUTPUT_BUFFER[20]={1500,1800,2100,2400,2700,3000,3300,3600,3900,4095,
4095,3900,3600,3300,3000,2700,2400,2100,1800,1500};
void DAC_DMA_Config(void)
{
DMA_InitTypeDef DMA_InitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA2, ENABLE);
DMA_DeInit(DMA2_Channel4);
DMA_InitStructure.DMA_PeripheralBaseAddr = DAC_DHR12R2_ADDR;//DHR12R2寄存器的地址
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&OUTPUT_BUFFER;//内存缓冲区
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;//发向外设(DAC)
DMA_InitStructure.DMA_BufferSize = 20;//数据个数
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;//外设地址不增加
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;//增加
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;//16位
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;//循环模式
DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;//禁止
DMA_Init(DMA2_Channel4, &DMA_InitStructure);
DMA_Cmd(DMA2_Channel4, ENABLE);
DAC_DMACmd(DAC1,DAC_Channel_2,ENABLE);
}