STM32G031 HAL库 ADC多通道DMA方式
时间: 2023-10-16 08:25:15 浏览: 302
以下为STM32G031 HAL库 ADC多通道DMA方式的示例代码:
```c
/* 初始化 ADC */
ADC_HandleTypeDef hadc;
hadc.Instance = ADC1;
hadc.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
hadc.Init.Resolution = ADC_RESOLUTION_12B;
hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc.Init.ScanConvMode = ADC_SCAN_ENABLE;
hadc.Init.EOCSelection = ADC_EOC_SEQ_CONV;
hadc.Init.LowPowerAutoWait = DISABLE;
hadc.Init.ContinuousConvMode = ENABLE;
hadc.Init.NbrOfConversion = 2;
hadc.Init.DiscontinuousConvMode = DISABLE;
hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START;
if (HAL_ADC_Init(&hadc) != HAL_OK) {
Error_Handler();
}
/* 配置ADC通道 */
ADC_ChannelConfTypeDef sConfig;
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;
sConfig.SamplingTime = ADC_SAMPLETIME_640CYCLES_5;
if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
Error_Handler();
}
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;
sConfig.SamplingTime = ADC_SAMPLETIME_640CYCLES_5;
if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
Error_Handler();
}
/* 初始化DMA */
DMA_HandleTypeDef hdma_adc;
hdma_adc.Instance = DMA1_Channel1;
hdma_adc.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_adc.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_adc.Init.MemInc = DMA_MINC_ENABLE;
hdma_adc.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
hdma_adc.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
hdma_adc.Init.Mode = DMA_CIRCULAR;
hdma_adc.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_adc) != HAL_OK) {
Error_Handler();
}
/* 配置DMA通道 */
__HAL_LINKDMA(&hadc, DMA_Handle, hdma_adc);
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
/* 启动ADC */
HAL_ADC_Start_DMA(&hadc, (uint32_t *)adc_values, 2);
```
其中,`ADC1`代表ADC模块的实例;`ADC_CHANNEL_0`和`ADC_CHANNEL_1`代表需要使用的ADC通道;`DMA1_Channel1`代表DMA通道的实例;`adc_values`是一个长度为2的数组,用于存储ADC转换结果。启动ADC转换时,使用`HAL_ADC_Start_DMA`函数,将DMA传输的目的地址设为`adc_values`数组的首地址。当ADC转换完成时,DMA会将转换结果存储到`adc_values`数组中。
阅读全文