涉及到的硬件有:光敏传感器,热敏传感器,红外对射传感器,电位器
通过adc将他们采集的模拟信号转换为数值
++ad.c文件++
#include "stm32f10x.h"
#include "stm32f10x_adc.h"
#include "ad.h"
#include "stdint.h"
void ad_Init(void)
{
//开启时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//配置ADCCLK
RCC_ADCCLKConfig(RCC_PCLK2_Div6);
//配置GPIO
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_2|GPIO_Pin_3;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//结构体初始化ADC
ADC_InitTypeDef ADC_InitStruct;
ADC_InitStruct.ADC_Mode=ADC_Mode_Independent; //工作模式为独立模式
ADC_InitStruct.ADC_DataAlign=ADC_DataAlign_Right; //ADC数据为右对齐
ADC_InitStruct.ADC_ExternalTrigConv=ADC_ExternalTrigConv_None; //软件触发
ADC_InitStruct.ADC_ContinuousConvMode=DISABLE; //单次转换
ADC_InitStruct.ADC_ScanConvMode=DISABLE; //扫描模式
ADC_InitStruct.ADC_NbrOfChannel=1; //扫描模式下要用到的通道数为1
ADC_Init(ADC1,&ADC_InitStruct);
//开启ADC电源
ADC_Cmd(ADC1,ENABLE);
//复位校准
ADC_ResetCalibration(ADC1);
//等待复位校准
while(ADC_GetResetCalibrationStatus(ADC1)==SET);
//开始校准
ADC_StartCalibration(ADC1);
//等待开始校准
while(ADC_GetCalibrationStatus(ADC1));
}
//获取转换值函数
uint16_t ad_Getvalue(uint8_t ADC_Channel)
{
ADC_RegularChannelConfig(ADC1,ADC_Channel,1,ADC_SampleTime_55Cycles5);
ADC_SoftwareStartConvCmd(ADC1,ENABLE);
while(ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC)==RESET);
return ADC_GetConversionValue(ADC1);
}
++ad.h文件++
#ifndef _AD_H
#define _AD_H
#include "stdint.h"
void ad_Init(void);
uint16_t ad_Getvalue(uint8_t ADC_Channel);
#endif
++main.c文件++
#include "stm32f10x.h"
#include "stm32f10x_adc.h"
#include "delay.h"
#include "OLED.h"
#include "ad.h"
uint16_t AD0,AD1,AD2,AD3;
int main (void)
{
//初始化函数
OLED_Init();
ad_Init();
OLED_ShowString(1,1,"AD0_Value:");
OLED_ShowString(2,1,"AD1_Value:");
OLED_ShowString(3,1,"AD2_Value:");
OLED_ShowString(4,1,"AD3_Value:");
while(1)
{
AD0=ad_Getvalue(ADC_Channel_0);
AD1=ad_Getvalue(ADC_Channel_1);
AD2=ad_Getvalue(ADC_Channel_2);
AD3=ad_Getvalue(ADC_Channel_3);
OLED_ShowNum(1,11,AD0,4);
OLED_ShowNum(2,11,AD1,4);
OLED_ShowNum(3,11,AD2,4);
OLED_ShowNum(4,11,AD3,4);
delay_ms(1000);
}
}