Light Sensor Code Help

I'm programming very basic circuit that uses a photoresistor and an LED. When the photoresistor senses no light from the led, it records the arduino's millisecond count to a variable (time). When the sensor receives light from the LED it figures out the time that the sensor was blocked by taking the current millisecond count from the variable 'time'.

Currently, there is an issue somewhere after the }else{

// I/O pins 
const int sensorPin = 0; //Photoresistor - Analog Pin 0
const int ledPin = 13; // Led - Digital Pin 13 

int sensorState = 0; //current state of the photoresistor
int threshold = 300; // controls the sensitivity of triggering the sensor
unsigned long time; 

void setup(){
  pinMode(ledPin, OUTPUT); //sets the led pin to output
  digitalWrite(ledPin, HIGH); //turns on led
  Serial.begin(9600); 
  delay (100);
}
void loop(){ 
 if (sensorState == 0){
  if (analogRead(sensorPin) < threshold){ //if sensor is blocked
   time = millis();
   sensorState = 1;

[glow]}else{ // the error in the code is somewhere after this [/glow]
 if (sensorState == 1){
  if (analogRead(sensorPin) > threshold){ //if sensor is not blocked
  time = millis () - time;
  Serial.println("Calculating Data...Please Wait");
  delay (3000); //this delay has no purpose
  Serial.println (time, DEC);  
  sensorState = 0;
  Serial.println("Ready");
}}
 }}}

When fixed, it should look something like this on the serial monitor:

Ready
Calculating Data...Please Wait
(#of millis.)
Ready

Thanks,
duemilanove

The way you wrote the code, once the sensorState becomes == 1 it is not possible to execute any code because everything is wrapped inside a:

if (sensorState == 0)
{
    . ..
}

Try This:

// I/O pins
const int sensorPin = 0; //Photoresistor - Analog Pin 0
const int ledPin = 13; // Led - Digital Pin 13

int sensorState = 0; //current state of the photoresistor
int threshold = 300; // controls the sensitivity of triggering the sensor
unsigned long time;

void setup()
{
  pinMode(ledPin, OUTPUT); //sets the led pin to output
  digitalWrite(ledPin, HIGH); //turns on led
  
  Serial.begin(9600);
  delay(100);
}

void loop()
{
 if (sensorState == 0 && analogRead(sensorPin) < threshold)
 {
     time = millis();
     sensorState = 1;
 }
    
 if (sensorState == 1 && analogRead(sensorPin) > threshold)
 {
    time = millis () - time;
    Serial.println("Calculating Data...Please Wait");
    delay (3000); //this delay has no purpose
    Serial.println (time, DEC);  
    sensorState = 0;
    Serial.println("Ready");
 }
}

Thanks a bunch for you help, BobTheBuilder! :slight_smile: It all works out fine now!