About LED and LDR

So I'm starting up with my first serious project.
I want to light up a LED through processing and light it down with a LDR. I was able to do that, but when I put it on and after that off, I can't put the LED back on. How can I do this?
I hope you can help, this is my code:

char val;
int ledPin = 13;

int LDR = 0;
int LDRValue = 0;
int light_sensitivity = 300;

void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}

void loop() {

if (Serial.available())
{
val = Serial.read();
}
if (val == '1')
{
digitalWrite(ledPin, HIGH);
}

delay(10);

LDRValue = analogRead(LDR);
Serial.println(LDRValue);

while (LDRValue < light_sensitivity)

{
digitalWrite(13,LOW);

}

delay(100);

}

thanks in advance.

For the future please use the code button </> when posting code so it looks like this and is easy to copy to a text editor for reviewing

char val;
int ledPin = 13;

int LDR = 0;
int LDRValue = 0;
int light_sensitivity = 300;

void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    if (Serial.available())
    {
        val = Serial.read();
    }
    if (val == '1')
    {
        digitalWrite(ledPin, HIGH);
    }

    delay(10);

    LDRValue = analogRead(LDR);
    Serial.println(LDRValue);

    while (LDRValue < light_sensitivity)
    {
        digitalWrite(13,LOW);
    }
    delay(100);
}

I have also tidied up the layout to make it easier to read.

...R

Try replacing the WHILE with IF and see what happens. I suspect the WHILE does not end when you want it to.

I don't think the line delay(10); adds any value

...R

Thanks, didn't know about that.

@Robin2

I did that, but when I put my finger of the LDR, the LED gets back on, but I want it to stay off, so I can turn it on again through processing.

Please help!!

Lou1997:
I did that, but when I put my finger of the LDR, the LED gets back on, but I want it to stay off, so I can turn it on again through processing.

That sounds like you may have wiring problem.

Make a pencil drawing showing how you have everything connected and post a photo of the drawing.

Also, a "please help" reminder message after about 30 minutes is not appreciated. It would be reasonable after 48 hours.

...R

LDR connected to 5v and a0.

10k ohm resistor connected to a0 and GND.

And LED to pin 13.

IMG_7954[1].JPG

Have a look at the state change detection example (in the IDE, File, Examples, Digital). That will show how to do one thing if the light goes from bright to dim and different thing if the light goes from dim to bright.

You want your LDR to basically work as a toggle button, only detecting a change of state once until reset.
Look at button examples. Make it work with a button. Then the LDR wouldn't be any different.