User:Laurier Rochon/prototyping/arduino recorder

From XPUB & Lens-Based wiki

Rough arduino pattern recorder/playback #1

Simple code to emulate a pattern recording device. It has a few little glitches, but the main idea works.

  • Program starts
  • User starts using pushbutton to determine a pattern (up to 100 clicks before array goes out of bounds)
  • After 5 seconds of silence, after user has started pushing (there can be 1min at the beginning though, that's fine)
  • Play the pattern back in a loop, with 2 sec intervals

(there is no way to restart it yet, I guess that will be part II)

HARD

  • Piezo in ground/pin 13
  • Pushbutton in 10K resistor => pin 2 / 5V power


SOFT

(much better)

const int buttonPin = 2;
const int nb=100;
int bs = 0;
int cs = 0;
unsigned long time;
int values[nb];
int c=0;
boolean startrec = false;

void setup() {
  pinMode(buttonPin, INPUT);
  tone(13,600,10);
  Serial.begin(9600); 
  Serial.println("Start recording...");
}

void loop(){
   bs = digitalRead(buttonPin);
   time = millis();
   char buffer[255];
   
   if(cs!=bs){
     startrec=true;
     cs=bs;
     values[c] = time;
     sprintf(buffer,"Recorded : %d",time);     
     Serial.println(buffer);
     c++;
   }
   
   if(startrec){
     int deadtime = time-values[c-1];
     if(deadtime>5000) playback();
   }
}

void playback(){
    Serial.println("Playing back");
    int cc = 0;
     for(int a=1;a<c-1;a++){
       int playtime = values[a]-values[a-1];
       int delaytime = values[a+1]-values[a];
       tone(13, 600,playtime);
       delay(delaytime);
     }
     Serial.println("Finished playing back");
     delay(1000);
     restart();
}

void restart(){
   startrec = false;
   memset(values,0,nb);
   c=0;
   Serial.println("You can start recording again");
}

(old version)

//globals
const int buttonPin = 2;
int values[100];
int c=0;
unsigned long time;
boolean startrec = false;

int buttonState = 1;
int newstate = 1;

void setup() {  
  pinMode(buttonPin, INPUT);
  Serial.begin(9600); 
}

void loop(){
  //time counter
  time = millis();
  buttonState = digitalRead(buttonPin);
  //this prevents the button from recording 2-3 times in the same push...
  delay(10);
  
  //if state has changed
  if(buttonState != newstate){
   startrec = true;
   
   //store in the array, print to screen and increment array index
   newstate = buttonState;
   values[c] = time/100; 
   Serial.println(values[c]);
   c++;
  }
  
  if(startrec){
   //if it's been more than 5 seconds doing nothing, after you've started pushing
   int deadtime = (time/100)- values[c-1];
   if(deadtime > 50){
     int cc = 0;
     //loop through values, and interpret the time difference as delays
     for(int a=0;a<c-1;a++){
        tone(13, 600,10);
        int dtime = (values[a+1]-values[a])*100;
        delay(dtime);
     }
     //gimme something to look at
     Serial.println("waiting 2 secs...replaying");
     delay(2000);
   } 
  }
  
}