Boolean not being updated?

Hello, I'm currently using a simple sketch with a HC-SR04 sensor and i'm currently stuck on this specific event; (I am using the newping library but I don't think it matters)

The sensor is reading 5 times per second the distance, when a certain distance is met, it has to make an action, then it has to wait until the object gets away from the detection range, I've seen other similar threads and they said a boolean could help, I'm new on Arduino and I tried, but unfortunately this doesn't seem to work, here's the code:

#include <NewPing.h>
#define TRIGGER_PIN  9
#define ECHO_PIN     10
#define MAX_DISTANCE 50

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

unsigned long timeSince = millis();
unsigned long holdFor = 300;

void setup() {
  Serial.begin(115200);
}

void loop() {
  bool isDetected = 0;
  delay(200);
  unsigned int uS = sonar.ping();
  unsigned int distance = sonar.convert_cm(uS);

  if ( distance > 8 )
  {
    Serial.println("Target absent, waiting.");
    timeSince = millis();
    isDetected = 0;
  }
      

  if ((distance > 3) && (distance < 7))
  {
    Serial.println("Target Detected."); // Cool, it's within range, now let's wait until the target actually stops, i'll wait for .3s that the target is still before proceeding.
    if ( (millis() - timeSince >= holdFor) && (isDetected = 0) )
    {
      Serial.println("Target is still, executing Action");
      // Action, LED will turn on, but not coded yet
      // Will wait until the target gets off before looping again.
      isDetected = 1;
    }
  }
 }

I've added several prints to the serial monitor to check the situation and it seems to be stuck in target detected/out of range, essentially it doesn't proceed to the action part. May it be related because the boolean is not updated?

I know it might be a silly mistake :smiley:
Best regards

Welcome

This bool isDetected = 0; should be static bool isDetected = 0;

This (isDetected = 0) should be (isDetected == 0)

You should use true and false instead of 1 and 0

Hello and thank you! It has solved the issue :slight_smile: