Follow-the-rythme game

Posted by kantch

kantch's picture

The force sensor is attached on top of the piezo buzzer. During the game, the buzzer plays a portion of a (random) melody and the player has to reproduce the rythm of the melody she just heard by beating with a finger the FSR. Each time the user remembers correctly the rythm, one note is added and the melody is played again, until the player wins by remembering the whole melody.

----------------------------------------------------------------------------------------------------------------------------

 

 #include "pitches.h"
 
int success[] = {NOTE_C4, NOTE_E4, NOTE_G4, NOTE_C4};
int durationsSuccess[] = {8, 8, 8, 4};
int successLength=8;
 
int fail[] = {NOTE_C4, NOTE_B3, NOTE_AS3, NOTE_A3};
int durationsFail[] = {8, 8, 8, 4};
int failLength=4;
 
int challenge[10];
int durationsChallenge[10];
int challengeLength=10;
 
void setup() {
  memset(challenge, 0, challengeLength);
  memset(durationsChallenge, 0, challengeLength);
}
 
void loop() {
  int z=0;
  challenge[z]=random(131, 262);
  durationsChallenge[z]=(random(0,2)+1)*2;
  z++;
  challenge[z]=random(131, 262);
  durationsChallenge[z]=(random(0,2)+1)*2;
  z++;
  challenge[z]=random(131, 262);
  durationsChallenge[z]=(random(0,2)+1)*2;
  z++;
  while(z<challengeLength){
    playMelody(challenge, durationsChallenge, z);
    if(readUserInput(durationsChallenge, z)){
      challenge[z]=random(131, 262);
      durationsChallenge[z]=(random(0,2)+1)*2;
      z++;
    }else{
      playMelody(fail, durationsFail, failLength);
    }
  }
  playMelody(success, durationsSuccess, successLength);
}
 
void playMelody(int *melody,int *durations, int length){
  for (int thisNote = 0; thisNote < length; thisNote++) {
    int noteDuration = 1000/durations[thisNote];
    tone(9, melody[thisNote],noteDuration);
    int pauseBetweenNotes = noteDuration*1.2;
    delay(pauseBetweenNotes);
    noTone(9);
  }
}
 
boolean readUserInput(int* durationsChallenge, int length){
  int thresholdDown=800;
  int thresholdUp=1000;
  int wait=100;
  float tol=0.4;
  float deltas[length];
  while(analogRead(0)>thresholdDown){}
  while(analogRead(0)<thresholdUp){}
  unsigned long prev=millis();
  for(int i=1; i<length; i++){
    while(analogRead(0)>thresholdDown){}
    while(analogRead(0)<thresholdUp){}
    unsigned delta = millis()-prev;
    prev = delta+prev;
    deltas[i-1]=delta;
  }
  for(int i=0; i<length-1; i++){
    if(abs( (((float) durationsChallenge[i]) - 1000/deltas[i])/((float) durationsChallenge[i]) ) > tol){
      return false;
    }
  }
  return true;
}
Photo on 2011-03-02 at 11.15.jpg
0
Your rating: None