Sensor Turning off

Hi,

So for my project I want the sensor to turn off after it reaches a certain threshold. We have a tone playing from a speaker at a random frequency. It runs for 20 seconds, but I want the arduino to read the input from a thermistor, and if it falls below the threshold then the sound would turn off. But what is happening is that the sound is timing out, meaning its running for the full 20 seconds. And it only plays when it is above that threshold.

The code is attached, and any help and insight will be greatly appreciated

code_coupled_random_turn_off.ino (1.17 KB)

The attached code:

unsigned long time; //allows ot run the code for a long time
unsigned long runtime = 6000000; // runs for 1 minute
int frequency; 
int timedelay = 5000;
//int AR = analogRead(10);

void setup(){
  Serial.begin(9600);
  pinMode(6,OUTPUT); // 
  pinMode(10, INPUT); // the thermistor
  randomSeed(analogRead(9));
}

void loop()
{
  
  frequency = random(300, 3000); // randomize frequency 
  Serial.print("Time: ");
  time = millis(); //prints time since program started
  Serial.print(time); // wait a second so as not to send massive amounts of data
  Serial.print(',');
  Serial.print("Thermistor: ");
  Serial.print(analogRead(10));
  Serial.print(',');
  Serial.print("Frequency: ");
  Serial.println(frequency);
  delay(20000); // how long the sound plays for 
 
 
    if (runtime - time <= runtime)
  { noTone(12); // turn off tone 
    digitalWrite(6,LOW);
    delay(timedelay);// 3 seconds 
   }

   if  (analogRead(10)<=800)
      {
        noTone(12); // pin turn off due to sensor
        digitalWrite(6, LOW);
      }

   
    while (time > runtime)
    {
      noTone(12);
      digitalWrite(6,LOW);
    }
   
tone(12, frequency);
digitalWrite(6,HIGH);

}
  //delay(2000);

Let's make this line have a more accurate comment:

delay(20000); // how long the sound plays for AND how long we completely ignore the thermistor

If you want to be able to interrupt that tone, then you need to get all the delay calls out of the code and embrace the "Blink Without Delay" style of timing using millis()

Thank you, I am kind of new to this.

If I do this will it still allow me to randomize the time delay between the sounds?