STM32數(shù)模轉(zhuǎn)換-DAC_DMA
掃描二維碼
隨時(shí)隨地手機(jī)看文章
DAC—數(shù)模轉(zhuǎn)換器
DAC即是數(shù)模轉(zhuǎn)換器,就是將數(shù)字量轉(zhuǎn)換成模擬量,原理什么的大家應(yīng)該都懂,直接跳入如何使用:
STM32的DAC使用起來非常簡單,首先將連接DAC通道的GPIO引腳配置為模擬狀態(tài),然后初始化DAC,一共只有四個(gè)參數(shù)需要初始化,其中最重要的是觸發(fā)源:這個(gè)參數(shù)的作用是,每來一個(gè)觸發(fā)源信號,DAC就刷新一次輸出,也就是將需要轉(zhuǎn)換的數(shù)字量轉(zhuǎn)換為電壓輸出,這里選擇定時(shí)器2作為觸發(fā)源。
代碼:
void DAC_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
DAC_InitTypeDef DAC_InitStructure;
DAC_TRIGTIM_Config();//定時(shí)器配置,見第2點(diǎn)
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; //定時(shí)器2做觸發(fā)源
DAC_InitStructure.DAC_WaveGeneration=DAC_WaveGeneration_None; //不需要
DAC_InitStructure.DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bits2_0;//這個(gè)是針對上一個(gè)參數(shù)的,所以也不重要
DAC_Init(DAC1,DAC_Channel_2,&DAC_InitStructure);
DAC_SetChannel2Data(DAC1,DAC_Align_12b_R,0);//設(shè)置一下初始值,其實(shí)也可以不用
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; //定時(shí)1ms
TIM_TimeBaseStructure.TIM_Prescaler = 2-1; //二分頻,計(jì)時(shí)器頻率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;//內(nèi)存緩沖區(qū)
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;//發(fā)向外設(shè)(DAC)
DMA_InitStructure.DMA_BufferSize = 20;//數(shù)據(jù)個(gè)數(shù)
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;//外設(shè)地址不增加
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;//循環(huán)模式
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);
}