Hi all,
I am working on a project measuring (and later processing) the readings of piezo pressure sensors. To be more exact, only the peak readings. A sensor is hit, produces a series of waves and I want to record the peak of the first wave and ignore the rest. After many YT tutorials, here's what I came up with so far. Please note this is just a first try for 1 sensor:
// these constants won't change:
const int piezo1 = 34; // the piezo is connected to analog pin 34
const int threshold1 = 200; // threshold value to decide when the detected sound is loud enough to be a real hit
const unsigned long debounceDelay1 = 30; // time elapesed after the last peak reading before reading this sensor again, to debounce
// these variables will change:
int sensorReading1 = 0; // variable to store the value read from the sensor pin
int currentReading1 = 0; // variable to
int peakReading1 = 0; // variable to store the peak reading to later convert to a MIDI note
unsigned long currentTime1 = 0; //
unsigned long peakTime1 = 0;
void setup() {
pinMode (piezo1, INPUT);
Serial.begin(9600); // use the serial port
}
void loop() {
sensorReading1 = analogRead(piezo1); // read the sensor and store it in the variable sensorReading1
if (sensorReading1 >= threshold1) // only act if sensorReading1 is above threshold1 value
{
currentTime1 = millis(); // set currentTime1 for the if comparisson to debounce
if ((sensorReading1 > currentReading1) && (currentTime1 > (peakTime1 + debounceDelay1))) // if the sensor reading1 is greater than the threshold1, greater than the previous reading and debounce time has elapsed
{sensorReading1 = currentReading1;} // replace currentReading1 with the new value, it's going up
if ((sensorReading1 >= threshold1) && (sensorReading1 < (currentReading1 - 10))) // if the sensor reading1 is greater than the threshold1 and is going down (past the peak),
{currentReading1 = peakReading1; // note the previous reading as the peakReading1, as the last currentReading was the first going down (so after the peak)
peakTime1 = millis();} // mark when the peakReading1 took place
Serial.println (peakReading1);
}
}
Please let me know where and how I could optimise this. Oh, and if I missed that there is a standard Arduino function that already does this, please enlighten me. My limited vocabulary on the subject doesn't always help me to find the functions available. I will use an ESP32 devBoard to run this on, as it is fast and cheap.
Cheers,
Hugo