/** pinAlert: the alert led. * Blinks when arduino is calibrating the analogInput. * Blinks fast when calibration finished, or memory is erased. * Lights when in recording state. */ const int pinAlert = 13; /** pwmOutput: the analogInput value is converted to 0-255 * and sent here. */ const int pwmOutput = 11; /** analogInput: analog input is read from here */ const int analogInput = 0; /** pinButton: the pin of the button */ const int pinButton = 7; /** valueLength is the delay between values recorded */ const int valueLength=50; /** savedCountMax is the maximum number of values recorded */ const int savedCountMax=300; /** saved array holds the recorded values */ int saved[savedCountMax]; /** minVal, maxVal: the minimum and the maximum value read from the * analog input while calibrating. */ int minVal=9999; int maxVal=-1; /** stores the position of the last saved value +1 */ int lastSaved; /** stores the postition of the last played value +1 */ int lastPlayed; void setup() { pinMode(pwmOutput, OUTPUT); pinMode(pinAlert,OUTPUT); pinMode(pinButton,INPUT); //Serial.begin(9600); lastSaved=0; lastPlayed=0; } void loop(){ int val; long valConverted; int continueCalibrating=1; if (maxVal == -1){ // calibrating, but only once blink(); int i=0; while(continueCalibrating){ if (i<300){ digitalWrite(pinAlert,LOW); }else{ digitalWrite(pinAlert,HIGH); if (i>600) i=-1; } i++; val=analogRead(analogInput); // store the maximun and minimum value read if (val < minVal) minVal=val; if (val > maxVal) maxVal=val; analogWrite(pwmOutput,normalize(val)); if (digitalRead(pinButton) == LOW){ // quit calibration if the button is pressed continueCalibrating=0; } } blink(); } int dIn=digitalRead(pinButton); if (dIn == HIGH){ // the button is not pressed, so we are replaying digitalWrite(pinAlert,LOW); valConverted=saved[lastPlayed]; lastPlayed++; if (lastPlayed > lastSaved){ lastPlayed=0; } }else{ // the button is pushed, so we are in recording state digitalWrite(pinAlert,HIGH); valConverted=normalize(analogRead(analogInput)); if (lastPlayed > 0){ // this is the first recorded value lastSaved=0; } if (lastSaved > savedCountMax){ // the array is full, starting over blink(); lastSaved=0; } saved[lastSaved]=(int)valConverted; lastSaved++; // playing will start from 0 after recording lastPlayed=0; } analogWrite(pwmOutput,valConverted); delay(valueLength); } /** * Any val value will be transformed between 0 and 255 */ int normalize(int val){ long valConverted; if (val > maxVal) val=maxVal; if (val < minVal+10) val=minVal; // +10 to loose some noise valConverted=( (val-minVal)*255 ) / (maxVal-minVal); return valConverted; } /* Blinks pinAlert */ void blink(){ for (int i=0; i<6; i++){ digitalWrite(pinAlert,HIGH); delay(35); digitalWrite(pinAlert,LOW); delay(25); } }