stm32 ADC2中断采样
时间: 2023-09-09 20:13:15 浏览: 85
以下是基于STM32F4系列的ADC2中断采样的示例代码:
```
#include "stm32f4xx.h"
#define ADC2_DR_ADDRESS ((uint32_t)0x4001214C)
__IO uint16_t ADC2ConvertedValue = 0;
void ADC2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable ADC2 and GPIOC clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC2, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
/* Configure ADC2 Channel 11 pin as analog input */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* ADC2 Configuration */
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = 1;
ADC_Init(ADC2, &ADC_InitStructure);
/* ADC2 Regular Channel 11 Configuration */
ADC_RegularChannelConfig(ADC2, ADC_Channel_11, 1, ADC_SampleTime_15Cycles);
/* Enable ADC2 DMA request */
ADC_DMARequestAfterLastTransferCmd(ADC2, ENABLE);
/* Enable ADC2 interrupt */
NVIC_InitStructure.NVIC_IRQChannel = ADC_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* Enable ADC2 */
ADC_Cmd(ADC2, ENABLE);
}
void ADC_IRQHandler(void)
{
if(ADC_GetITStatus(ADC2, ADC_IT_EOC) != RESET)
{
ADC_ClearITPendingBit(ADC2, ADC_IT_EOC);
/* Get ADC2 converted value */
ADC2ConvertedValue = ADC_GetConversionValue(ADC2);
}
}
int main(void)
{
ADC2_Init();
while (1)
{
/* Start ADC2 conversion */
ADC_SoftwareStartConv(ADC2);
/* Wait until ADC2 conversion is complete */
while(ADC_GetFlagStatus(ADC2, ADC_FLAG_EOC) == RESET);
/* Do something with ADC2 converted value */
// ...
}
}
```
在该代码中,通过调用`ADC2_Init()`函数初始化ADC2。其中,ADC2的输入通道被配置为PC1,采样时间为15个时钟周期。ADC2采用中断模式,当转换完成时会触发中断。在中断处理程序中,通过调用`ADC_GetConversionValue()`函数获取ADC2转换后的值,并存储到全局变量`ADC2ConvertedValue`中。在主函数中,通过调用`ADC_SoftwareStartConv()`函数启动ADC2转换,并在转换完成后通过`ADC_GetFlagStatus()`函数等待转换完成。转换完成后,可以在主函数中对转换后的值进行处理。
阅读全文