简体   繁体   中英

true/false switch toggling back to zero

So I tried making a script, that switches the value of a boolean between true and false. For some reason, every time I press the connected button, the boolean value goes to one, but then immediately back to zero

bool on = false;

if(digitalRead(inputOn) == HIGH && on == false){
     on = true; 
     digitalWrite(outputLedGreen6, HIGH);
     Serial.print("OnStatus");
     Serial.println(on);
     delay(500);

  } else if(digitalRead(inputOn) == HIGH){
    on = false;
    digitalWrite(outputLedGreen6, LOW);
    Serial.print("OnStatus");
    Serial.println(on);
    delay(500);

  } 
bool on = false;

if(digitalRead(inputOn) == HIGH && on == false){
     on = true; 
     digitalWrite(outputLedGreen6, HIGH);
     Serial.print("OnStatus");
     Serial.println(on);
     delay(500);

  } 
  else if(digitalRead(inputOn) == HIGH ){ //CHANGE THIS LINE HERE
  //In the question, there was no else statement. Only 2 ifs. So whenever the first if statement executed, the second would also execute.

    on = false;
    digitalWrite(outputLedGreen6, LOW);
    Serial.print("OnStatus");
    Serial.println(on);
    delay(500);

  } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM