Malfunctioning if statement

Hi there, I’m trouble with an if statement. My code is too long for pasting it here to be practical, but here’s a really simplified equivalent scenario.

int index = 0;
int Pressure = 0;
String myString;

void loop()
  index = myString.indexOf("trigger");

  if (Pressure == 0 && index > 0)
    Pressure = 100; 



Where myString is updated frequently in the other portion of the code, and the Indicator code just shows that the if statement was activated.
To me, this seems like it should run the first time that the keyword “trigger” is in myString, and then never again because the Pressure condition is no longer met.

However, what actually happens, according to that indicator (lets say its an LED), is that the if statement runs every single loop, regardless of what either the index or pressure is equal. Both of the conditions could be false and this if statement still runs for some reason.

Sorry for the unusual way of explaining that, it’s just not practical for me to paste my actual code because of length and complexity. If there’s anything I can explain better, let me know. Thanks in advance for the help!

If you paste your code in a code block (look for </> in the toolbar) it will automatically ‘windowize’ it so it’s at least browsable.

Actually your check for > 0 would not yield true when the string starts with trigger, you rather want to check for >= 0

Also the omitted code may well interfere with your subsequent checks, so you need to browse for any instance where Pressure could be reset to 0 or double check your indicator logic - maybe it’s just not reset when the condition is not met - at least the way how you indicate the met condition would be good to see :wink:

@HEng, I’ve reformatted the code block, but actually the preformatted text feature isn’t the right one to use for blocks of code. For these you’d use a line with ```cpp before the block of code and with ``` after (each by itself without any leading or trailing whitespace)

For more infor about the formatting features of Discourse (with which this forum is built) can be found here

1 Like

Alright, thanks guys. As far as the code goes, its ~1300 lines long (yeah I know, not the best practice, but anyway that’s how it is), so copying the whole thing down would be a little overkill.

However, turns out creating an analogy situation also wasn’t good! A buddy of mine looked at the code and found an extra semicolon, which obviously wasn’t in my analogy. So live and learn, I guess.

Thank you for your time and help!

1 Like