How do i add a button to my arduino code so when i press it it will change to another code?
int pinled1 = 12;
int pinled2 = 11;
int pinled3 = 10;
int pinled4 = 9;
int tim = 50;
void setup()
{
pinMode(pinled1, OUTPUT);
delay(50);
pinMode(pinled2, OUTPUT);
delay(50);
pinMode(pinled3, OUTPUT);
delay(50);
pinMode(pinled4, OUTPUT);
delay(50);
}
void loop()
{
digitalWrite(pinled1, LOW);
delay(tim);
digitalWrite(pinled1, HIGH);
delay(tim);
digitalWrite(pinled2, LOW);
delay(tim);
digitalWrite(pinled2, HIGH);
delay(tim);
digitalWrite(pinled3, LOW);
delay(tim);
digitalWrite(pinled3, HIGH);
delay(tim);
digitalWrite(pinled4, LOW);
delay(tim);
digitalWrite(pinled4, HIGH);
delay(tim);
digitalWrite(pinled1, LOW);
delay(tim);
digitalWrite(pinled1, HIGH);
delay(tim);
digitalWrite(pinled2, LOW);
delay(tim);
digitalWrite(pinled2, HIGH);
delay(tim);
digitalWrite(pinled3, LOW);
delay(tim);
digitalWrite(pinled3, HIGH);
delay(tim);
digitalWrite(pinled4, LOW);
delay(tim);
digitalWrite(pinled4, HIGH);
delay(tim);
}






























Visit Our Store »
Go Pro Today »




int pinled1 = 12;
int pinled2 = 11;
int pinled3 = 10;
int pinled4 = 9;
int button1 = whatever pin you want it on;
int button2 = whatever pin you want it on;
int buttonstate1 = 0; // this variable will change
int buttonstate2 = 0; // this variable will change
int tim = 50;
void setup()
{
pinMode(pinled1, OUTPUT);
delay(50);
pinMode(pinled2, OUTPUT);
delay(50);
pinMode(pinled3, OUTPUT);
delay(50);
pinMode(pinled4, OUTPUT);
delay(50);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop()
{
buttonstate1 = digitalread(button1);
buttonstate2 = digitalread(button2);
if (buttonstate1 == HIGH){
while(buttonstate2 == LOW)
{
buttonstate1 = digitalread(button1);
buttonstate2 = digitalread(button2);
//put your led pattern here
}}
else if (buttonstate2 == HIGH){
while(buttonstate1 == LOW)
{
buttonstate1 = digitalread(button1);
buttonstate2 = digitalread(button2);
//put second led pattern here
}}}
You could shorten it up by making a "check buttons" subroutine. Also, why did you put delays after you set the pins to input or out put? The code may not be completely right(a few semi-colons or brackets missing)
if you have any other questions, just let me know
Thank you for select my answer for best answer!
L