So this code I have plays jingle bells through a buzzer with LEDs blinking along with it as soon as the power is connected. I'm also able to operate a servo using two buttons. However I would like to be able connect the power without the song and LED's starting to play. I would like the song to start only once I press one of the buttons. Any help would be much appreciated. I'm very new to using an Arduino so this code is kit-bashed using couple different programs I found.
My circuit
#include <Servo.h>
const byte buzzerPin = 8;
const byte pinSwitch1 = 2;
const byte pinSwitch2 = 3;
const byte ledPin = 13;
const byte pinServo = 9;
// Notes is an array of text characters corresponding to the notes
// in your song. A space represents a rest (no tone)
const int songLength = 31;
const char notes[songLength] = "eee eee egcde fff ffee eeggfdc " ; // a space represents a rest
const int beats[songLength] = { 2,2,3,1,2,2,3,1,2,2,3,1,4,4,2,2,3,0,1,2,2,2,0,1,1,2,2,2,2,4,4 };
const int tempo = 140;
Servo
servo;
void setup()
{
pinMode( buzzerPin, OUTPUT );
pinMode( ledPin, OUTPUT );
pinMode( pinSwitch1, INPUT ); //you'll need pull-down resistors on these inputs; closing switch sets it high
pinMode( pinSwitch2, INPUT );
servo.attach( pinServo ); //other
}//setup
void loop()
{
PlaySong();
MoveServo();
}//loop
#define GET_NOTE 0
#define PLAY_NOTE 1
#define SONG_PAUSE 2
void PlaySong( void )
{
static byte
statePlay = GET_NOTE;
static int
noteNumber = 0;
static unsigned long
noteDuration = 0,
noteTime = 0;
unsigned long
timeNow;
switch( statePlay )
{
case GET_NOTE:
if( notes[noteNumber] != ' ' )
{
digitalWrite( ledPin, HIGH );
tone( buzzerPin, frequency( notes[noteNumber] ) );
}//if
noteDuration = beats[noteNumber] * tempo; // length of note/rest in ms
noteTime = millis();
statePlay = PLAY_NOTE;
break;
case PLAY_NOTE:
if( millis() - noteTime < noteDuration )
return;
tone( buzzerPin, 0 );
digitalWrite( ledPin, LOW );
if( noteNumber < songLength )
{
noteNumber++;
statePlay = GET_NOTE;
}//if
else
{
//after song has finished, wait 2-seconds then play it again
noteNumber = 0;
noteTime = millis();
statePlay = SONG_PAUSE;
}//else
break;
case SONG_PAUSE:
if( millis() - noteTime < 2000 )
return;
statePlay = GET_NOTE;
break;
}//switch
}//PlaySong
void MoveServo( void )
{
static int
pos = 0;
static unsigned long
timeServo = 0;
unsigned long
timeNow;
timeNow = millis();
if( (timeNow - timeServo) < 5 )
return;
timeServo = timeNow;
if( digitalRead( pinSwitch1 ) == HIGH )
{
if( pos < 180 )
pos++;
servo.write( pos );
}//if
if( digitalRead( pinSwitch2 ) == HIGH )
{
if( pos > 0 )
pos--;
servo.write( pos );
}//if
}//MoveServo
int frequency( char note )
{
switch( note )
{
case 'c': return 262; break;
case 'd': return 294; break;
case 'e': return 330; break;
case 'f': return 349; break;
case 'g': return 392; break;
case 'a': return 440; break;
case 'b': return 494; break;
case 'C': return 523; break;
default: return 0; break;
}//switch
}//frequency