I am new to arduino and programming and Im trying to make a basic program that has 2 buttons and 2 LEDS.
This is what I want to do:
If I press Button1, L1 is ON and goes to function next()
if I press Button2, L2 is ON with L1, waits 2 seconds then turns both off and returns to the beginning of the loop.
I have tried it and only L1 comes on when Button1 is pressed and goes to the next() function but doesnt turnon L2 when Button2 is pressed and the rest of the code.
Can anyone tell me whats wrong please?
int L1 = 13;
int stateofL1 = L1;
int L2 = 12;
int Green = 11;
int Button1 = 7;
int Button2 = 6;
void setup()
{
pinMode(L1, OUTPUT);
pinMode(L2, OUTPUT);
pinMode(Button1, INPUT);
pinMode(Button2, INPUT);
}
void loop()
{
int Press1 = digitalRead(Button1);
int Press2 = digitalRead(Button2);
if(Press1 == HIGH)
{
digitalWrite(L1, HIGH);
next();
}
}
void next()
{
int Press2 = digitalRead(Button2);
if(Press2 == HIGH)
{
digitalWrite(L2, HIGH);
delay(2000);
digitalWrite(L1, LOW);
digitalWrite(L2, LOW);
}
}
It is a question of speed. The software is running too fast to detect the change in button 2. Think about something that is executing in less than a microsecond and you will understand if you trace the logic of what you have done.
I pressed Button2 then 1, Nothing happened with 2 but with 1 L1 came on. Im not really sure why its not working. If I press button1, L1 comes on and should go to next() where it should wait for button2 to be pressed and carry out the statement then go back to the start of the loop. Ive literally started looking into C programming a few days ago and cant really see why its not working.
Where exactly do you think it is waiting? It starts next(), checks for button 2. If it is not on, exits next. As per previous message, think of the speed at which this is happening.
yeah, eventually I want a 9 button keypad that takes 4 digits, checks the code and turns on green light for right or red for wrong. with every digit an LED will come on in a row of 4.
My recommendation in that you should investigate finite ste machine and implement one for this assignment. You are going down a blind alley if you want to scale this to more buttons.
Im pulling my hair out trying to do something thats simple written down and Im not seeing how the code doesnt do what I want. Can someone have a look and see why this inst working. very frustrating.
int L1 = 13;
int L2 = 12;
int Button1 = 7;
void setup()
{
pinMode(L1, OUTPUT);
pinMode(L2, OUTPUT);
pinMode(Button1, INPUT);
Serial.begin(9600);
}
void loop()
{
int P1 = digitalRead(Button1);
do
{
Serial.print("press 1");
delay(3000);
}
while(P1 == LOW);
if(P1 == HIGH)
{
digitalWrite(L1, HIGH);
}
}
You get stuck in the loop still. The condition isn't the problem, its the code that is supposed to be executed for that while loop.
You can't have a while loop with a condition without any way for the program to leave it.