Go Down

Topic: Oled multiple if statements (Read 278 times) previous topic - next topic

0miker0

I have an oled display working with two pushbuttons. When I have:
Code: [Select]

if(button_1 == HIGH)
{
 "Button_1 pressed"
 }

 if(button_2 == HIGH)
{
 "Button_2 pressed"
 }

 else
 {
  "Waiting"
 }


When I press button_1 I see it flash "Button_1 pressed" and "Waiting" flash over and over. Button_2 pressed just shows "Button_2 pressed". Pressing nothing just shows "Waiting"

When I have:

Code: [Select]

if(button_1 == HIGH)
{
 "Button_1 pressed"
 }

 else if(button_2 == HIGH)
{
 "Button_2 pressed"
 }

 else
 {
  "Waiting"
 }



Changing the 2nd "if" statement to "else if" makes it work fine. Why does the 2nd "if" statement have to be "else if"?



BulldogLowell

over 200 posts and you give us that code?

These are not the codes we are looking for....

PaulS

Quote
Why does the 2nd "if" statement have to be "else if"?
If one thing is pressed, print message 1.

If another thing is pressed, print message 2. If not, print message 3.

Can you see that that is not what you want? If nothing if pressed, what gets printed? If only the first thing is pressed, what gets printed? If only the second thing is pressed, what gets printed?

If one thing is pressed, print message 1. If not, if another thing is pressed, print message 2. If not, print message 3.

THAT is what an if/else if/else statement does. Can you see that they are different?

If not, consider this:

Code: [Select]
if(firstThingPressed)
{
    printMessageOne();
}
else
{
   if(secondThingPressed)
   {
      printMessageTwo();
   }
   else
   {
      printMessageThree();
   }
}


Which of your snippets does that resemble?

An else if statement isn't really a separate statement at all. It simply eliminates the need for a set of curly braces. The above snippet is exactly the same as:

Code: [Select]
if(firstThingPressed)
{
    printMessageOne();
}
else if(secondThingPressed)
{
   printMessageTwo();
}
else
{
   printMessageThree();
}
The art of getting good answers lies in asking good questions.


Go Up