const int tiltPin = D2;
unsigned long lastPublish = 0;
const unsigned long PUBLISH_INTERVAL = 2000;
const unsigned long SHAKE_WINDOW = 2000;
const int SHAKE_THRESHOLD = 10;
int lastState = 0;
int stateChanges = 0;
unsigned long windowStart = 0;
void setup() {
Serial.begin(115200);
pinMode(tiltPin, INPUT_PULLUP);
windowStart = millis();
}
void loop() {
int currentState = digitalRead(tiltPin);
unsigned long currentTime = millis();
if (currentState != lastState) {
stateChanges++;
lastState = currentState;
Serial.print("State change: ");
Serial.println(stateChanges);
}
if (currentTime - windowStart >= SHAKE_WINDOW) {
bool isShaking = (stateChanges >= SHAKE_THRESHOLD);
if (currentTime - lastPublish >= PUBLISH_INTERVAL) {
String data = String(isShaking ? "1" : "0");
Particle.publish("shake-detect", data, PRIVATE);
Serial.print("Shake detected: ");
Serial.println(isShaking ? "YES" : "NO");
lastPublish = currentTime;
}
stateChanges = 0;
windowStart = currentTime;
}
delay(10);
}
Click to Expand
Content Rating
Is this a good/useful/informative piece of content to include in the project? Have your say!
You must login before you can post a comment. .