[mw_shl_code=c,true].c文件
#include "sys.h"
#include "delay.h"
#include "gp2y.h"
void GP2Y_Init(void)
{
RCC->APB2ENR|=1<<4;//使能PC口
GPIOC->CRL&=0XFFFFFFF0;//pc0作为输入引脚
RCC->APB2ENR|=1<<9;//使能ADC1通道时钟
RCC->APB2RSTR|=1<<9;//ADC1复位
RCC->APB2RSTR&=~(1<<10);//复位结束
RCC->CFGR&=~(3<<14); //分频因子清零
RCC->CFGR|=2<<14;//设置ADC分频因子6 72M/6=12,ADC最大时间不能超过14M
RCC->APB2RSTR|=1<<9; //复位ADC1
ADC1->CR1&=0XF0FFFF; //工作模式清零
ADC1->CR1|=0<<16;//独立工作模式
ADC1->CR1|=0<<13;//模数转换工作在单通道模式
ADC1->CR1&=~(1<<8); //非扫描模式
ADC1->CR2&=~(1<<1); //单次转换模式
ADC1->CR2&=~(7<<17);
ADC1->CR2|=7<<17; //软件控制转换
ADC1->CR2&=~(1<<11); //右对齐
ADC1->SQR1&=~(0XF<<20);
ADC1->SQR1|=0<<20;
ADC1->SMPR2&=~(7<<3); //通道1采样时间清空
ADC1->SMPR2|=7<<3; //通道1 239.5周期,提高采样时间可以提高精确度
ADC1->CR2|=1<<0; //开启AD转换器
RCC->APB2ENR|=1<<9; //ADC1时钟使能
RCC->APB2RSTR|=1<<9; //ADC1复位
while(ADC1->CR2&1<<3); //等待校准结束
ADC1->CR2|=1<<2; //开启AD校准
while(ADC1->CR2&1<<2); //等待校准结束
RCC->APB2ENR|=1<<4;//使能PC口
GPIOC->CRL&=0XFFFFFF3F;//pc1作为输入引脚
GPIOC->CRL|=0X000000F0;
}
u16 Get_GP2Y(u8 ch)
{
u16 Vo;
GP2Y_IO_OUT();
GP2Y_DQ_OUT=0;
delay_us(280);
Vo=Get_Adc_Average(ch,10);
delay_us(40);
GP2Y_DQ_OUT=1;
delay_us(9680);
return Vo;
}
.h文件
#ifndef __GP2Y_H
#define __GP2Y_H
#include "sys.h"
#define GP2Y_IO_IN(){GPIOC->CRL&=0XFFFFFF0F;GPIOC->CRL|=8<<4;GPIOC->CRL&=0XFFFFFF0F;GPIOC->CRL|=3<<4;}
#define GP2Y_IO_OUT(){GPIOC->CRL&=0XFFFFFF0F;GPIOC->CRL|=3<<4;GPIOC->CRL&=0XFFFFFF0F;GPIOC->CRL|=8<<4;}
#define GP2Y_DQ_OUT PCout(0) //
#define GP2Y_DQ_IN PCin(0)
u16 Get_Adc_Average(u8 ch,u8 times);
void GP2Y_Init(void);
u16 Get_GP2Y(u8 ch);
#endif
main函数部分
#include "sys.h"
#include "usart.h"
#include "delay.h"
#include "led.h"
#include "lcd.h"
#include "adc.h"
#include "gp2y.h"
#include "adc.h"
int main()
{
u16 dustVal;
float temp,ppm=0,ppmpercf=0,dustdensity=0;
Stm32_Clock_Init(9); //系统时钟设置
uart_init(72,9600); //串口初始化为9600
delay_init(72); //延时初始化
LED_Init(); //初始化与LED连接的硬件接口
LCD_Init(); //初始化LCD
Adc_Init();
GP2Y_Init(); //ADC初始化
POINT_COLOR=RED;//设置字体为红 {MOD}
LCD_ShowString(60,50,200,16,16,"Mini STM32");
LCD_ShowString(60,70,200,16,16,"fenchen TEST");
LCD_ShowString(60,90,200,16,16,"ATOM@ALIENTEK");
LCD_ShowString(60,110,200,16,16,"2015/10/20");
//显示提示信息
POINT_COLOR=BLUE;//设置字体为蓝 {MOD}
LCD_ShowString(60,130,200,16,16,"ADC: V");
LCD_ShowString(60,150,200,16,16,"DIANYA: V");
LCD_ShowString(60,170,200,16,16,"fenchenzhishu: ");
while(1)
{
dustVal=Get_Adc_Average(ADC_CH1,10);//通道10的值
LCD_ShowxNum(132,130,dustVal,4,16,0);//显示ADC的值
ppm+=dustVal;
temp=(float)dustVal*(3.3/4096);
ppm=temp;//保存电压值
LCD_ShowxNum(148,150,ppm,3,16,0X80);//显示电压值
dustdensity=0.17*ppm-0.1;
ppmpercf = (ppm-0.0256)*120000;
if (ppmpercf < 0)
{ppmpercf = 0;}
if (dustdensity < 0 )
{dustdensity = 0;}
if (dustdensity > 0.5)
{dustdensity = 0.5;}
LCD_ShowxNum(140,170,dustdensity,3,16,0);//显示灰尘指数
LCD_ShowxNum(164,170,ppmpercf,3,16,0X80);
LED0=!LED0;
delay_ms(250);
}
}
[/mw_shl_code]
一周热门 更多>