LDR and constantly lit LED -ideas?

//making this for a school project - first part of a bigger piece of code - stuck on this, the LED
stays on constantly and only seems to work when put the LDR in shade or sunlight then press reset.

int led = 13;
int lightLevel;

void setup() {
Serial.begin(38400);
pinMode (led, OUTPUT);

}

void loop() {
lightLevel = analogRead(A0);
Serial.print("Light Level: ");
Serial.println(lightLevel, DEC);
while (lightLevel>30) {digitalWrite(led, HIGH);} //how can I get this to poll continuously rather than
while (lightLevel<30) {digitalWrite(led, LOW);} //having to press reset?

}

if (lightlevel>30)
{digitalWrite(led,HIGH);}
else
{digitalWrite(led,LOW);}

Open the Serial Monitor, then change the light exposure sometimes, press Ctrl+A (to select ALL) and paste it here under CODE brackets.

What values are you getting? Are the values the expected?

This is what your code does:

  1. Read the light level.
  2. See if the variable lightLevel is above 30. It is because you haven't updated it. Yay. Go back to line 2.
  3. Go back to the start of the loop.

You never get to line 3 because line 2 is always true. A WHILE continues to loop forever until the condition becomes false. An IF, like Runaway Pancake says tests the condition, runs once and then moves on.

You can use a while if you really want, but you need to change it to this:
while( analogRead(A0) > 30 )
{
digitalWrite(led, HIGH);
}

cheers guys, will try

Better to change WHILE to IF

...R

cheers Runaway Pancake, that worked straight away