SYSTEM_THREAD(ENABLED); // SHARP GP2Y0A21YK0F IR Distance sensor V0 const int constAnalogIRSensorPin = A0; const int constLED = D7; // D7 is built in LED const int constThreshold = 2000; // measured 2900 at 10cm, 800 at 50cm const int timeZoneOffset = 17; // -7 hour for PST = +17H int timeToCheck = 20*60; // 8PM bool failedToPublishEvent = false; int distance = 0; void setup() { Serial.begin(9600); pinMode(constLED, OUTPUT); Particle.variable("distance", distance); failedToPublishEvent = false; } void loop() { // current time in minutes since mignight int currentTime = (Time.hour() + timeZoneOffset)%24 * 60 + Time.minute(); // reads the value from the specified analog pin. The device has 8 channels (A0 to A7) with a 12-bit resolution. // This means that it will map input voltages between 0 and 3.3 volts into integer values between 0 and 4095. // This yields a resolution between readings of: 3.3 volts / 4096 units or, 0.0008 volts (0.8 mV) per unit. distance = analogRead(constAnalogIRSensorPin); // read if (distance > constThreshold) { // the charging cable is holstered: turn on LED and publish an event digitalWrite(constLED, HIGH); if (currentTime == timeToCheck) { failedToPublishEvent = !Particle.publish("Detected"); delay(60000); // delay 1 minute after a publish } } else digitalWrite(constLED, LOW); // if failed to publish, try again if (failedToPublishEvent) { failedToPublishEvent = !Particle.publish("Detected"); // try again delay(60000); // delay 1 minute after a publish } // wait before checking again delay(1000); // ms Serial.println(distance); }