stm32f103ADC采集电压通过dma怎么算出小频电压最大值最小值 代码
时间: 2023-09-16 16:08:05 浏览: 81
uart_string_ dm_str.zip_STM32F103_adc定时采集_worried7lc
以下是一个示例代码,用于通过DMA采集STM32F103的ADC电压,并计算最大值和最小值。
首先,需要初始化ADC和DMA模块,设置ADC的采样通道和采样速率。然后,启动DMA传输,以将ADC采样值存储到缓冲区中。最后,遍历缓冲区,计算最大值和最小值。
```c
#include "stm32f10x.h"
#define ADC1_DR_Address ((u32)0x4001244C)
u16 ADC_ConvertedValue[1000];
void ADC_DMA_Config(void)
{
DMA_InitTypeDef DMA_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
//初始化ADC1和DMA1
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 | RCC_APB2Periph_GPIOA, ENABLE);
//配置ADC1通道2对应的GPIOA.2引脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//配置DMA1通道1
DMA_DeInit(DMA1_Channel1);
DMA_InitStructure.DMA_PeripheralBaseAddr = ADC1_DR_Address;
DMA_InitStructure.DMA_MemoryBaseAddr = (u32)ADC_ConvertedValue;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize = 1000;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
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_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel1, &DMA_InitStructure);
//启动DMA1通道1
DMA_Cmd(DMA1_Channel1, ENABLE);
//初始化ADC1
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfChannel = 1;
ADC_Init(ADC1, &ADC_InitStructure);
//配置ADC1通道2
ADC_RegularChannelConfig(ADC1, ADC_Channel_2, 1, ADC_SampleTime_55Cycles5);
//启动ADC1的DMA传输
ADC_DMACmd(ADC1, ENABLE);
//启动ADC1
ADC_Cmd(ADC1, ENABLE);
//等待ADC1启动
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADRDY));
//启动ADC1的连续转换模式
ADC_StartConversion(ADC1);
}
int main(void)
{
u16 max_value = 0, min_value = 0xffff;
ADC_DMA_Config();
while (1)
{
//遍历ADC采样值缓冲区
for(int i=0; i<1000; i++)
{
if(ADC_ConvertedValue[i] > max_value)
{
max_value = ADC_ConvertedValue[i];
}
if(ADC_ConvertedValue[i] < min_value)
{
min_value = ADC_ConvertedValue[i];
}
}
//计算最大值和最小值的电压值
float max_voltage = (float)max_value / 4096 * 3.3;
float min_voltage = (float)min_value / 4096 * 3.3;
}
}
```
需要注意的是,ADC采样值缓冲区的长度应该足够大,以便准确地计算最大值和最小值。这里设置为1000个采样值。另外,根据实际应用情况,可能需要调整ADC采样速率和DMA传输速率。
阅读全文