Help with two things at once

Hi I cant get this to work , trying to do two things at once with the millis function. Any help would be appreciated.

int led = 11; // the pin that the LED is atteched to int sensor = 2; // the pin that the sensor is atteched to int state = LOW; // by default, no motion detected int val = 0;

const int pResistor = A0; const int ledPin=9; int value;

long time1, time2;

void setup() { pinMode(led, OUTPUT); // initalize LED as an output pinMode(sensor, INPUT); // initialize sensor as an input Serial.begin(9600);

pinMode(ledPin, OUTPUT); pinMode(pResistor, INPUT);

time1=millis(); time2=millis(); }

void loop(){ if(millis()>time1) { value = analogRead(pResistor);

//You can change value "25" if (value > 500){ digitalWrite(ledPin, HIGH); //Turn led off } else{ digitalWrite(ledPin, LOW); //Turn led on time1 = millis()+30; }}

if(millis()>time2) { val = digitalRead(sensor); // read sensor value if (val == HIGH) { // check if the sensor is HIGH digitalWrite(led, HIGH); // turn LED ON delay(100); // delay 100 milliseconds

if (state == LOW) { Serial.println("Motion detected!"); state = HIGH; // update variable state to HIGH } delay (6000); } else { digitalWrite(led, LOW); // turn LED OFF delay(200); // delay 200 milliseconds

if (state == HIGH){ Serial.println("Motion stopped!"); state = LOW; time2 = millis() +35;

} } }}

delay (6000);

The whole point of the Blink Without Delay style is NOT to have any delays. As soon as you put one in there you blow the whole thing. Especially one this long.

BTW: Your handling of time will cause issues if the code runs for 49 days or more. This code can't handle millis resetting to zero. Study the Blink Without Delay example and see how to calculate the elapsed time with subtraction instead of trying to calculate the next time point with addition. The subtraction method makes the math immune to the rollover of millis.

In addition to the above, always use "unsigned long" for time variables.

The demo Several Things at a Time is an extended example of BWoD. It may help with understanding the technique.