Your wiring is correct, but there is a better way to wire momentary switches. Wire one side of the switch directly to ground and the other side of the switch to a digital input. Take advantage of the internal pullup resistor by enabling the internal pullup with pinMode(pin, INPUT_PULLUP). The switch will read HIGH when not pushed and LOW when pushed. An advantage of that wiring is that you can easily debounce the switch with a small cap across the switch (hardware debounce).
Here is the state change detection example modified to use an active low switch (LOW when pushed) to toggle the led on pin 13.
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Variables will change:
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
void setup()
{
// initialize the button pin as a input with internal pullup enabled
pinMode(buttonPin, INPUT_PULLUP);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop()
{
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState)
{
if (buttonState == LOW)
{
// if the current state is LOW then the button
// went from off to on:
Serial.println("on");
digitalWrite(ledPin, !digitalRead(ledPin)); // toggle the led state
}
else
{
// if the current state is LOW then the button
// went from on to off:
Serial.println("off");
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}
And a schematic of the switch wiring:
