stm32f103c8t6 adc采样电压程序标准库
时间: 2023-09-03 08:05:30 浏览: 125
STM32F103C8T6开发板实验例程:ADC实验程序源代码.rar
以下是使用标准库进行ADC采样的示例代码:
```c
#include "stm32f10x.h"
#include <stdio.h>
#define ADC1_DR_Address ((uint32_t)0x4001244C) // ADC1数据寄存器地址
void ADC1_Init(void)
{
ADC_InitTypeDef ADC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
DMA_InitTypeDef DMA_InitStructure;
RCC_ADCCLKConfig(RCC_PCLK2_Div6); // ADC时钟频率为72MHz/6=12MHz
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1 | RCC_AHBPeriph_GPIOA, ENABLE); // 使能DMA1和GPIOA时钟
// PA1作为ADC通道1的输入引脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// ADC1配置
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
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通道1配置
ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_239Cycles5);
// DMA1配置
DMA_DeInit(DMA1_Channel1);
DMA_InitStructure.DMA_PeripheralBaseAddr = ADC1_DR_Address;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&ADCValue;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
DMA_InitStructure.DMA_BufferSize = 1;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Disable;
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);
// 使能ADC/DMA
ADC_DMACmd(ADC1, ENABLE);
ADC_Cmd(ADC1, ENABLE);
DMA_Cmd(DMA1_Channel1, ENABLE);
// ADC校准
ADC_ResetCalibration(ADC1);
while (ADC_GetResetCalibrationStatus(ADC1));
ADC_StartCalibration(ADC1);
while (ADC_GetCalibrationStatus(ADC1));
}
int main(void)
{
uint16_t ADCValue = 0;
ADC1_Init();
while (1)
{
ADC_SoftwareStartConvCmd(ADC1, ENABLE); // 启动ADC转换
while (!DMA_GetFlagStatus(DMA1_FLAG_TC1)); // 等待DMA传输完成
DMA_ClearFlag(DMA1_FLAG_TC1); // 清除DMA传输完成标志位
ADCValue = ADC_GetConversionValue(ADC1); // 读取ADC值
printf("ADC Value: %d\n", ADCValue);
}
}
```
注意,在上面的代码中,`ADCValue`是一个`uint16_t`类型的变量,用于存储ADC转换结果。此外,还需要在工程中添加`stdio.h`头文件,以便使用`printf()`函数输出调试信息。
阅读全文