/*
 
  Original Author: David Souder
  Inspiré de l'exemple Seeed pour les méthodes Seeed: http://wiki.seeedstudio.com/Grove-Dust_Sensor/#platforms-supported 
  Version : 31/03/2018
*/


#ifndef DUINOEDU_DUST_PPD42NS_H
#define DUINOEDU_DUST_PPD42NS_H


class Duinoedu_Dust_PPD42NS	
{
  public:
	Duinoedu_Dust_PPD42NS(){
		sampletime_ms = 2000;
		lowpulseoccupancy = 0;
		ratio = 0;
		concentration = 0;
	}
	
  
	void branch(uint8_t _pin){
		pin = _pin;
		pinMode(pin, INPUT);
	}
	
	uint32_t getPulseWidth(){
		return pulseIn(pin, LOW);
	}
	
	uint32_t getConcentration(){
		
		
		duration = pulseIn(pin, LOW);
		//Serial.println(duration);
		
		
		lowpulseoccupancy = lowpulseoccupancy + duration;
		//Serial.println(lowpulseoccupancy);
	
		if ((millis()- starttime) >= sampletime_ms)
		{
			
			ratio = lowpulseoccupancy /(sampletime_ms*10.0); 
			concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62; 
			// Reset
			lowpulseoccupancy = 0;
			starttime = millis();
		}
		
		return concentration;	
	}
	
	uint8_t pin;
	unsigned long duration;
	unsigned long starttime;
	unsigned long sampletime_ms;
	unsigned long lowpulseoccupancy;
	float ratio;
	float concentration;

};

#endif












/* Exemple
#include <Duinoedu_Dust_PPD42NS.h>

Duinoedu_Dust_PPD42NS dust;

void setup() {
  Serial.begin(9600);
  dust.branch(D8);
}

void loop() {
  Serial.println( dust.getPulseWidth() );     // Largeur d'impulsion en ms
  Serial.println( dust.getConcentration() );  // Concentration en pcs/0.01cf  
}

*/