Hi, I'm a beginner so I'm sure the answers simple but I'm trying to make a code so when a button is pressed a system runs through once (lights up an LED). However when I press the button the system keeps running and lighting up the LED, even if I press the button again. Can someone please help?
int LED = 10;
int button = 2;
void setup()
{
pinMode(button, INPUT);
pinMode(LED, OUTPUT);
}
void loop()
{
int buttonstate;
buttonstate=digitalRead(button);
while (buttonstate==LOW)
{
digitalWrite(LED,HIGH);
delay(1000);
digitalWrite(LED,LOW);
delay(500);
}
}
const byte led = 10; // you should use const(constant) for your fixed ledpins/buttonpins
const byte button = 2; // the byte type is enough for the number of your pins
void setup()
{
pinMode(led, OUTPUT);
pinMode(button, INPUT_PULLUP); // use the internal pullup of your chip
// now your button state is HIGH
}
void loop()
{
byte buttonstate = digitalRead(button);
if (buttonstate == LOW) // when the button is pressed the buttonstate goes from HIGH to LOW
{
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(500);
}
}
So when you press the button once, the led goes on then off once
when you hold the button the led flashes nonstop until u let go of the button
connect your button:
pin two ------one leg of your button ------------ the other leg of your button ----arduino ground
( no resistors needed)
This is called input pullup(using the chip's internal resistor) (the button state is HIGH before you press the button)
Thanks for the help! I finally got it to work after using the code provided by siutoejai, and finally realizing that I had my button backwards... Thanks again.