In this small program, I was learning to connect buttons through breadboard and was using OR gate in the code. I learnt how to connect however I want to know that to Why connect ground resistor and the digital pins in the same button pin. And if I connect the digital pin to any other pin, either the led glows out of nowhere or the program doesn't work at all..
Code ~
const int button1 = 2; // the number of the pushbutton pin
const int button2 = 3;
const int ledPin = 13; // the number of the LED pin
// variables will change:
int state1 = 0; // variable for reading the pushbutton status
int state2 = 0;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop() {
// read the state of the pushbutton value:
state1 = digitalRead(button1);
state2 = digitalRead(button2);
if (state1 == HIGH || state2 == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
And if you want to know more than what @LarryD answered, search pull down and pull up resistors. Here you are adding a pull down.
If you were using a pull-up, you could use the built in resistor that your arduino UNO is offering and that’s activated just by setting the pin to INPUT_PULLUP instead of INPUT.
Ok So you mean that when I don't enter digitalRead in the code, it is grounded through the resistor and if I use digitalRead, it gets connected to the digital pin for that instance..
Thanks @paulpaulson@LarryD thanks for the help. I am taking a bit longer to understand cause I will just enter the 10th grade and using Arduino and all these components is new to me
I think that when we enter this code, the arduino will read the status of the button (Either High or Low) through the digital pin and then store the status in the variable state1
I watched some yt videos and now I think my concept is clear. So really the 5v and pin in front of it on the other side are always connected internally. When I press the button, 5v power also gets to the digital pins and so It reads a HIGH and because We don't want so much power so we remove the excess power through resistor and put it in the ground. Am I correct?
The 4 pin switch you show in the wiring image connects diagonal pins together when it is pressed (closed).
When the switch is open, the 10k resistor makes sure any voltage on the pin is discharged to GND. This is similar to you walking across a carpet and then discharging the static electricity in your body on a metal object (like a light switch).
This 10k resistor can be as high as 100k and more and still discharge the pins voltage.
When the switch is closed 5v will be on the pin and actually appear across the 10k resistor.
If you had a voltmeter, you would see 5v across this resistor.
As a side note, when we have 5v across the 10k resistor, the current through the resistor is: