I am connecting the switch on the arduino like this:
When the switch is closed, the led maintain its state.
When the switch is open the led starts changing states reaaaly fast.
So I'm not really sure of how I should connect the switch on the arduino,
or if I'm connecting the pullup resistor correctly, or if I'm programming it incorrectly.
(I have already tried connecting the resistor between the switch and pin4 -> led still blinks like crazy)
Someone has a suggestion on what I'm doing wrong?
Also, I think this is a General Eletronics question, not a programming one. Not sure though
The resistor needs to pull-up - your circuit shows the resistor in-line with the switch - it's not doing much there, the input
will "float" when the switch is open, and it will pick up noise from all the nearby circuitry (and your fingers).
You connect the switch between input pin and ground, the resistor between input pin and +5V. When the switch is open
the resistor pulls the pin to 5V, when the switch is closed it pulls the pin down to 0V.
A physical resistor is not actually needed as the Arduino pins have a pull-up mode:
// in newer Arduino versions:
pinMode (pin, INPUT_PULLUP) ;
// equivalent to
pinMode (pin, INPUT) ;
digitalWrite (pin, HIGH) ; // enables internal pull-up when pin is an input
Switch toggle code that should not require a resistor. Put switch between pin 5 and ground.
/zoomkat servo-LED button toggle test 11-12-2012
#include <Servo.h>
int button = 5; //button pin, connect to ground to move servo
int press = 0;
Servo servo;
boolean toggle = true;
void setup()
{
pinMode(13, OUTPUT); //LED on pin 13
pinMode(button, INPUT); //arduino monitor pin state
servo.attach(7); //pin for servo control signal
digitalWrite(5, HIGH); //enable pullups to make pin high
}
void loop()
{
press = digitalRead(button);
if (press == LOW)
{
if(toggle)
{
digitalWrite(13, HIGH); // set the LED on
servo.write(160);
toggle = !toggle;
}
else
{
digitalWrite(13, LOW); // set the LED off
servo.write(20);
toggle = !toggle;
}
}
delay(500); //delay for debounce
}