Random sound generator

🕒 < 1 m read

In this project, I used a piezo speaker to randomly play certain notes which i arrayed form 0 – 9.


soundgenerator

Demo

Note: The LED in the video would not be used in this project.

Code

int speakerPin = 3; //Speaker Pin
long randomNo;

int length = 10; // the number of notes
char notes[] = "cdefgabCDE"; // a space represents a rest
int beats[] = {1};

void playTone(int tone, int duration) {
for (long i = 0; i < duration * 300L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}

void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C','D','E' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956, 851, 758 };
// play the tone corresponding to the note name
for (int i = 0; i < 10; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}

void setup() { //set outputs and inputs

  Serial.begin(9600); // Monitor
  pinMode(speakerPin, OUTPUT); //Speaker 
  randomSeed(analogRead(0));
}

void loop() {
      randomNo = random (0,10);
      Serial.println(randomNo);
      int l = randomNo;
      if(l==0){playNote(notes[0], beats[0] * 100);}
      if(l==1){playNote(notes[1], beats[0] * 100);}
      if(l==2){playNote(notes[2], beats[0]*100 );}
      if(l==3){playNote(notes[3], beats[0] * 100);}
      if(l==4){playNote(notes[4], beats[0]* 100);}
      if(l==5){playNote(notes[5], beats[0] * 100);}
      if(l==6){playNote(notes[6], beats[0]* 100);}
      if(l==7){playNote(notes[7], beats[0]* 100);}
      if(l==8){playNote(notes[8], beats[0]* 100);}
      if(l==9){playNote(notes[9], beats[0]*100);}
      delay(100);
}
Share your love

Leave a Reply

Your email address will not be published. Required fields are marked *