/***************************************************
Project R2D2 Sound Generator
To all fans of StarWars and Arduino!
Written by Marcelo Larios
BSD license, all text above must be included in any redistribution
Participated in the Instructable Arduino Contest 2019
https://www.instructables.com/R2D2-Sound-Generator/
****************************************************/
#define speakerPin 11
#define led1Pin 7
#define led2Pin 8
#define led3Pin 9
void setup() {
pinMode(speakerPin, OUTPUT);
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
pinMode(led3Pin, OUTPUT);
randomSeed(analogRead(0));
}
void phrase1() {
int k = random(1000,2000);
digitalWrite(led1Pin, HIGH);
for (int i = 0; i <= random(100,2000); i++){
tone(speakerPin, k+(-i*2));
delay(random(.9,2));
}
digitalWrite(led1Pin, LOW);
for (int i = 0; i <= random(100,1000); i++){
tone(speakerPin, k + (i * 10));
delay(random(.9,2));
}
}
void phrase2() {
int k = random(1000,2000);
digitalWrite(led2Pin, HIGH);
for (int i = 0; i <= random(100,2000); i++){
tone(speakerPin, k+(i*2));
delay(random(.9,2));
}
digitalWrite(led2Pin, LOW);
for (int i = 0; i <= random(100,1000); i++){
tone(speakerPin, k + (-i * 10));
delay(random(.9,2));
}
}
void loop() {
int K = 2000;
switch (random(1,7)) {
case 1:phrase1(); break;
case 2:phrase2(); break;
case 3:phrase1(); phrase2(); break;
case 4:phrase1(); phrase2(); phrase1();break;
case 5:phrase1(); phrase2(); phrase1(); phrase2(); phrase1();break;
case 6:phrase2(); phrase1(); phrase2(); break;
}
for (int i = 0; i <= random(3, 9); i++){
digitalWrite(led3Pin, HIGH);
tone(speakerPin, K + random(-1700, 2000));
delay(random(70, 170));
digitalWrite(led3Pin, LOW);
noTone(speakerPin);
delay(random(0, 30));
}
noTone(speakerPin);
delay(random(2000, 4000));
}