Create a program that generates a tune whenever the tact switch is pressed (in latch states). Define your own tune frequencies for each of the 2 tact switches. The tunes should not finish playing whenever pressing each switch

const int speakerpin = 6;
const int sw1 = 2;
const int sw2 = 3;
int song = 0;
int seq = 0;
int led[] = {8,9,10,11,12,13};
int a;

#define TUNE1 35
const int notes_tune1[TUNE1] = {330, 311, 330, 311, 330, 494, 294, 262, 440, 262, 330, 440, 494, 330, 440, 494, 523, 330, 311, 330, 311, 330, 494, 294, 262, 440, 262, 330, 440, 494, 330, 523, 494, 440,0}; //Fur Elise

const int beats_tune1[TUNE1] = {1,1,1,1,1,1,1,1,4,1,1,1,4,1,1,1,4, 1,1,1,1,1,1,1,1,4,1,1,1,4,1,1,1,4,1};

 #define TUNE2 33
const int notes_tune2[TUNE2] = {117, 175, 277, 294, 392, 349, 98, 196, 277, 294, 440, 392, 65,131,156,196,294,262,131,156,196,262,87,175,220,262, 0}; // Bohemian Rhapsody
const int beats_tune2[TUNE2] = {1, 1, 1, 1, 3, 2, 1, 1, 1, 1, 3, 2,1, 1, 1, 1, 3, 2,1,1,1,1,1,1,1,1, 1};

const int tempo = 250;
void setup()
{
  pinMode(speakerpin, OUTPUT);
  pinMode(sw1,INPUT_PULLUP);
  pinMode(sw2,INPUT_PULLUP);
  for (a=0;a<6;a++)
    pinMode (led[a],OUTPUT);
}
void loop()
{
  while(digitalRead(sw1) == 0)
  {
    song = 1;
  }
  while(digitalRead(sw2) == 0)
  {
    song = 2;
  }
  switch(song)
  {
    case 1:
    	playTune1();
        ledblink();
    	break;
    
    case 2:   
    	playTune2();
        ledblink();
        break;  
  }
}
void playTune1()
{
  for(int i = 0; i < TUNE1; i++)
  {
    if(notes_tune1[i] == 0)
    {
      delay(beats_tune1[i]*tempo);
    }
    else
    {
    ourTone(notes_tune1[i], beats_tune1[i]*tempo);
    }
    delay(tempo/2);
     ledblink();
  }
}
void playTune2()
{
  for(int y = 0; y < TUNE2; y++)
  {
    if(notes_tune2[y] == 0)
    {
      delay(beats_tune2[y]*tempo);
    }
    else
    {
      ourTone(notes_tune2[y], beats_tune2[y]*tempo);
    }
    delay(tempo/2);
     ledblink();
  }
}
void ourTone(int freq, int duration)
{
  tone(speakerpin, freq, duration);
  delay(duration);
  noTone(speakerpin);
}
void ledblink()
{
  digitalWrite(8, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(10, HIGH);
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(13, LOW);
  delay(50);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
  digitalWrite(11, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(13, HIGH);
  delay(50);
}

There is a problem in the code but I can't seem to find it. Please help me, I am still learning arduino through tinkercad. Thank you

Do you get errors when compiling the code or does it just not do what you want ?

When is our assignment due ?

the-tunes-should-not-finish-playing-whenever-pressing-each-switch


Elaborate on this?

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.