"If" only being asked once?

Hey everyone,

I have made a simple program to test an idea I had but can't seem to work out this issue.

int testbutton = digitalRead(53);

void setup() {

  Serial.begin(9600);
}

void loop() {
  Serial.println("loop");
  delay (500);
  test();
}
void test(){
  Serial.println("test");
  delay (500);//(analogRead(GasLeakSens));
  Serial.println(testbutton);
  if (testbutton == HIGH){
  test();  
  }
}

The issue is, if the board is powered up with pin 53 high it will say its high regardless of its real life state. If its powered up low, it will say its low regardless of its state. I can only assume the "IF" is only being asked once.

Any ideas?

Thanks

I can only assume the "IF" is only being asked once.

You can, but you'd be wrong. The problem is that the variable only gets assigned a value once, so every time the if statement is evaluated, the result will always be the same.

You need to assign a new value to testbutton (is that a state or a pin number? Why isn't the name clear(er)?) on every pass through loop(), by calling digitalRead().

I imagine that calling:

int testbutton = digitalRead(53);

as a variable initialization will have indeterminate results since the function will be called before setup(). That’s where pin 53 should have been configured for input.

Its bad naming because it was only intended as a test.

So would I need to add

int buttonreadin = 0;

Followed by

void test(){
  Serial.println("test");
  delay (500);
  Serial.println(buttonreadin );
  buttonreadin = digitalRead (testbutton);
  if (buttonreadin = 1){
  test();  
  }
}

Something like that?

Something like that?

Only vaguely like that. You do NOT want a function calling itself like that. It hardly makes sense to print the value in buttonreadin and then assign buttonreadin a value.

I had it print it so I could check it was going high or not, and I'm calling itself again to create sort of a loop. I think I need to re-think the if exit strategy...

In your solution you might want to consider whether
  if (buttonreadin = 1){is actually doing what you want

I had it print it so I could check it was going high or not

But, don't you want to read first, and then print what you read?

You are printing yesterday's news, and then acting on today's news. So, your actions can seem strange.

Just a tip, if you're never changing testbutton, use #define testbutton instead of declaring it as a variable. Also,

UKHeliBob:
In your solution you might want to consider whether if (buttonreadin = 1) is actually doing what you want

He is right. A bit of help.

Are you saying that in the context of your code

  if (buttonreadin = 1)

is correct ?

“test()” is recusively calling itself and that may/will cause an endless loop:

void test(){
  Serial.println("test");
  delay (500);//(analogRead(GasLeakSens));
  Serial.println(testbutton);
  if (testbutton == HIGH){
  test(); <- This may/will cause the endless loop
  }
}