Im trying to write a sketch in which I use an LDR and an LED. What Im trying to accomplish is when the LED turns on in front of the LDR, the variable s1 stores the time it happens and when the LED turns off s2 stores that time. The program doesnt work when run as it is but when I use the Serial.print() section at the bottom or use a delay, the program runs properly. I dont understand the reason ...plz someone help me.
here is the sketch:
const int sense=1;
int scan, oldscan, permit1, permit2;
unsigned long s1, s2;
void setup()
{
Serial.begin(9600);
oldscan = analogRead(sense);
}
void loop()
{
scan = analogRead(sense);
if(scan - oldscan > 300 && permit1 == 0)
{
s1 = millis();
permit1 = 1;
permit2 = 0;
Serial.print("s1=");
Serial.println(s1);
}
if(oldscan - scan > 300 && permit2 == 0)
{
s2 = millis();
permit2 = 1;
permit1 = 0;
Serial.print("s2=");
Serial.println(s2);
}
oldscan = scan;
// delay(500);
/* Serial.print("scan=");
Serial.println(scan);
Serial.print("oldscan=");
Serial.println(oldscan);
Serial.print("permit1=");
Serial.println(permit1);
Serial.print("permit2=");
Serial.println(permit2); */
}