Sounding an alarm after minimum duration below threshold

Hello,

I am currently using some force sensitive resistors to sound an alarm when enough pressure is applied to them to make the input value < the threshold. The trouble is that I need them to do this only after the threshold has been met for 2 seconds. I am very new to coding and arduinos and I am having trouble figuring out how to achieve this. I would greatly appreciate any suggestions. Thank you.

Here is the relevant part of my current code

const int analogPin = A2; // pin that the sensor 1 is attached to
const int analogPin2 = A4; // pin that sensor 2 is attached to
const int threshold = 800;   // an arbitrary threshold level that's in the range of the analog input
const int threshold2 = 500;
int SPEAKER = 9;      // pin that speaker is attached to
int freq = 1800;  // speaker frequency

void setup() {
  // initialize the LED pin as an output:
  pinMode(SPEAKER, OUTPUT);
  // initialize serial communications:
  Serial.begin(9600);
}

void loop() {
  // read the value of the potentiometer:
  int analogValue = analogRead(analogPin);

  // if the analog value is low enough, buzz:
  if (analogValue < threshold) {
    tone(SPEAKER, freq);
    delay(400);
    noTone(SPEAKER);
    delay(100);
  }
  else {
    noTone(SPEAKER);
    
  }

The trouble is that I need them to do this only after the threshold has been met for 2 seconds.

You need to set a flag when the sensor value goes below the threshold and record the time. (Note that this is not the same as setting the flag and recording the time when the sensor value IS below the threshold).

Independently, see if the flag is set and has been set for long enough.

If the sensor value goes above (or is above works, too) the threshold, clear the flag and set the time to 0.

Think about boiling an egg. When you boil an egg, you wait for the water to boil, and then start a timer.

You start the timer when the water IS boiling but WAS NOT boiling previously. Otherwise you would look at the saucepan and say "hey, it's boiling! I'll reset the timer back to 3 minutes!".

Which, of course, would keep happening, until you ran out of water.

Nice analogy, but you wouldn't turn the timer off if the water stopped boiling, and reset it when the water started boiling again.