"if" command not working as it should

when running this code, it seems to work fine until it gets to the part where my If there is voltage detected in the correct button, then light correct LED. it will for some reason say there is, when there clearly isnt, i have tried it on the tinkercad sim aswell and gotten the same results.

const int blueLight = 12;
const int yellowLight = 11;
const int blueButton = 3;
const int yellowButton = 4;
const int greenLight = 8;
const int redLight = 7;


void setup() {
pinMode(yellowButton, INPUT);
pinMode(yellowLight, OUTPUT);
pinMode(blueButton, INPUT);
pinMode(blueLight, OUTPUT);
pinMode(greenLight, OUTPUT);
pinMode(redLight, OUTPUT);
randomSeed(analogRead(0));
Serial.begin(9600);
}

void loop() {
  digitalWrite(blueLight, LOW);
  digitalWrite(yellowLight, LOW);
  digitalWrite(redLight, LOW);
  digitalWrite(greenLight, LOW);
  
  int randNumber = random(2);
  int correctButton;
  int incorrectButton;

  Serial.print(randNumber);
  if (randNumber == 0) {
    digitalWrite(yellowLight, HIGH);
    correctButton = yellowButton;
    incorrectButton = blueButton;
  } 
  if (randNumber == 1){
    digitalWrite(blueLight, HIGH);
    int correctButton = blueButton;
    int incorrectButton = yellowButton;
  }
  Serial.print("correct button is ");
  Serial.print(correctButton);
  Serial.print("incorrect button is ");
  Serial.print(incorrectButton);
  while (true) {
    Serial.print(" 'while loop started'");
    if (digitalRead(correctButton == HIGH)) {
      digitalWrite(greenLight, HIGH);
      Serial.print(" 'correct button click'");
      break;
    }
    if (digitalRead(incorrectButton == HIGH)) {
      digitalWrite(redLight, HIGH);
      Serial.print(" 'incorrect button click'");
      break;
    }
    
  }
 delay(2000);
}

anyone know how to fix this???

I think should be

1 Like

omg your a lifesaver, thank you!!!

I don't see how this can be working properly even with the fix from @bobcousins.

if (randNumber == 1){ digitalWrite(blueLight, HIGH); int correctButton = blueButton; int incorrectButton = yellowButton; }

The incarnations of correctButton and incorrectButton in this if statement will not exist outside the if statement. They are not the same variables as the ones that are set when randNumber == 0.
Change it to:

if (randNumber == 1){ digitalWrite(blueLight, HIGH); correctButton = blueButton; incorrectButton = yellowButton; }

Pete

2 Likes

I did come across that issue when finalising the code, and fixed it as such.

Thanks for your help anyway
-Alex

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.