4. Piano on the way

The final code looks like this: 


// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin
const int speakerPin = 11; //the number of the speaker pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(speakerPin, OUTPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    tone(speakerPin, 440);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
    noTone(speakerPin);
  }
}


We are now going to add one more button to the circuit, to play a different note once pressed. We will need one more pushbutton and one more 10kΩ resistor.

The setup of this button will the same as first button, alas the new button will be
attached to a different pin on the Arduino (3).


First we add variables for the new button:

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int buttonPin = 3;     // the number of the new pushbutton pin!
const int ledPin =  13;      // the number of the LED pin
const int speakerPin = 11; //the number of the speaker pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;         // variable for reading the new pushbutton status!

And then we initialise pin 3 as input:

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pins as an input:
  pinMode(buttonPin, INPUT);
  pinMode(buttonPin2, INPUT); //tadah!
  // initialise the speaker pin as output:
  pinMode(speakerPin, OUTPUT);
}