int motorPin = 3;
int buzzerPin = 9;
int buttonPin=2;
int buttonState=0;
#include "pitches.h"
// notes in the melody the Bare Necessities from the JUNGLE BOOK:
int melody[] = {NOTE_G6, NOTE_A6, NOTE_C6,
0,NOTE_E6, NOTE_DS6,
NOTE_E6, NOTE_D6, NOTE_C6, NOTE_C6, NOTE_C6,
NOTE_D6, NOTE_C6, NOTE_D6, NOTE_C6,
NOTE_D6, NOTE_C6, NOTE_A6, NOTE_A6, 0, NOTE_G6,
NOTE_C6, NOTE_G6, NOTE_C6, NOTE_C6, NOTE_E6,
NOTE_A7, NOTE_G6, NOTE_E6, NOTE_F6,
NOTE_D7,0};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 4, 4,
2, 4, 4,
4, 8, 8, 4, 8,
4, 4, 4, 4,
4, 8, 8, 4, 8, 8,
8, 4, 8, 4, 4,
4, 4, 4, 4,
2, 2};
void setup(){
pinMode(motorPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop(){
//read button state
buttonState=digitalRead(buttonPin);
//checks to see if button is HIGH, does not play melody and spin motor if true
if(buttonState==HIGH){
digitalWrite(motorPin, 0);// sets motor speed to 0
Serial.println("Button LOW"); //testing to see button state
noTone(buzzerPin); // no signal sent to buzzer
}
else{
// buttonState is LOW plays melody and spins motor
digitalWrite(motorPin, 175); //sets motor speed to 175
Serial.println("Button HIGH");
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000 / noteDurations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
}
}
}