Skip to content

Instantly share code, notes, and snippets.

@ghing
Created November 29, 2013 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghing/7707414 to your computer and use it in GitHub Desktop.
Save ghing/7707414 to your computer and use it in GitHub Desktop.
Arduino sketch to read piezoelectric sensor for Florence's science project.
// Use a Radio Shack 273-059 piezo buzzer as a shock sensor
// Based on recipe from http://www.eng.utah.edu/~cs5789/handouts/piezo.pdf
// and the Knock example (http://arduino.cc/en/Tutorial/Knock)
const int ledPin = 13; // Built in LED is pin 13
const int piezoPin = 0; // Piezoelectric element is attached to analog pin 0
const int threshold = 7; // Ignore readings below this value;
const int delayTime = 500; // HTime to pause during each loop
int val, t;
void setup() {
pinMode(ledPin, OUTPUT);
// Open serial communications and wait for port to open:
Serial.begin(57600);
Serial.println("Starting");
}
void loop() {
digitalWrite(ledPin, LOW);
val = analogRead(piezoPin); // Read the piezo
if (val >= threshold) {
// Read a value over the threshold
// Trigger a visual notification that a shock was detected
digitalWrite(ledPin, HIGH);
// Start our record of time at the initial over-threshold value
t = 0;
// Read values until they are well below the threshold
while(val > 0) {
// Output the time and value in the format "TIME,VALUE"
Serial.print(t);
Serial.print(",");
Serial.print(val);
Serial.print("\n");
// Read another value
val = analogRead(piezoPin);
// Increment the time
t++;
}
// Wait before taking another reading
delay(delayTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment