10sec delay without using delay() function

hello everyone i have been having some issues with delay() function. Your tutorial was very useful thanks. Am working on a traffic light with sensor . The sensing part is where am got stuck. I have this code that i want to rewrite without using delay() function

Basically, i wanted a delay before the LDR (photocell) sensor sense a car. if the delay is 10sec , and a car did not spend up to 10sec nothing should happen but if = 10sec turn pin 5 HIGH. your help will be highly appreciated .

1 to write the code without using delay () function
or
2 10secs timer without using delay () function

thanks here is my code

int sensorPin = A0;            // select the input pin for the ldr
unsigned int sensorValue = 0;  // variable to store the value coming from the ldr
int LDRLED  = 5;            // select the input pin for the ldr

void setup()
{
 pinMode(LDRLED, OUTPUT);
 //Start Serial port
 Serial.begin(9600);        // start serial for output - for testing
}

void loop()
{
 // read the value from the ldr:
 sensorValue = analogRead(sensorPin);     
 if(sensorValue<300)
 {
   delay (3000);
   sensorValue = analogRead(sensorPin);     
   if(sensorValue<300)
     digitalWrite(LDRLED, HIGH);       

 }
 else 
 {
   digitalWrite(LDRLED, LOW);   // set the LED off

 }
 //For DEBUGGING - Print out our data, uncomment the lines below
 Serial.print(sensorValue, DEC);     // print the value (0 to 1024)
 Serial.println("");                   // print carriage return  
 delay(500);  
}

Moderator edit: [code][/code] tags added. (Nick Gammon)

You don't want a delay at all. That is not what you are describing. What you want to do is measure when events occur, and determine if the difference between when two events happened is greater than some threshold.

Certain other events can render those times immaterial. For instance, a car stops at a red light. You'd notice that, and plan to cycle the light at some point in the future. But, between the car arriving and the time to cycle the light, a fire truck approaches. The time that the car stopped becomes immaterial. The fire truck/ambulance/police car has priority.

milllis() is typically the function to use to record when an event occurs.

Check out the blink without delay example and keep track of the time yourself using millis().

The demo several things at a time illustrates the use of millis() to manage timing without blocking. It is an extended example of BWoD.

...R

Thanks for your quick response guys I really appreciate. The purpose of the sensor is to control car overflow on road not to sense a car for go. The blink without delay() on the this site can't solve it. I am new in ardiuno so I have been stressing over it. Please any one can help me with x secs( 10secs) without delay () function will solve my problem. Thanks in anticipation :)

I think you are asking for a 10 second de-bounce so the car is not noticed until it has been sensed for 10 seconds.

its not pretty as it relies on the sensor being over 300 before it resets the timer but it should work

unsigned long previousMillis = 0;
unsigned long interval = 10000; //10 seconds
int sensorPin = A0;            // select the input pin for the ldr
unsigned int sensorValue = 0;  // variable to store the value coming from the ldr
int LDRLED  = 5;            // select the input pin for the ldr

void setup()
{
  pinMode(LDRLED, OUTPUT);
  //Start Serial port
  Serial.begin(9600);        // start serial for output - for testing
}

void loop()
{
  unsigned long currentMillis = millis();
  // read the value from the ldr:
  sensorValue = analogRead(sensorPin);
  if (sensorValue < 300) { //lower than 300 equals something sensed
    if (currentMillis - previousMillis >= interval) {//10 second timer
      digitalWrite(LDRLED, HIGH);//only turn on after 10 seconds
    }
  }
  else// sensor now reads over 300
  {
    digitalWrite(LDRLED, LOW);   // set the LED off
    previousMillis = currentMillis;//reset timer so its ready for the next time
  }

  //For DEBUGGING - Print out our data, uncomment the lines below
  //Serial.print(sensorValue, DEC);     // print the value (0 to 1024)
  //Serial.println("");                   // print carriage return
  // delay(500);
}

David, In case you didn't get it yet, to measure time in an Arduino sketch, you watch the milliseconds pass. At moment T0, let's say, the millis() function returns X. 10 seconds later than T0 is millis() + 10 * 1000.

Your code could look like this:

unsigned long lastMillis;

// set lastMillis when you want to start counting (button press etc);

void loop()
{
  if (millis() - lastMillis >= 10000L)
  {
     // 10 seconds passed;

     lastMillis = millis();
  }


}

Thank guys i cant just but thank you for your time. gpop1 “ the car is not noticed until it has been sensed for
10 seconds.” you are correct with the discription. i will test the code now i really appricaite. florinc thanks for the explanation . its very helpful.
tho my code ran well but the delay() function using the processor until its finished was my issue. That was why i was looking for a way to rewrite it without delay () function. am an electronic guru trying to update myself to microprocessor platform. LOVE ARDUINO IT MAKES JOB EASIER THAN ELECTRONICS IC JUNKS

trying to update myself to microprocessor platform

Hint: Think Arduino sketches as PLC ladder logic written in C.

:) WHAOOOOO just like magic gpop1 thanks very much you read my mind exactly what i was looking for . thanks a million times everyone . i will combine the sensor code with the traffic light code and lets see how it gose. thanks

thanks florinc. i studied electrnoic engineering i did abit of database and qbasics. Am just studying C language now. i found arduino very intresting. thanks for ur word of wisdom. “ Hint: Think Arduino sketches as PLC ladder logic written in C”

am spinning on a spot again .problem with mergging the codes together

hi guys here i come again please

How about helping people to help you by using the code button </> so your code looks like it does in Replies #6 and #7. Code does not have bullet points in it.

Doing it properly also makes it easy to copy to a text editor.

…R

i need help please . i have not really gotten the scope of other timing that’s y am have this issue
here is my full scope of work: i got the code online and am modifying it for better efficiency.

trafficLights1
trafficLights2
sensorPin1
sensorPin2

i got with where i wanted to introduce 10sec timer to the sensor before activating yellow (pin 3 ) then delay 3secs before the red (pin 2) comes up but is not working.

Please any help will be appriciated please

these are the lines the correction starts

void activateTrafficLight1(String lights, int pedestrians)

void activateTrafficLight2(String lights, int pedestrians)

here is my code :

 int trafficLights1[] = {
  2,3,4,5};   // red, yellow, green, pedestrians led pins
int trafficLights2[] = {
  6,7,8,9};   // red, yellow, green, pedestrians led pins

int sensorPin1 = A0;            // LDR sensor pin
int sensorPin2 = A1;            // LDR sensor pin
unsigned int sensorValue = 0;  // variable to store the value coming from the LDR
int LDRLED1  = 10;            //   indicator pin for the LDR
int LDRLED2  = 11;            //   indicator pin for the LDR

int situations = 4;
int duration[] = {
  8000,3000,10000,3000}; // duration of each situation
long previousCars = 0;
long previousPeds = 0;
unsigned long previousMillis = 0;
unsigned long interval_1 = 10000; //10 seconds
long interval_2 = 300;   //blink interval for pedestrians
int ledState = LOW;
int state;
int i = 0;

void setup()
{
  pinMode(LDRLED1, OUTPUT);

  for(int i = 0; i < 4; i++) {
    pinMode(trafficLights1, OUTPUT);
    pinMode(trafficLights2, OUTPUT);
  }
  Serial.begin(9600);
}

void loop() 

{   
  unsigned long currentMillis = millis();      
  if(currentMillis - previousCars < duration) {         
    situation(i);      
  } 
  else { 
    previousCars = currentMillis; 
    if(i >= situations) {
      i = 0;
    } 
    else {
      i++;
    }      
  }
}

void activateTrafficLight1(String lights, int pedestrians) 
{  unsigned long currentMillis = millis();

     // read the value from the ldr:
  sensorValue = analogRead(sensorPin1);     
  if(sensorValue<300)
      if (currentMillis - previousMillis >= interval_1) {//10 second timer

  
    digitalWrite(LDRLED1, HIGH); 
    digitalWrite(3, HIGH); 
    digitalWrite(2, HIGH); 
    digitalWrite(4, LOW); 


  }
  else 
  {
    digitalWrite(LDRLED1, LOW);   // set the LED off
    digitalWrite(3, LOW); 
    digitalWrite(2, LOW); 
    digitalWrite(4, LOW);
    
    previousMillis = currentMillis;//reset timer so its ready for the next time
  }
  {
    for(int x = 0; x < 3; x++) 
    {
      if(lights
== '0') state = LOW;

      if(lights
== '1') state = HIGH;

      digitalWrite(trafficLights1
, state);   

    }
    if(pedestrians == 1) {
      blinkPed(trafficLights1[3]);
    } 
    else {
      digitalWrite(trafficLights1[3], LOW);
    }
  }
}

void activateTrafficLight2(String lights, int pedestrians)
{   
  for(int x = 0; x < 3; x++)
  {
    if(lights
== '0') state = LOW;

    if(lights
== '1') state = HIGH;

    digitalWrite(trafficLights2
, state);

  }
  if(pedestrians == 1) {
    blinkPed(trafficLights2[3]);
  } 
  else {
    digitalWrite(trafficLights2[3], LOW);
  }
}

void situation(int i)
{
  switch(i){
  case 0: 
    activateTrafficLight1("100",1); // 100 means red ON, yellow OFF, green OFF
    activateTrafficLight2("001",0); // the second parameter is for pedestrians
    break;                     // 1 is ON and 0 is OFF
  case 1: 
    activateTrafficLight1("110",0); // 110: red ON, yellow ON, green OFF
    activateTrafficLight2("010",0);
    break;   
  case 2: 
    activateTrafficLight1("001",0);
    activateTrafficLight2("100",1);
    break;
  case 3:   
    activateTrafficLight1("010",0);
    activateTrafficLight2("110",0);
    break;   
  }
}

void blinkPed(int ped) {
  unsigned long currentMillis = millis();
  if(currentMillis - previousPeds > interval_2) {      
    previousPeds = currentMillis;      
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    digitalWrite(ped, ledState);
  }   
}

Hi.

You are declaring arrays, but you seem to forget to handle them as such. I am not sure that is what you are asking your question about (i'm sorry but its a bit hard to understand your question for me). But that is what most of the errors i'm seeing in the IDE are about. So have a look at the arrays, there's some [values in square brackets] missing.

There's an other error, complaining about comparing pointers and integers. That's about line 40, and that problem is also caused by the array you want to use. You even made the same [mistake] here, but without that [mistake], you can't do this that way. Also you seem to be comparing time with numbers of cars if i understand the names correctly. I can't imagine that to be what you want to do, so have a look at that too i'd say.

Next error is the use of ' and ". Those are off, should use the correct type. The involved lines here are: 84, 87, 107 and 110.

After correcting all of these, the sketch will compile. Still i'm wondering if it will do what you expect it to do.

DELETED

Thanks for your quick response Vaclav and MAS3. i have written the code with delay () function before i knew delay () will take the whole processor and wont allow any thing to function until the time elapse that why i had to look for way out. The code below was giving to me yesterday on the forum IT WORKED PERFECTLY. But i couldn’t merge it with the main code because am not really getting the new time forma am a newbie.
please if this code could be merge with my main code that would be all. thanks for your time

i have introduced 2 LDR each on trafficLights1 and trafficLights2 to sense trafic overflow ut the ldr should delay 10 secs before turning on yellow light (3) then wait 3secs before redlight (2) comes up thats the main scope of the project

sensorPin1
sensorPin2

MAS3 maybe i messed with the code here is the code without any changes
please i really need help. thanks

MAIN CODE

int trafficLights1[] = {2,3,4,5};	// red, yellow, green, pedestrians led pins
int trafficLights2[] = {6,7,8,9};	// red, yellow, green, pedestrians led pins
int situations = 4;
int duration[] = {8000,3000,10000,3000}; // duration of each situation
long previousCars = 0;
long previousPeds = 0;
long interval = 300;	//blink interval for pedestrians
int ledState = LOW;
int state;
int i = 0;

void setup()
{
  for(int i = 0; i < 4; i++) {
	  pinMode(trafficLights1[i], OUTPUT);
	  pinMode(trafficLights2[i], OUTPUT);
  }
	Serial.begin(9600);
}

void loop()
{	
	unsigned long currentMillis = millis();		
	if(currentMillis - previousCars < duration[i]) {			
		situation(i);		
	} else { 
		previousCars = currentMillis; 
		if(i >= situations) {
			i = 0;
			} else {
			i++;
		}		
	}
}

void activateTrafficLight1(String lights, int pedestrians) 
{	
	for(int x = 0; x < 3; x++) 
	{
		if(lights[x] == '0') state = LOW;
		if(lights[x] == '1') state = HIGH;
		digitalWrite(trafficLights1[x], state);	
	}
	if(pedestrians == 1) {
		blinkPed(trafficLights1[3]);
	} else {
		digitalWrite(trafficLights1[3], LOW);
	}
}

void activateTrafficLight2(String lights, int pedestrians)
{	
	for(int x = 0; x < 3; x++)
	{
		if(lights[x] == '0') state = LOW;
		if(lights[x] == '1') state = HIGH;
		digitalWrite(trafficLights2[x], state);
	}
	if(pedestrians == 1) {
		blinkPed(trafficLights2[3]);
	} else {
		digitalWrite(trafficLights2[3], LOW);
	}
}

void situation(int i)
{
	switch(i){
		case 0: 
			activateTrafficLight1("100",1); // 100 means red ON, yellow OFF, green OFF
			activateTrafficLight2("001",0); // the second parameter is for pedestrians
			break;							// 1 is ON and 0 is OFF
		case 1: 
			activateTrafficLight1("110",0); // 110: red ON, yellow ON, green OFF
			activateTrafficLight2("010",0);
			break;	
		case 2: 
			activateTrafficLight1("001",0);
			activateTrafficLight2("100",1);
			break;
		case 3:	
			activateTrafficLight1("010",0);
			activateTrafficLight2("110",0);
			break;	
	}
}

void blinkPed(int ped) {
	unsigned long currentMillis = millis();
	if(currentMillis - previousPeds > interval) {		
		previousPeds = currentMillis;		
		if (ledState == LOW)
		ledState = HIGH;
		else
		ledState = LOW;
		digitalWrite(ped, ledState);
	}	
}

if this code can be merged with the above thats what am looking for . please help

unsigned long previousMillis = 0;
unsigned long interval = 10000; //10 seconds
int sensorPin = A0;            // select the input pin for the ldr
unsigned int sensorValue = 0;  // variable to store the value coming from the ldr
int LDRLED  = 5;            // select the input pin for the ldr

void setup()
{
  pinMode(LDRLED, OUTPUT);
  //Start Serial port
  Serial.begin(9600);        // start serial for output - for testing
}

void loop()
{
  unsigned long currentMillis = millis();
  // read the value from the ldr:
  sensorValue = analogRead(sensorPin);
  if (sensorValue < 300) { //lower than 300 equals something sensed
    if (currentMillis - previousMillis >= interval) {//10 second timer
      digitalWrite(LDRLED, HIGH);//only turn on after 10 seconds
    }
  }
  else// sensor now reads over 300
  {
    digitalWrite(LDRLED, LOW);   // set the LED off
    previousMillis = currentMillis;//reset timer so its ready for the next time
  }

  //For DEBUGGING - Print out our data, uncomment the lines below
  //Serial.print(sensorValue, DEC);     // print the value (0 to 1024)
  //Serial.println("");                   // print carriage return
  // delay(500);
}

thanks very much.

Hi.

If you're now asking for someone to do the work for you, i won't do that. What would you learn from that, and how would you do it the next time when you run in some similar problem ?

For some reason, you went from a 70 line code which seems to be inspired from the "blink" example, to a code that is twice as large, and now suddenly uses arrays and strings for no good reason i can think of. Those need to be handled correctly, and that's not happening here.

Did you make this code, or is it something that was handed to you or that you found somewhere ?

If you're new with coding, forget arrays for a while. You've shown you're not there to use arrays and strings. You certainly don't need them for this sketch. Keep it simple for now, so you can read and understand your own code.

if you are use to ladder logic then you may be more comfortable ignoring timers and just make a single timer that acts as a counter. If the counter was one per second then you should be able to use that with out getting complicated

 unsigned long currentMillis = millis();//one second into timers
  if(currentMillis - previousMillis > 1000L) {
      timer_1++;
      timer_2++;
      timer_3++;
       previousMillis = currentMillis;}//this makes a one second timer
       //every second timer is increased by one
       
       switch (timer_1){
         case 10:
         //at 10 seconds i do this
         break;
     case 25:
         //at 25 seconds i do this
         break;
         case 32:
         //at 32 seconds i do this
         break;
         case 60:
         //at 60 seconds i do this then i can reset the timer here
         timer_1=0;//or i can place this somewhere else
         break;
         
         //i can also use ifs like
         
         if (timer_2 <=10){
           //do this
         }
         
         //decied when to reset the timer to 0 or force the timer to remain set by using a 
         //number larger than the if. so timer_2==20 then the if is locked in until reset

funny thing is once you get use to doing this you will understand the concept of timing