Back to Parent

//Laser variables
int laserOne = 0;
int laserTwo = 0;
int photoOne = A1;
int photoTwo = A0;
int threshPin = D0;
int thresh = 500;
int photo1;
int photo2;
int occupancy = 0;
long interval = 1000;
long previousMillis = 0;
bool in = FALSE;
bool out = FALSE;
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
int noise;
int micPin = D0;
double volts;

void setup(){

  pinMode (photoOne, INPUT);
  pinMode (photoTwo, INPUT);
  pinMode (micPin, INPUT);
  Spark.variable("Occupancy", &occupancy, INT);
  Spark.variable("Sample", &sample, INT);
  Spark.variable("Noise", &volts, DOUBLE);
}

void loop (){

   unsigned long startMillis= millis();  // Start of sample window
   unsigned int peakToPeak = 0;   // peak-to-peak level

   unsigned int signalMax = 0;
   unsigned int signalMin = 1024;

   unsigned long currentMillis = millis();

   // collect data for 50 mS
   while (millis() - startMillis < sampleWindow)
   {
      sample = analogRead(micPin);
      if (sample < 2000)  // toss out spurious readings
      {
         if (sample > signalMax)
         {
            signalMax = sample;  // save just the max levels
         }
         else if (sample < signalMin)
         {
            signalMin = sample;  // save just the min levels
         }
      }
   }
   peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
   volts = (peakToPeak * 3.3) / 1024;  // convert to volts


  photo1 = analogRead(photoOne);
  photo2 = analogRead(photoTwo);

  if(photo1 <= thresh && photo2 > thresh && in == FALSE && out == FALSE) {
    in = TRUE;
    out = FALSE;
  }

  if(photo2 <= thresh && photo1 > thresh && in == FALSE && out == FALSE) {
    out = TRUE;
    in = FALSE;
  }

  if(in == true && currentMillis - previousMillis < interval) {
    if(photo2 < thresh){
        occupancy++;
        in = FALSE;
        delay(1000);
    }
  }

  else if(out == true && currentMillis - previousMillis < interval) {
    if(photo1 < thresh){
        occupancy--;
        out = FALSE;
        delay(1000);
    }
  }

  else if(currentMillis - previousMillis >= interval) {
    in = FALSE;
    out = FALSE;
    previousMillis = currentMillis;
  }


  if(occupancy < 0){
      occupancy = 0;
  }
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0