STM32F103有雙DAC通道,利用DMA實現(xiàn)2個波形輸出
#include "stm32f10x.h"
//DAC1,2初始化
void dac_init(void)
{
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN; //開啟端口A時鐘
RCC->APB1ENR |= RCC_APB1ENR_DACEN; //開啟DAC時鐘
GPIOA->CRL &= 0xff00ffff; //PA4,PA5模擬輸入
DAC->CR = DAC_CR_TEN1 | DAC_CR_TEN2; //開啟觸發(fā)使能才能設置觸發(fā)模式
//開啟DAC,關閉輸出緩存,TIM6 TRGO觸發(fā),DMA使能
DAC->CR |= DAC_CR_EN1 | DAC_CR_BOFF1 | DAC_CR_DMAEN1 | \
DAC_CR_EN2 | DAC_CR_BOFF2 | DAC_CR_DMAEN2;
//必須關閉緩沖才能輸出低于0.5V電壓
}
//DMA2初始化
void dma2_init(unsigned int cpar, unsigned int cmar, unsigned int cndtr)
{
RCC->AHBENR |= RCC_AHBENR_DMA2EN; //開啟DMA2時鐘
DMA2_Channel3->CPAR = cpar; //外設地址
DMA2_Channel3->CMAR = cmar; //存儲器地址
DMA2_Channel3->CNDTR = cndtr; //傳輸數(shù)據(jù)量
//通道開啟,從存儲器讀,循環(huán),外設不自增,存儲器自增
//外設32位數(shù)據(jù),存儲器32位數(shù)據(jù),優(yōu)先級最高,非存儲器到存儲器
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時鐘
TIM6->PSC = psc; //預分頻器
TIM6->ARR = arr; //自動重裝載
TIM6->CR2 &= 0xff8f;
TIM6->CR2 |= TIM_CR2_MMS_1; //更新事件用作TRGO
TIM6->CR1 &= 0xff70;
TIM6->CR1 |= TIM_CR1_CEN | TIM_CR1_ARPE; //使能計數(shù)器,非單脈沖模式,自動重裝載
}
初始化RCC時鐘為72MHz,正弦波1000點,2個波形,一個反相,一個幅度改變
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波形頻率,修改預分頻和重裝載數(shù)值可以改變波形頻率
計算公式:f=fosc/n/(arr+1)/(psc+1)
f-波形頻率
n-波形點數(shù)
arr-定時器計數(shù),不能為0
psc-時鐘分頻系數(shù)
fosc-系統(tǒng)時鐘,一般PLL后為72MHz
上海意泓電子科技有限責任公司 版權所有 未經(jīng)授權禁止復制或鏡像
CopyRight 2020-2025 www.pendragonrpg.com All rights reserved 滬ICP備2021005866號