用STM32F103的ADC采样并显示的程序
时间: 2023-05-30 13:06:50 浏览: 334
以下是用STM32F103的ADC采样并显示的程序,包括初始化ADC、GPIO和定时器,以及采样和显示函数:
```c
#include "stm32f10x.h"
#define ADC1_DR_Address ((uint32_t)0x4001244C)
uint16_t ADC_Value = 0;
uint16_t ADC_Average = 0;
void ADC_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void ADC_Config(void)
{
ADC_InitTypeDef ADC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
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);
ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_239Cycles5);
ADC_Cmd(ADC1, ENABLE);
ADC_ResetCalibration(ADC1);
while(ADC_GetResetCalibrationStatus(ADC1));
ADC_StartCalibration(ADC1);
while(ADC_GetCalibrationStatus(ADC1));
ADC_Cmd(ADC1, ENABLE);
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
}
void TIM_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = 7199;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM2, ENABLE);
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
ADC_Value = ADC_GetConversionValue(ADC1);
ADC_Average = (ADC_Average + ADC_Value) / 2;
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
void LED_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void LED_ON(void)
{
GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_RESET);
}
void LED_OFF(void)
{
GPIO_WriteBit(GPIOC, GPIO_Pin_13, Bit_SET);
}
int main(void)
{
ADC_GPIO_Config();
ADC_Config();
TIM_Config();
LED_GPIO_Config();
while(1)
{
if(ADC_Average > 2048)
{
LED_ON();
}
else
{
LED_OFF();
}
}
}
```
在这个程序中,首先进行了ADC、GPIO和定时器的初始化。其中,ADC采用的是单通道、连续转换模式,并启用了软件触发转换;GPIO使用的是模拟输入模式;定时器使用的是时基模式,定时周期为100ms。在定时器中断中,读取ADC采样值并计算平均值,然后在主循环中判断平均值是否大于2048,从而控制LED的开关状态。
阅读全文