DFRobot商城里面卖的PM2.5激光粉尘传感器:
商品地址: https://www.dfrobot.com.cn/goods-1113.html
Wiki页面地址: https://wiki.dfrobot.com.cn/_SKU_SEN0177_PM2.5%E6%BF%80%E5%85%89%E7%B2%89%E5%B0%98%E4%BC%A0%E6%84%9F%E5%99%A8
Wiki里面给的代码是这样的:
- //******************************
- //*Copyright (c) 2015, DFRobot
- //*All rights reserved
- //*Abstract: Read value of PM1,PM2.5 and PM10 of air quality
- //*
- //*Version:V2.0
- //*Author:Jason
- //*Date:Feb.2016
- //******************************
- #include <Arduino.h>
- #define LENG 32
- char buf[LENG];
-
- int PM01Value=0; //define PM1.0 value of the air detector module
- int PM2_5Value=0; //define PM2.5 value of the air detector module
- int PM10Value=0; //define PM10 value of the air detector module
-
- void setup()
- {
- Serial.begin(115200);
- }
-
- void loop()
- {
- if(Serial.available())
- {
- Serial.readBytes(buf,LENG);
- if(buf[0] == 0x42 && buf[1] == 0x4d){
- if(checkValue(buf,LENG)){
- PM01Value=transmitPM01(buf); //count PM1.0 value of the air detector module
- PM2_5Value=transmitPM2_5(buf);//count PM2.5 value of the air detector module
- PM10Value=transmitPM10(buf); //count PM10 value of the air detector module
- }
- }
- }
- static unsigned long OledTimer=millis();
- if (millis() - OledTimer >=1000)
- {
- OledTimer=millis();
-
- Serial.print("PM1.0: "); //send PM1.0 data to bluetooth
- Serial.print(PM01Value);
- Serial.println(" ug/m3");
-
- Serial.print("PM2.5: "); //send PM1.0 data to bluetooth
- Serial.print(PM2_5Value);
- Serial.println(" ug/m3");
-
- Serial.print("PM10: "); //send PM1.0 data to bluetooth
- Serial.print(PM10Value);
- Serial.println(" ug/m3");
- }
-
- }
- char checkValue(char *thebuf, char leng)
- {
- char receiveflag=0;
- int receiveSum=0;
- char i=0;
-
- for(i=0;i<leng;i++)
- {
- receiveSum=receiveSum+thebuf[i];
- }
-
- if(receiveSum==((thebuf[leng-2]<<8)+thebuf[leng-1]+thebuf[leng-2]+thebuf[leng-1])) //check the serial data
- {
- receiveSum=0;
- receiveflag=1;
- }
- return receiveflag;
- }
-
- int transmitPM01(char *thebuf)
- {
- int PM01Val;
- PM01Val=((thebuf[4]<<8) + thebuf[5]); //count PM1.0 value of the air detector module
- return PM01Val;
- }
-
- //transmit PM Value to PC
- int transmitPM2_5(char *thebuf)
- {
- int PM2_5Val;
- PM2_5Val=((thebuf[6]<<8) + thebuf[7]);//count PM2.5 value of the air detector module
- return PM2_5Val;
- }
-
- //transmit PM Value to PC
- int transmitPM10(char *thebuf)
- {
- int PM10Val;
- PM10Val=((thebuf[8]<<8) + thebuf[9]); //count PM10 value of the air detector module
- return PM10Val;
- }
复制代码
还是今年二月份更新的,但是,烧到板子上,接好传感器,并没有结果出来。
我自己分析的原因如下:
1.传感器串口的波特率是9600,Wiki页面里面已经写清楚了,代码里面使用的是115200
2.直接使用Serial.readBytes函数,因为传感器是每秒自动发送数据,这样读取的数据起始位是随机的,根本无法继续对数据进行处理。
3.buf的类型为char,应该为unsigned char。类型为char时,会导致checksum出错(认为读取结果有负数),也会导致PM2.5的结果有负数出现。
下面是我修改的代码:
PM.zip
(使用的是软串口)
运行结果:
***********************************************************************************************************Update:2016.3.26
更新了一下程序,更简洁一些
PM_test.2016.3.26.zip
|