Hey I'm new to Arduino and electronics. I have tried to use a switch/button for turning on and off an led, but it's not working. I have the anode of the led connected to pine 13 and the cathode to ground. I have 5v going to one side of my switch and the other side of the switch goes to pin 9. When I press the button pin 9 will be connected to 5v.
This is the code that I am using.
const int MAIN =9; //Swicth (button)
const int LED = 13; // LED
void setup() {
// put your setup code here, to run once:
pinMode(MAIN, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if ( MAIN == HIGH ) { //If Swicth is on
digitalWrite(LED, HIGH); // Turn on LED
}
else{
digitalWrite (LED,LOW); //Else turn led off.
You need a (>220ohm) resistor in series with the LED, otherwise you will burn out the LED or damage the pin.
You also need a (10k) pull up resistor between the switch-pin and 5volt.
Post a picture, so we can see what you're doing.
Leo..
You need a 220 Ω resistor in series with the LED.
You need a 10K resistor from pin 9 to GND.
You need to look for a LOW for a switch closer.
It’s best to use diagonal terminals with a switch like that.
First:
You can (I think) also don't use rhe pullup resistor, you can declare the button pin like a INPUT_PULLUP, and connect the button between pun and gnd. Of corse all the code relative the button is inverted (if now the level press button is HIGH, after it will be LOW)
Second:
About the programme there are many exampkes about how to light a led by pressing a button. You can also look at thoose. They are also in reference and examples.
Third:
If you need only light the led when button is pressed, and disactive the led when button is no pressed, you can also remive Arduino, and connect
5V
Button
Resistor
Led
gnd