Skip to content

Instantly share code, notes, and snippets.

@aljosamrak
Last active May 27, 2020 11:00
Show Gist options
  • Save aljosamrak/0676335a19e23e84ed7d5ae913e71b96 to your computer and use it in GitHub Desktop.
Save aljosamrak/0676335a19e23e84ed7d5ae913e71b96 to your computer and use it in GitHub Desktop.
Dust Sensor (PPD42NS) pulse width measuring using interrupts
/**
* Dust Sensor (PPD42NS)
* VCC 5V
* GND GND
* SIG D7
*/
// Pin (D7) connected to the dust sensor signal pin
int pin = 13;
volatile unsigned long pulseStartTime; // time of front raising
volatile unsigned long pulseDuration; // duration of the pulse
unsigned long starttime;
unsigned long sampletime_ms = 30000; //sampe 30s
unsigned long lowpulseoccupancy = 0;
void setup(void)
{
Serial.begin(115200);
pinMode(pin, INPUT);
// Interrupt on front changing
attachInterrupt(digitalPinToInterrupt(pin), isr, CHANGE);
// Get the current time;
starttime = millis();
}
ICACHE_RAM_ATTR void isr()
{
// Get the current time
unsigned long currentTime = micros();
// High state indicaste pulse start - remember the time
if (digitalRead(pin) == LOW)
{
pulseStartTime = currentTime; // save get time of pulse start
}
else
{
// Low state indicaste pulse end - calculate pulse width
if (pulseStartTime != 0) // check that we detected a pulse start
{
pulseDuration = currentTime - pulseStartTime;
// Reset the time counter
pulseStartTime = 0;
}
}
}
void loop(void) {
// If pulse duration present
if (pulseDuration != 0)
{
// Accumulate pulses over a 30s period
lowpulseoccupancy = lowpulseoccupancy + pulseDuration;
pulseDuration = 0;
}
// if the sampel time == 30s
if ((millis() - starttime) > sampletime_ms)
{
float ratio = lowpulseoccupancy / (sampletime_ms * 10.0); // Integer percentage 0=>100
float concentration = 1.1 * pow(ratio, 3) - 3.8 * pow(ratio, 2) + 520 * ratio + 0.62; // using spec sheet curve
Serial.print("concentration = ");
Serial.print(concentration);
Serial.println(" pcs/0.01cf");
Serial.println("\n");
lowpulseoccupancy = 0;
starttime = millis();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment