用STM32F4的库函数写ADC1的DMA2
时间: 2023-09-30 12:02:53 浏览: 128
以下是使用STM32F4库函数编写ADC1的DMA2的示例代码:
```
#include "stm32f4xx.h"
#define ADC1_DR_ADDRESS ((uint32_t)0x4001204C)
void ADC_DMA_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
DMA_InitTypeDef DMA_InitStructure;
// Enable clock for ADC1, DMA2 and GPIOA
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2 | RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
// Configure PA0 as analog input
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// ADC1 configuration
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = 1;
ADC_Init(ADC1, &ADC_InitStructure);
// Configure DMA2 stream 0 for ADC1
DMA_InitStructure.DMA_Channel = DMA_Channel_0;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&ADC1->DR;
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)&ADC_Value;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
DMA_InitStructure.DMA_BufferSize = 1;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Disable;
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_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
DMA_Init(DMA2_Stream0, &DMA_InitStructure);
// Enable DMA2 stream 0
DMA_Cmd(DMA2_Stream0, ENABLE);
// Enable ADC1 DMA
ADC_DMACmd(ADC1, ENABLE);
// Enable ADC1
ADC_Cmd(ADC1, ENABLE);
// Start ADC1 conversion
ADC_SoftwareStartConv(ADC1);
}
int main(void)
{
ADC_DMA_Init();
while (1)
{
// Do something with ADC_Value
}
}
```
在上面的代码中,我们首先定义了ADC1_DR_ADDRESS常量,它的值等于ADC1数据寄存器的地址。我们还定义了ADC_DMA_Init函数,这个函数用于初始化ADC1和DMA2。在函数中,我们首先启用了ADC1、DMA2和GPIOA的时钟。然后,我们配置了PA0为模拟输入,并使用ADC_Init函数配置了ADC1。接下来,我们使用DMA_Init函数配置了DMA2流0用于ADC1,并启用了DMA2流0。最后,我们启用了ADC1 DMA和ADC1,并启动了ADC1转换。
在main函数中,我们只需调用ADC_DMA_Init函数即可初始化ADC1和DMA2。在while循环中,我们可以读取ADC_Value变量的值,并对其进行操作。需要注意的是,ADC_Value变量是uint16_t类型,因为我们使用的是12位ADC。如果你使用的是10位ADC,则需要将它改为uint16_t类型。
阅读全文