Same code but different output in Arduino

Viewed 59

Recently i'm develop a program by using Arduino UNO. The code i write for two button is totally same but the output different.

Here is the code i write.

const int BUTTON1 = 6;
const int BUTTON2 = 7;
String i, j, x;

int ButtonState = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(BUTTON1, INPUT_PULLUP);
  pinMode(BUTTON2, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(BUTTON1) == LOW) {
    delay(500);
    i = "1";
    Serial.println(i);
  } 
  if (digitalRead(BUTTON2) == LOW) {
    delay(500);
    j = "2";
    Serial.println(j);
  } 
  else {
    delay(500);
    x = "0";
    Serial.println(x);
  }
}

When i keep pressing the button1, the output is 1 0 1 0 1 0 1 0

And when i keep pressing the button2, the ouput is 2 2 2 2 2 2 2

How can i make the output of button1 same with the output of button2?

1 Answers

How can i make the output of button1 same with the output of button2?

You are getting 1 0 1 0 1 0 1 0 for button 1 because first if and last else block will be executed each time when button1 is pressed.

Add else to second if.

if (digitalRead(BUTTON1) == LOW) {
    delay(500);
    i = "1";
    Serial.println(i);
  } 
  else if (digitalRead(BUTTON2) == LOW) {
    delay(500);
    j = "2";
    Serial.println(j);
  } 
  else {
    delay(500);
    x = "0";
    Serial.println(x);
  }
Related