Very Simple Motion Detector (SpinOff of Official Starter Kit's Project 05)

I have a photoresistor and a piezo, and I want the piezo only to sound once the photoresistor reaches a certain a value. Once it reaches that value I want the piezo to sound off continuously.

Right now when I run it, the piezo just sounds continuously. sensorValue is not changing either in the serial monitor. Here’s the relevant piece of the code–this is the part I spun off from the Project 05 code. Thanks for the help!

void loop() {
  sensorValue = analogRead(A0);
  Serial.print("Sensor Value: ");
  Serial.println(sensorValue);
  delay(1);
  if (sensorValue < 300) {
    TurnOn = 1;
  } //If the photoresistor is darkened, TurnOn = 1
  while (TurnOn = 1) {
    int pitch = map(sensorValue, sensorLow, sensorHigh, 50, 4000);
    tone(8, pitch, 20);
    delay(10);
  } //Once TurnOn = 1, the Piezo will start making noise
 
}

you never turn it off:

use a dead zone to create hysteresis:

pseudo code:

{
  sensorValue = analogRead(A0);
  Serial.print("Sensor Value: ");
  if(sensorValue < 300)
  {
    turnOn();
  }
  else if(sensorValue > 325)  // DeadZone of 25 Wide
  {
    turnOn();
  }
}
  while (TurnOn = 1) {
    int pitch = map(sensorValue, sensorLow, sensorHigh, 50, 4000);
    tone(8, pitch, 20);
    delay(10);
  } //Once TurnOn = 1, the Piezo will start making noise

This is what we call an infinite loop. First off, the condition (TurnOn = 1) doesn't check to see if TurnOn is 1, it sets TurnOn to 1 which is always true so this loop always runs no matter what. Gammon Forum : Electronics : Microprocessors : Arduino programming traps, tips and style guide see Trap #3.

But even when you get that fixed it still won't work. Once TurnOn is 1 and you enter that loop, nothing inside that loop ever changes TurnOn to any other value. So every time the while checks it will find that TurnOn still equals 1 and run this while loop again. None of your other code will ever be executed because you are trapped in this while loop running only the while loop over and over again until a value that's never going to change changes.