用STM32F4库函数实现ADC连续采样,DMA双缓冲模式,DMA中断
时间: 2024-03-05 09:26:55 浏览: 135
基于stm32f4定时器触发双ADC多通道规则同步采样
4星 · 用户满意度95%
实现ADC连续采样,DMA双缓冲模式和DMA中断的步骤如下:
1. 配置ADC和DMA
```
// ADC配置
ADC_InitTypeDef ADC_InitStruct;
ADC_CommonInitTypeDef ADC_CommonInitStruct;
ADC_StructInit(&ADC_InitStruct);
ADC_CommonStructInit(&ADC_CommonInitStruct);
ADC_CommonInitStruct.ADC_DMAAccessMode = ADC_DMAAccessMode_2; // DMA双缓冲模式
ADC_CommonInit(&ADC_CommonInitStruct);
ADC_InitStruct.ADC_ContinuousConvMode = ENABLE; // 连续采样模式
ADC_InitStruct.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None; // 外部触发禁用
ADC_InitStruct.ADC_DataAlign = ADC_DataAlign_Right; // 右对齐
ADC_InitStruct.ADC_NbrOfConversion = 1; // 一次转换
ADC_Init(ADC1, &ADC_InitStruct);
// DMA配置
DMA_InitTypeDef DMA_InitStruct;
DMA_StructInit(&DMA_InitStruct);
DMA_InitStruct.DMA_Channel = DMA_Channel_0;
DMA_InitStruct.DMA_PeripheralBaseAddr = (uint32_t)&ADC1->DR;
DMA_InitStruct.DMA_Memory0BaseAddr = (uint32_t)&adc_value[0];
DMA_InitStruct.DMA_DIR = DMA_DIR_PeripheralToMemory;
DMA_InitStruct.DMA_BufferSize = 2; // 双缓冲
DMA_InitStruct.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStruct.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStruct.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStruct.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStruct.DMA_Mode = DMA_Mode_Circular;
DMA_InitStruct.DMA_Priority = DMA_Priority_High;
DMA_InitStruct.DMA_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStruct.DMA_FIFOThreshold = DMA_FIFOThreshold_HalfFull;
DMA_InitStruct.DMA_MemoryBurst = DMA_MemoryBurst_Single;
DMA_InitStruct.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
DMA_Init(DMA2_Stream0, &DMA_InitStruct);
DMA_DoubleBufferModeConfig(DMA2_Stream0, (uint32_t)&adc_value[1], DMA_Memory_0);
DMA_DoubleBufferModeCmd(DMA2_Stream0, ENABLE);
```
2. 配置ADC和DMA中断
```
NVIC_InitTypeDef NVIC_InitStruct;
// ADC中断配置
NVIC_InitStruct.NVIC_IRQChannel = ADC_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
// DMA中断配置
NVIC_InitStruct.NVIC_IRQChannel = DMA2_Stream0_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
DMA_ITConfig(DMA2_Stream0, DMA_IT_TC | DMA_IT_HT, ENABLE);
```
3. 启动ADC和DMA
```
ADC_Cmd(ADC1, ENABLE);
DMA_Cmd(DMA2_Stream0, ENABLE);
ADC_DMACmd(ADC1, ENABLE);
```
4. 编写ADC和DMA中断服务函数
```
void ADC_IRQHandler(void)
{
if (ADC_GetITStatus(ADC1, ADC_IT_EOC) == SET)
{
ADC_ClearITPendingBit(ADC1, ADC_IT_EOC);
}
}
void DMA2_Stream0_IRQHandler(void)
{
if (DMA_GetITStatus(DMA2_Stream0, DMA_IT_TCIF0) == SET)
{
DMA_ClearITPendingBit(DMA2_Stream0, DMA_IT_TCIF0);
// 处理DMA传输完成事件
}
else if (DMA_GetITStatus(DMA2_Stream0, DMA_IT_HTIF0) == SET)
{
DMA_ClearITPendingBit(DMA2_Stream0, DMA_IT_HTIF0);
// 处理DMA半传输完成事件
}
}
```
阅读全文