#define LEDPIN 13 #define BUTTONPIN 19 #define PINX A0 #define PINY A1 #define PINZ A2 #define HORNPIN A4 boolean activeState = false; int lastsum = 0; void setup() { pinMode(BUTTONPIN, INPUT); digitalWrite(BUTTONPIN,HIGH); // set pullups pinMode(LEDPIN,OUTPUT); pinMode(PINX, INPUT); pinMode(PINY, INPUT); pinMode(PINZ, INPUT); pinMode(HORNPIN, OUTPUT); digitalWrite(HORNPIN,LOW); Serial.begin(9600); } #define MOVEMENTALLOWANCE 20 #define ARMDELAY 5 void loop() { int accelsum = 0; handleButtons(); if (activeState){ flash(3); // flash three times to indicate we are armed delay(ARMDELAY*1000); flash(1); // flash once to warn of arming. lastsum = analogRead(PINX) +analogRead(PINY)+analogRead(PINZ); while (activeState){ accelsum = analogRead(PINX) +analogRead(PINY)+analogRead(PINZ); // you can use the following prints to tune the MOVEMENTALLOWANCE // Serial.print("accelsum:");Serial.print(accelsum);Serial.print(" Diff: "); // Serial.println(abs(accelsum - lastsum)); if (abs(accelsum - lastsum) > MOVEMENTALLOWANCE){ Serial.println ("HONK"); honk(2); activeState = false; } lastsum = accelsum; delay(200); } delay(500); } } void flash(int times){ for (int i =0 ; i < times; i++){ digitalWrite(LEDPIN, HIGH); delay(300); digitalWrite(LEDPIN,LOW); delay(300); } } #define HORNOFFDELAY 1000 #define HORNONDELAY 1000 void honk(int times){ for (int i = 0; i < times; i++){ digitalWrite(HORNPIN, HIGH); delay(HORNONDELAY); digitalWrite(HORNPIN,LOW); delay(HORNOFFDELAY); } } #define DEBOUNCEDELAY 200 long lastcheck = 0; // last time we checked the button int lastButton = HIGH; void handleButtons(){ long current = millis(); if ((current - lastcheck) < DEBOUNCEDELAY) return; int reading = digitalRead(BUTTONPIN); if (reading != lastButton){ lastcheck = current; // reset debounce timer if (reading == LOW) { //button pressed activeState = activeState? false:true; } } lastButton = reading; }