NAzT
7/9/2015 - 5:21 AM

DustSensor.ino

DustSensor.ino

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP8266WiFi.h>
#include <WiFiHelper.h>

const char* ssid     = "";
const char* pass     = "";

int pinDust = 14;
byte _buff[2];

unsigned long duration, starttime, endtime, sampletime_ms = 30000, lowpulseoccupancy = 0;
float ratio = 0, concentrations = 0;
int i = 0;

WiFiHelper *wifi;
LiquidCrystal_I2C lcd(0x21, 16, 2);

void init_wifi()
{
  wifi = new WiFiHelper(ssid, pass);
  wifi->on_connected([](const char* message)
  {
    Serial.println (message);
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  });
  wifi->on_disconnected([](const char* message)
  {
    Serial.println (message);
  });
  wifi->begin();
}

void init_hardware()
{
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.println();
}

void setup()
{
  lcd.begin();
  lcd.backlight();
  init_hardware();
  init_wifi();
  pinMode(pinDust, INPUT);
  lcd.setCursor(4, 0);
  lcd.print("Dust Now");
  lcd.setCursor(1, 1);
  lcd.print("Dust : ");
  lcd.setCursor(8, 1);
  lcd.print("0.00  ");
}

void loop()
{
  wifi->loop();
  concentrations = read_dust(pinDust);

  lcd.setCursor(8, 1);
  lcd.print(concentrations);
  uploadThingsSpeak(concentrations);
}

void uploadThingsSpeak(float d) {
  static const char* host = "api.thingspeak.com";
  static const char* apiKey = "API KEY";

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    DEBUG_PRINTLN("connection failed");
    return;
  }
  String url = "/update/";
  //  url += streamId;
  url += "?key=";
  url += apiKey;
  url += "&field1=";
  url += d;

  Serial.print("Requesting URL: ");
  Serial.println(url);


  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
}

float   read_dust(uint8_t pin)
{
  duration = pulseIn(pin, LOW);
  lowpulseoccupancy += duration;
  endtime = millis();
  if ((endtime - starttime) > 1000)
  {
    Serial.print(duration);
    Serial.print(",");
  }
  if ((endtime - starttime) > sampletime_ms)
  {
    ratio = (lowpulseoccupancy - endtime + starttime + sampletime_ms) / (sampletime_ms * 10.0); // Integer percentage 0=>100
    concentrations = 1.1 * pow(ratio, 3) - 3.8 * pow(ratio, 2) + 520 * ratio + 0.62; // using spec sheet curve
    lowpulseoccupancy = 0;
    starttime = millis();
  }
  return concentrations;
}