Advertisement
Guest User

AdaptedKnockSensor

a guest
Jun 21st, 2014
3,246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | None | 0 0
  1. const int ledPin = 5;      // led connected to digital pin 5
  2. const int knockSensor = A0; // the piezo is connected to analog pin 0
  3. const int threshold = 20;  // threshold value to decide when the detected sound is a knock or not
  4.  
  5. int sensorReading = 0;      // variable to store the value read from the sensor pin
  6. int ledState = LOW;         // variable used to store the last LED status, to toggle the light
  7. unsigned long lastPeakTime = 0; //used for calculating peak
  8. int currentPeak = 0;       
  9. int blinkCounter = 0;
  10.  
  11. void setup() {
  12.  pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
  13.  Serial.begin(9600);       // use the serial port for debugging
  14. }
  15.  
  16. void loop() {
  17.   // read the sensor and store it in the variable sensorReading:
  18.   sensorReading = analogRead(knockSensor);    
  19.   if (sensorReading > currentPeak) {
  20.     currentPeak = sensorReading;
  21.   }
  22.  
  23.   // if the sensor reading is greater than the threshold:
  24. if (sensorReading >= threshold) {
  25.     Serial.print(sensorReading);
  26.         Serial.println(" Knock! ");
  27.  
  28.         while(blinkCounter <= 3)
  29.             {
  30.             Serial.println(blinkCounter);
  31.             digitalWrite(ledPin, HIGH);
  32.             delay(250);
  33.             digitalWrite(ledPin, LOW);
  34.             delay(250);
  35.             blinkCounter++;
  36.             }
  37.         blinkCounter = 0;
  38.         delay(50);  
  39.   }
  40.     //DEBUG CODE THAT GETS WRITTEN TO SERIAL, NOT NECESSARY TO LEAVE IN
  41.     if(millis() - lastPeakTime > 2000) {
  42.         Serial.print("Peak value: ");
  43.         Serial.println(currentPeak);
  44.         lastPeakTime = millis();
  45.         currentPeak = 0;
  46.     }
  47.  
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement