I don't understand the book explanation of this 10k resistor connecting the switch and ground.
This is my current code:
int switchState=0;
void setup(){
pinMode(2,INPUT); //switch
pinMode(3,OUTPUT); //green led
pinMode(4,OUTPUT); //red led
pinMode(5,OUTPUT); //red led
}
void loop(){
switchState=digitalRead(2);
//voltage on pin 2 =1
//no voltage on pin 2 =0;
if(switchState==0){
//no voltage on pin 2
digitalWrite(3,HIGH);
digitalWrite(4,LOW);
digitalWrite(5,LOW);
}
else{
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,HIGH);
}
}
With this 10k resistor attached, the device works as expected. Only green is lit when switch is not pressed, and only the two reds are lit when switch is pressed.
However, without the 10k resistor, all three LEDS are lit when the switch is not pressed. When the switch is pressed, the green stops being lit, but the two other red LEDS stay lit, though they become brighter.
So my question is... when the 10k is removed, why are the 3 LEDS lit when the switch is not pressed?