|

#include <STC32G.h>
#include "intrins.h"
#include "stdio.h"
typedef unsigned charu8;
typedef unsigned intu16;
typedef unsigned longu32;
#define MAIN_Fosc 24000000UL//定义主时钟
#define Baudrate 115200L
#define TM (65536 -(MAIN_Fosc/Baudrate/4))
#define PrintUart 1
sbit PM25_LED = P1^1;
void delay_ms(unsigned int ms);
void Pm25_Get_Value();
void InitADC();
u16 GetADCResult();
//u16 Get_ADC12bitResult(u8 channel); //channel = 0~15
/******************** 串口打印函数 ********************/
void UartInit(void)
{
#if(PrintUart == 1)
SCON = (SCON & 0x3f) | 0x40;
T1x12 = 1; //定时器时钟1T模式
S1BRT = 0; //串口1选择定时器1为波特率发生器
TL1 = TM;
TH1 = TM>>8;
TR1 = 1;//定时器1开始计时
#else
S2_S = 1; //UART2 switch to: 0: P1.0 P1.1, 1: P4.6 P4.7
S2CFG |= 0x01; //使用串口2时,W1位必需设置为1,否则可能会产生不可预期的错误
S2CON = (S2CON & 0x3f) | 0x40;
T2L = TM;
T2H = TM>>8;
AUXR |= 0x14; //定时器2时钟1T模式,开始计时
#endif
}
void UartPutc(unsigned char dat)
{
#if(PrintUart == 1)
SBUF = dat;
while(TI==0);
TI = 0;
#else
S2BUF = dat;
while(S2TI == 0);
S2TI = 0; //Clear Tx flag
#endif
}
char putchar(char c)
{
UartPutc(c);
return c;
}
/**ADC初始化函数**/
void InitADC() //adc初始化
{
ADC_CONTR &= 0xF0;
ADC_CONTR |= 0x00; //设置ADC端口为P1.0
ADCTIM = 0x3f; //设置ADC内部时序
ADCCFG = 0x2f; //设置ADC时钟为系统时钟/2/16
ADC_POWER = 1; //打开ADC电源
ADC_RES = 0; //清空ADC数据
}
/**ADC采样函数**/
u16 GetADCResult()//adc开始采样
{
ADC_START=1;//启动AD转换
_nop_();
_nop_();
while (!ADC_FLAG);//查询ADC完成标志
ADC_FLAG=0;//清完成标志
return (ADC_RES<<8)|ADC_RESL;
}
void main()
{
EAXFR = 1;
CKCON = 0x00;
WTST = 0x00;
P1M0 = 0X00;P1M1 = 0X01; //设置P1.0为ADC口
UartInit();
printf("STC32G GP2Y1014 Test.\r\n");
//printf("PM2.5_value = \r\n",PM25_value);//输出PM2.5的数值
Pm25_Get_Value();
InitADC();
while(1);
{
GetADCResult();
delay_ms(1000);
}
}
void delay_ms(unsigned int ms)
{
unsigned int i;
do{
i = MAIN_Fosc / 6000;
while(--i); //6T per loop
}while(--ms);
}
/****
*******获取PM2.5值函数
*******传入值:adc通道
*******返回值:PM2.5值
*******注意:本函数需要调用adc获取函数
*****/
u16 Pm25_Get_Value()
{
u16 adc_value = 0; //adc值变量
u16 count = 0; //计数次数值变量
u16 PM25_value = 0; //PM2.5值变量
PM25_LED = 0; //PM2.5 LED灯拉低开启
delay_ms(28); //延时280us
adc_value += GetADCResult(); //获取一次adc值,并累加
delay_ms(4); //延时40us
PM25_LED = 1; //PM2.5 LED灯拉高关闭
if(++count >= 5) //获取5次adc值
{
count = 0; //计数次数清零
adc_value = adc_value / 5; //取5次平均值
PM25_value = ((adc_value/255.0)*5*0.17-0.1)*1000; //计算PM2.5值
adc_value = 0; //adc值清零
}
return PM25_value;
} |
|