STM32 雙DAC DMA TIM6輸出正弦波例子
STM32F103有雙DAC通道,利用DMA實(shí)現(xiàn)2個(gè)波形輸出
#include "stm32f10x.h"
//DAC1,2初始化
void dac_init(void)
{
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN; //開啟端口A時(shí)鐘
RCC->APB1ENR |= RCC_APB1ENR_DACEN; //開啟DAC時(shí)鐘
GPIOA->CRL &= 0xff00ffff; //PA4,PA5模擬輸入
DAC->CR = DAC_CR_TEN1 | DAC_CR_TEN2; //開啟觸發(fā)使能才能設(shè)置觸發(fā)模式
//開啟DAC,關(guān)閉輸出緩存,TIM6 TRGO觸發(fā),DMA使能
DAC->CR |= DAC_CR_EN1 | DAC_CR_BOFF1 | DAC_CR_DMAEN1 |
DAC_CR_EN2 | DAC_CR_BOFF2 | DAC_CR_DMAEN2;
//必須關(guān)閉緩沖才能輸出低于0.5V電壓
}
//DMA2初始化
void dma2_init(unsigned int cpar, unsigned int cmar, unsigned int cndtr)
{
RCC->AHBENR |= RCC_AHBENR_DMA2EN; //開啟DMA2時(shí)鐘
DMA2_Channel3->CPAR = cpar; //外設(shè)地址
DMA2_Channel3->CMAR = cmar; //存儲(chǔ)器地址
DMA2_Channel3->CNDTR = cndtr; //傳輸數(shù)據(jù)量
//通道開啟,從存儲(chǔ)器讀,循環(huán),外設(shè)不自增,存儲(chǔ)器自增
//外設(shè)32位數(shù)據(jù),存儲(chǔ)器32位數(shù)據(jù),優(yōu)先級(jí)最高,非存儲(chǔ)器到存儲(chǔ)器
DMA2_Channel3->CCR = DMA_CCR3_EN | DMA_CCR3_DIR | DMA_CCR3_CIRC |
DMA_CCR3_MINC | DMA_CCR3_PSIZE_1 | DMA_CCR3_MSIZE_1 |
DMA_CCR3_PL_0 | DMA_CCR3_PL_1;
}
//TIM6初始化
void tim6_init(unsigned short arr, unsigned short psc)
{
RCC->APB1ENR |= RCC_APB1ENR_TIM6EN; //開啟TIM6時(shí)鐘
TIM6->PSC = psc; //預(yù)分頻器
TIM6->ARR = arr; //自動(dòng)重裝載
TIM6->CR2 &= 0xff8f;
TIM6->CR2 |= TIM_CR2_MMS_1; //更新事件用作TRGO
TIM6->CR1 &= 0xff70;
TIM6->CR1 |= TIM_CR1_CEN | TIM_CR1_ARPE; //使能計(jì)數(shù)器,非單脈沖模式,自動(dòng)重裝載
}
初始化RCC時(shí)鐘為72MHz,正弦波1000點(diǎn),2個(gè)波形,一個(gè)反相,一個(gè)幅度改變
for(i = 0; i < 1000; i++)
{
sw[i] = 4095 - sine_wave[i];
sw[i] <<= 16;
sw[i] += sine_wave[i] / 3;
}
dma2_init((unsigned int)&DAC->DHR12RD, (unsigned int)sw, 1000);
dac_init();
tim6_init(7200, 0);
ARR為7199,PSC為0,72M/7199/1000=10Hz波形頻率,修改預(yù)分頻和重裝載數(shù)值可以改變波形頻率
計(jì)算公式:f=fosc/n/(arr+1)/(psc+1)
f-波形頻率
n-波形點(diǎn)數(shù)
arr-定時(shí)器計(jì)數(shù),不能為0
psc-時(shí)鐘分頻系數(shù)
fosc-系統(tǒng)時(shí)鐘,一般PLL后為72MHz