Saturday, December 10, 2011

Arduino Tap Back

I saw a video on the arduino forum of someone using a piezo to detect taps/knocks etc, and then play them back with a vibrating motor. I though it'd be pretty fun ot make one too, but i instead used the LM386 amp from my previous project and the tone() function in arduino to play back the tones.

I hooked up the piezo like so:

















and then the lm386 to a digital port like:












CODE: 

#define spkr 4 //digital pin to lm386
#define piezo 5 //analog pin piezo is on
int timeFirst;
int loopnum = 0; //# of times a tap is detected
int timeSecond;
int TapDelay;
int timeStore[15]; //how many taps you want to record
int lengthtest;
void setup()
{
  Serial.begin(9600);
  noTone(spkr);
}

void loop()
{
  int sensorValue = analogRead(piezo); //read the piezo value
  Serial.println(sensorValue, DEC); // print to serial for debug
  if (sensorValue > 50) //physically taping on the piezo gives results to around 400
  {                    //its about 30 when still
    if(loopnum!=0) //run only if its not the first tap detected
    {
      timeSecond = millis(); //record time tap happened
      TapDelay =(timeSecond - timeFirst); //how long between taps
      timeStore[loopnum]=TapDelay; //write time between taps to array

      Serial.println();
      Serial.print("# of taps detected: ");
      Serial.println(loopnum);
    }
    timeFirst = millis(); //record time at tap to calc time between next tap and current tap
    ++loopnum; // increase by one so that next tap delay is written to next array value
  }

  lengthtest=millis();
  if((lengthtest-timeFirst)>2000 && loopnum>0) //2000msec is how long to wait before playback after last tap
  {
    Serial.print("playback");
    for(int x=1; x<=loopnum; ++x) //go through timestore array and play taps with the recorded delays
    {
      tone(spkr, 300);
      delay(175); // how long to play each tap for
      noTone(spkr);
      delay(timeStore[x]);  //delay between taps
    }
    loopnum=0; //reset tap counter
  }
  delay(175); //delay to reduce amount of data, one tap can count as multipule because the arduino sample too often.
}

1 comment:

  1. You make it entertaining and you still take care of to keep it sensible. I can’t wait to learn much more from you. That is actually a terrific web site.
    RC Cars

    ReplyDelete