Store a timestamp in IF

Hi!

I working whit hc-sr04 sensors whit a rtc ds1302 clock all mounted on an Arduino Mega, my idea is when the sensor detect an object, show me a timestamp(hh:mm:ss) and keep it, then when object out of range, the timestamp variable(called hourIn) return to 0.

I was using Static variables but whit no success, maybe Arrays but i don’t know how to use them here

Here’s my code

#include <DS1302.h>
#include <Time.h>
#include <TimeLib.h>
#define echoPin 12 // Echo Pin
#define trigPin 13 // Trigger Pin

time_t t = now();
DS1302 rtc(6,20,21);
Static String hourIn;

void setup()
{
  setTime(t);
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}



void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);  
    delayMicroseconds(2); 
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10); 
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

    
   if (distance <= 4) { 
	hourIn = rtc.getTimeStr();
	Serial.println(hourIn);
      	
    } 
   }
    else if (distance >= 5 || distance <= 0){
	Serial.println("Out of range");

    }
   
  delay(500);
}

I appreciate any help, thanks!

I think it easier to:

  1. detect the thing
  2. save the timestamp
  3. record in a bool isPresent = true.
  4. if the thing leaves the area, change isPresent to false

If you like, make the two variables Global

If you want to make them persistent if there is a power-loss, you can save them to EEPROM

time_t t = now();

If you think you know what time it is, why do you need to call this function with that time?

 setTime(t);

then when object out of range, the timestamp variable(called hourIn) return to 0.

Where do you make that happen? hourIn is a lousy name for a String variable that hold more than the hour that some event happened at.

BulldogLowell:
I think it easier to:

  1. detect the thing
  2. save the timestamp
  3. record in a bool isPresent = true.
  4. if the thing leaves the area, change isPresent to false

If you like, make the two variables Global

If you want to make them persistent if there is a power-loss, you can save them to EEPROM

Sounds good and i dont need them pesistent, only keep it in the loop when IF is correct. Now i am not home for testing

PaulS:
If you think you know what time it is, why do you need to call this function with that time?

Your right, i forgot delete them cuz the original code is too long

PaulS:
Where do you make that happen? hourIn is a lousy name for a String variable that hold more than the hour that some event happened at.

Really, when is Else lost their If timestamp and get current time again