0

Basically I have three push buttons that correspond to pins 1 to 3 and want to set an efficient code that sets a certain variable into the index whose digitalRead is equal to one. Let us assume that only one button can be pressed at a time.

void loop()
    {
    if(digitalRead(1) == 1)                       
        {
        Variable = 1;            
        }
    if(digitalRead(2) == 1)                       
        {
        Variable = 2;              
        }
    if(digitalRead(3) == 1)                       
        {
        Variable = 3;  
        }
    }

Is there are more efficient way to do this, like for example using other loops?

I can't wrap around my head with doing this concept using the other loops such as for, do while, while and switch because the nature of the idea feels so unconventional for their uses.

4
  • 1
    "Efficient" is very subjective. Using a for loop will decrease code size, but increase execution time. Using discrete ifs like that will increase code size but decrease execution time.
    – Majenko
    Mar 2 at 14:20
  • What exactly is the role of the Variable in your code? Can the values be arbitrary, or are they pin numbers, or are they indices of the pressed buttons? You could use a for loop to go other an array of pins and assign the variable with the element of a second array. I'm not sure, what the actual goal is here, so it is difficult to suggest a good way.
    – chrisl
    Mar 2 at 14:23
  • 1
    And how is this question different from your previous one?
    – chrisl
    Mar 2 at 14:25
  • Okay it was pretty much the same, this one can be closed since you gave a good answer to the original question.
    – AndroidV11
    Mar 2 at 21:24
1

If you can only have one button pushed at a time, you can only end up with at most one of the if statements evaluate to true. In your code, you check button 2 and 3, even if button 1 is pressed. Your code can be a bit faster if you do this:

if(digitalRead(1) == 1)                       
{
  Variable = 1;            
}
else if(digitalRead(2) == 1)                       
{
  Variable = 2;              
}
else if(digitalRead(3) == 1)                       
{
  Variable = 3;  
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.