0

I'm trying to make a program that whenever a button is push, a different word will show on a lCD screen. However, it seems that the two buttons provide the same output ("Screen A"), it's like there is no difference between them, and I'm not sure what's the cause.

The code is very simple:

const int buttonPin1 = 13;     // the number of the pushbutton pin
const int buttonPin2 = 12;     // the number of the pushbutton pin

int buttonState = 0;   

long randNumber;

void setup() {


  for(int x=0; x<2; x++)
  {
    pinMode(buttonPin[x], INPUT); 
  }  

}
    void loop() {

      for(int x=0; x<2; x++)
      {
        buttonState = digitalRead(buttonPin[x]);

        if (buttonState == HIGH && buttonPin[x] == 13) {
          lcd.print("  Screen A ");
        }
        if (buttonState == HIGH && buttonPin[x] == 12) {    
          lcd.print("  Screen B ");
        }
      }

    }

Any help is appreciated

1
  • You are missing the definition of your buttonPin[] array.
    – Duncan C
    Commented Apr 26, 2019 at 15:55

1 Answer 1

1

I guess it's something with the circuit ... can you add it to your question.

Also, make sure buttonPin has the values 13 and 12 in the first and second index.

Btw, The following code is functionally identical:

void loop() 
{
    if (digitalRead(buttonPin[0]) == HIGH)
    {
       lcd.print("  Screen A ");
    }
    if (digitalRead(buttonPin[1]) == HIGH)
    {
       lcd.print("  Screen B ");
    }
}

If you want to have the loop and a flexible amount, use something like:

#define NR_OF_PINS 2

int buttonPins[NR_OF_PINS] = { 8, 9 };
String screens[NR_OF_PINS] = { "Screen A", "Screen B" };

void loop()
{
    for (int pin = 0; pin < NR_OF_PINS; pin++)
    {
        if (digitalRead(buttonPins[pin]) == HIGH)
        {
            lcd.print(screens[pin]);
        }
    }
}

Update

My answer is related to the code before you edited.

Remarks:

  • After your edited code, you forgot to declare buttonPin:

    int buttonPin[] = { buttonPin1, buttonPin2 };

  • You do not use long randNumber

  • Instead of a global variable int buttonState you can create it locally in the loop function (although you do not need it according to my code above).

    buttonState = digitalRead(buttonPin[x]);

  • Also, what you high likely want to add is button debouncing (check the arduino example about this), unless you add a delay after showing a screen of a considerable amount (like 100 ms or more).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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