User:Lieven Van Speybroeck/Prototyping/5-Playback Pattern

From XPUB & Lens-Based wiki

Recording music with a pushbutton on Arduino

This program lets you make a record of tones by pushing a pushbutton on Arduino.
Waiting 5 seconds ends the 'record-session'.
By pushing 1 more time, the pattern you recorded will be played back.

int btnPin=2;
int spkrPin=13;
int btnActive=0;
int toneArray[100];
int delayTime=0;
int i=0;
int g=0;

void setup(){
  pinMode(spkrPin, OUTPUT);
  pinMode(btnPin, INPUT);
  Serial.begin(9600);
  tone(spkrPin, 400, 10);
  
}

void loop(){
  while (delayTime < 5000) { // Keep 'recording' until the buttons is untouched for a minimum of 5 seconds
    
    btnActive=digitalRead(btnPin);
    
    while (btnActive==LOW){ // Go through this loop as long as the button is left unpressed
        delayTime=(millis()-toneArray[i-1]); // Measure the time the button is left unpressed
        btnActive=digitalRead(btnPin);
    }
    // ok, pressed now...
    toneArray[i]=millis(); // Store 'time of press' into an array
    Serial.print("You've waited ");Serial.print(delayTime, DEC);Serial.println(" milliseconds to push the button"); // Print how long you've waited to push the button
    i++; // Move up the pointer in the array 1 position
    
    btnActive=digitalRead(btnPin);
    
    while (btnActive==HIGH){ // Go through this loop as long as the button is pressed
        btnActive=digitalRead(btnPin);
        tone(spkrPin, 400, 10); // Play tone while pushing the button
    }
    // ok, released now...
    toneArray[i]=millis(); // Store 'time of release' into the array
    Serial.print ("You pushed the button for ");Serial.print((toneArray[i]-toneArray[i-1]), DEC);Serial.println(" milliseconds"); // Print how long you've pushed the button
    i++; // Move up the pointer in the array 1 position
  }
  
  Serial.println("Playback:"); // This gets triggered when the 'record' is ended, so the button was left untouched for 5 seconds and then got pushed 1 more time
  for (g=0; g<(i-2); g=g+2){
     tone(spkrPin, 400, (toneArray[g+1]-toneArray[g])); // Playback the tones based on the values in the array
     delay(toneArray[g+2]-toneArray[g+1]); // Define the delay between tones based on the values in the array
     Serial.print("Tone lasted for " );Serial.print((toneArray[g+1]-toneArray[g]), DEC);Serial.println(" milliseconds"); // Print out the length of the tone that was played
     Serial.print("The delay after this tone was ");Serial.print((toneArray[g+2]-toneArray[g+1]), DEC);Serial.println(" milliseconds"); // Print out the length of the delay
  }
  
  while(1){}; // 'Stop the program: go into an endless empty loop
}