Step 4Calibrate your Sensor to Detect Vibrations
To test the signal, use mastic to attach piezo to a flat surface. Try tapping or scratching on the surface at different locations and different intensities see what type of readings you get on the Arduino.
To reduce noise, I recommend computing a moving average of the input. This is a crude way of determining wave amplitude that avoids false positives due to random static current. More advanced methods such as FFT may also be used.
// Sample Code
int sensor = 2; // Analog in
int val =0; // Current reading for analog pin
int avg; // Running average of the wave amplitude
int MIDPOINT = 520; // Base reading
void setup() {
Serial.begin(9600);
avg = MIDPOINT; // set average at midpoint
}
void loop() {
val = analogRead(sensor);
// Compute wave amplittue
if (val > MIDPOINT) {
val = val - MIDPOINT;
} else {
val = MIDPOINT - val;
}
// compute running average fr the amplitute
avg = (avg * 0.5) + (val * 0.5);
if (avg > 130) {
// vibration detected!
Serial.println("TAP");
delay(100); // delay to ensure Serial port is not overloaded
}
}
| « Previous Step | Download PDFView All Steps | Next Step » |
1
comment
|
Add Comment
|
![]() |
Add Comment
|














































