Piezo Disc problem

Hello everyone,

I am building a project where a tapping a piezo disc will prompt a random number to be selected. The random number will fall within a couple parameters and that will cause a light to turn on. I am having a problem where it is spamming like a ton of numbers regardless of the threshold I put on it. Has anyone dealt with this before or know how to compensate for it?

int greenPin = 10;
int bluePin = 11;
int redPin = 9;
int randNum;
int piezoPin = 0;
int pressure = 0;
int threshold = 100;
int N = 100;

void setup()
{
Serial.begin(9600);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(redPin, OUTPUT);
}

void loop()
{
pressure = analogRead(piezoPin);

if (pressure >= threshold)
{
randNum = random(0,100);
Serial.println(randNum);

// if (randNum <= 33)
// {
// analogWrite(greenPin, 0);
// analogWrite(bluePin, 0);
// analogWrite(redPin, 75);
// }
//
// else if (randNum > 33 && randNum <= 66)
// {
// analogWrite(greenPin, 75);
// analogWrite(bluePin, 0);
// analogWrite(redPin, 0);
// }
// else if (randNum > 66 && randNum <= 100)
// {
// analogWrite(greenPin, 0);
// analogWrite(bluePin, 75);
// analogWrite(redPin, 0);
// }
}

}

Did you use a 1Megohm resistor from the analogue pin to ground (across the piezo).

pressure = analogRead(piezoPin);
This is assuming a piezo generates a DC voltage,
and/or that it’s peak voltage exactly coincides with when you measure.

Try measuring the piezo multiple times, and store it’s peaks in a variable.
Leo…

//piezo disk with 1Megohm load resistor across
const byte piezoPin = A0;
int rawValue;
int peakValue;

void setup() {
  Serial.begin(9600); // for debugging only
}

void loop() {
  peakValue = 0; // reset before measuring
  for (int i = 0; i < 250; i++) { // multiple A/D readings
    rawValue = analogRead(piezoPin);
    if (rawValue > peakValue) peakValue = rawValue; // store peaks
  }

  // this 'if' block can be removed after testing
  if (peakValue > 0) {
    Serial.println(peakValue);
    delay(250);
  }
  // use 'peakValue' in the rest of the code
}

If all you want to know is that a tap has happened you could simply put a delay in after you write a number to stop it going round the loop so fast. I'd start with delay(250), 1/4 of second, and play with the value until it works as you want.

Steve,