How do I wire up this button to toggle my PWM LED on/off?

Hi all,

Arduino newbie here. I was messing around with a PWM LED and managed to get gradients and other cool effects going. Now I want to wire up a button to toggle it on or off.

I have one of these cheap switches from eBay, which have no instructions. I took some male to male wire and screwed it into the ends, and then have been trying different spots on my Arduino... but I'm not making any progress. I know I probably need to send power through it to "test" whether the circuit is open, but I'm either wiring it up wrong or haven't done the code right. Where/how do I connect this thing?

I probably just need a nudge in the right direction. I can write code myself once I know the correct way to wire it.

Cheers,

eBay Switch.jpg

Wire the switch to a digital input pin with a pull up resistor.

pin -> switch -> GND

Have a variable that stores the state of the LED, on or off. Have the sketch monitor the state of the switch, when it changes, change the state variable and then set the led to the state of the variable.

See this for the options:-
http://www.thebox.myzen.co.uk/Tutorial/Inputs.html

Awesome. Apparently the Arduino has a digital resistor built in, activated with this setup code:

pinMode(8, INPUT);
  digitalWrite(8, HIGH); // Digital 10k ohm resistor

My switch had HI written under one terminal. I wired that in to pin 8, then wired the other end in to GND. I'm instantly getting back 1's over the serial monitor until I press the switch, and then get back a clean string of 0's. I'll still probably do triple-check code to rule out anomalous changes (must get same input back 3 times in a row), but I think this will work great!

Much appreciated!

Final question - Did I wire it up right, or should I reverse it? (Maybe it doesn't even matter? I really am a novice with this wiring stuff.)

You should probably use this style instead.

pinMode(8, INPUT_PULLUP);

This will use an internal pull up resistor so the pin will be HIGH until you pull it low.

digitalWrite is usually used when then pin is set as an OUTPUT pin, not an INPUT.

It doesn't matter which way you wire a switch, it just completes the circuit to GND when the switch is closed (So pin has a LOW reading). When the switch is open, the pin has a HIGH reading (because of the pull up resistor).

You can get the same effect by connecting one end of the switch to pin 8, and the other end of the switch to 5V, with no pull up resistor, This would mean the pin would read LOW when the switch is open, and read HIGH when the switch is closed (As it completes the circuit to 5V).

This would mean the pin would read LOW when the switch is open, and read HIGH when the switch is closed (As it completes the circuit to 5V).

Only if there was a resistor from the pin to Gnd so the pin wasn't floating when the button is not pressed.