关键代码如下:
main.c
#include "stm32f10x.h"
#include "usart.h"
#include "stdio.h"
#include "delay.h"
#include "string.h"
#include "pwm.h"
#include "adc.h"
int main()
{
NVIC_SetPriorityGrouping(5);//两位抢占两位次级
Usart1_Config();
SysTick_Config(72000);
RGBpwm_Config();
uint8_t cai_count=0;
uint16_t cont=0;
Adc_Config();
while(1)
{
if(ledcnt[0]>=ledcnt[1]){//过去500ms
ledcnt[0]=0;
Get_Smoke_Value();
}
}
return 0;
}
adc.c
#include "ADC.h"
//库函数
void Adc_Config(void)
{
//开时钟ADC1和PC,PA
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOC|RCC_APB2Periph_ADC1,ENABLE);
RCC_ADCCLKConfig(RCC_PCLK2_Div6);
//配置GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;//MQ2
GPIO_Init(GPIOC, &GPIO_InitStructure);
//配置ADC1
ADC_InitTypeDef ADC_InitStruct={0}; //
ADC_InitStruct.ADC_Mode = ADC_Mode_Independent;//ADC独立模式
ADC_InitStruct.ADC_DataAlign = ADC_DataAlign_Right;//数据右对齐
ADC_InitStruct.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;//选择软件SWSTART位触发
ADC_InitStruct.ADC_ContinuousConvMode = DISABLE;//连续还是单次模式
ADC_InitStruct.ADC_ScanConvMode = DISABLE;//关闭扫描
ADC_InitStruct.ADC_NbrOfChannel = 1;
ADC_Init(ADC1,&ADC_InitStruct);
ADC_Cmd(ADC1, ENABLE);
//配置通道
ADC_RegularChannelConfig(ADC1, ADC_Channel_11,1, ADC_SampleTime_239Cycles5);
//校准
ADC_ResetCalibration(ADC1);
while(ADC_GetResetCalibrationStatus(ADC1));
ADC_StartCalibration(ADC1);
while(ADC_GetCalibrationStatus(ADC1));
}
void Get_Smoke_Value()
{
uint16_t Smoke=0;
//让规则通道转换一次
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
//ADC1->CR2 |= 0x01<<22;
while(ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC) == 0)//判断寄存器的位2是不是等于1,是0就等待转换完成
{}
Smoke = ADC_GetConversionValue(ADC1); //读规则组通道数据寄存器
printf("烟雾浓度参数 = %d \r\n",Smoke);
return;
}
adc.h
#ifndef _ADC_H_
#define _ADC_H_
#include "stm32f10x.h"
#include "stdio.h"
void Get_Smoke_Value();
void Adc_Config(void);
#endif