# Delay/Millis use

**URL:** <https://forum.arduino.cc/t/delay-millis-use/975217>\
**Category:** Programming\
**Created:** [March 30, 2022, 1:48pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217 "2022-03-30T13:48:14Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![hamza3745](https://avatars.discourse-cdn.com/v4/letter/h/ac91a4/32.png) [@hamza3745](https://forum.arduino.cc/u/hamza3745)\
**Post date:** [March 30, 2022, 1:48pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/1 "2022-03-30T13:48:14Z")

</div>

I've written a code for a robot that ''will chase rats''.  
The vehicle is moving using 2 DC motors and steers using a servo.  
Steering is achieved through specific pulse widths for each direction (1000 left,1500 straight,2000 right, etc.) For the steering to be maintained a 20ms period is needed.

The device is using a contact switch. When the switch is pressed the vehicle turns left or right and reverses for 500ms for example.

My question is the following:

Is it possible to move backward while steering (20ms period pulses) using a delay command?  
I had an argument about this and I was feeling sure that a 500ms delay cant be integrated into a program that has a repetitive action every 20ms.

\*In the uploaded code I am using a millis counter not a delay

void loop() {  
unsigned int numServo; // pulse control variables  
numServo=1500; // initialised to 1500 (straight ahead)  
timenow=millis();

// Set motors to maximum speed  
analogWrite(LeftSpeed, 255);  
analogWrite(RightSpeed, 255);

//Robot moves forward  
digitalWrite(R1, HIGH);  
digitalWrite(R2, LOW);  
digitalWrite(L1, HIGH);  
digitalWrite(L2, LOW);

//Reading the value of the infra-red sensors  
digitalRead(DRight);  
digitalRead(DLeft);

//Checking if the switch is pressed  
digitalRead(Switch);

//When the rodent is detected straight ahead  
if (DRight == HIGH && DLeft == HIGH)  
{

digitalWrite (Buzzer, HIGH);  
numServo=1500;  
}

//When the rodent is detected right  
if (DRight == HIGH && DLeft == LOW)  
{

digitalWrite (Buzzer, HIGH);

//Turn the robot 35degrees to the right  
numServo=1888;  
}

//When the rodent is detected left  
if (DRight == LOW && DLeft == HIGH)  
{  
digitalWrite (Buzzer, HIGH);  
//Turn the robot 35degrees to the left  
numServo=1112;  
}

//When no rodent is detected  
if (DRight == LOW && DLeft == LOW)  
{  
//Stop this annoying horn!  
digitalWrite (Buzzer, LOW);  
}

//If the switch hook is pressed again the wall, We hitted a wall!  
if (Switch == HIGH)  
{  
timecounter=millis();

//Setting a counter to allow us to count 0.5s while simiultanesly moving backwards and sending a pwm to the servo to turn right.  
//Using a delay function wouldn't allow us to execute both tasks at the same time.  
//As soon as the reverse turn is completed our vehicle will go straight forward at full speed (top code snippet\*)

while( (timenow-timecounter) \<500)  
{

// Let's move back right!

//Motors are moving the wheels backwards  
digitalWrite(R1, LOW);  
digitalWrite(R2, HIGH);  
digitalWrite(L1, LOW);  
digitalWrite(L2, HIGH);

// Set motors to maximum speed  
analogWrite(LeftSpeed, 255);  
analogWrite(RightSpeed, 255);

// Steering wheel turning the wheels to the right  
numServo=1888;

if(( timenow-timelast ) \>= 20) // need pulses to be every 20 +/- 5 ms  
{  
timelast=millis();// update last pulse time  
// then do servo pulse:  
digitalWrite(ServoPin,HIGH);  
delayMicroseconds(numServo);  
digitalWrite(ServoPin,LOW);  
}

}

}

if(( timenow-timelast ) \>= 20) // need pulses to be every 20 +/- 5 ms  
{  
timelast=millis();// update last pulse time  
// then do servo pulse:  
digitalWrite(ServoPin,HIGH);  
delayMicroseconds(numServo);  
digitalWrite(ServoPin,LOW);  
}  
}

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [March 30, 2022, 2:18pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/2 "2022-03-30T14:18:56Z")

</div>

> [@hamza3745](#):
>
> the uploaded code

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'  
  
Use [color = red] **code tags** [/color] (the \</\> icon above the compose window)&nbsp;to make it easier to read and copy for examination

> [@How to get the best out of this forum](https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum/679966):
>
> See also [FAQ - Arduino Forum](https://forum.arduino.cc/faq) for general rules on forum behavior and etiquette. Hello, Welcome to the Arduino Forum. This guide explains how to get the best out of this forum. Please read and follow the instructions below. Being new here you might think this is having rules for the sake of rules, but that is not the case. If you don’t follow the guidelines all that happens is there is a long exchange of posts while we try to get you to tell us what we need in order to help you, which is frus…

---

<div class="post-metadata">

**Author:** ![MicroBahner](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/microbahner/32/238923_2.png) [@MicroBahner](https://forum.arduino.cc/u/MicroBahner)\
**Post date:** [March 30, 2022, 2:21pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/3 "2022-03-30T14:21:32Z")

</div>

And don't post code snippets. Post the complete code that can be compiled.

Why don't you use a library to control your servo? Than you don't have to bother with the pulse creation in loop, what makes things much easier.  
[`servo.h`](https://www.arduino.cc/reference/en/libraries/servo/) is included in the IDE.

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [March 30, 2022, 2:22pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/4 "2022-03-30T14:22:14Z")

</div>

> [@hamza3745](#):
>
> I was feeling sure that a 500ms delay cant be integrated into a program that has a repetitive action every 20ms.

You are right if you are referring to a **delay()** because whilst the 500mS delay() is happening then a 20mS delay() can't be happening

However, using millis() for timing, you could have a 500mS period and a 20mS period happening at the same time with no interference between them

---

<div class="post-metadata">

**Author:** ![PaulRB](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/paulrb/32/216330_2.png) [@PaulRB](https://forum.arduino.cc/u/PaulRB)\
**Post date:** [March 30, 2022, 2:31pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/5 "2022-03-30T14:31:17Z")

</div>

> [@hamza3745](#):
>
> The vehicle is moving using 2 DC motors and steers using a servo

That's a strange design. Normally steering is achieved by varying the speed of the 2 DC motors and no servo is needed. The third "wheel" is normally just for stability and is not driven. Often it is just a captive ball bearing.

---

<div class="post-metadata">

**Author:** ![Perehama](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/perehama/32/256713_2.png) [@Perehama](https://forum.arduino.cc/u/Perehama)\
**Post date:** [March 30, 2022, 4:30pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/6 "2022-03-30T16:30:31Z")

</div>

```cpp
while ( (timenow - timecounter) < 500) {

```

You never exit this loop. Instead of calling timenow once in the beginning, and then having to track it throughout all the conditional branches, just call it as needed in-line.

```cpp
while ( (millis() - timecounter) < 500) {

```

This is actually "blocking" code as it will not do anything else until 500 milliseconds. It is better to write things inversed, so you do what you want when the 500 is up...

```cpp
if (millis() - intervalStart >= 500) {
  //do what has to be done.
}

```

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [March 30, 2022, 4:36pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/7 "2022-03-30T16:36:46Z")

</div>

Hi hamza,

If somebody would like to copy your code she/he has a **hard** job of exactly marking all characters  
needed. The users will jump over to **another users** post where copying is done with a **single** mouse-click.

There is a much more comfortable function for doing this.

## code-sections

> [@Make experienced users help: two ways to quickly post code as a code-section](https://forum.arduino.cc/t/make-experienced-users-help-two-ways-to-quickly-post-code-as-a-code-section/937298):
>
> Hi newcomer, This thread wants to show you how you can speed-up getting helpful answers with small effort. If you manage at least to post this way. You have the sympathy of the experienced users. If you are willing to invest another 20 minutes these 20 minutes extra-time will save you a minimum of 200 minutes to finish your project. always post your full sketch. As a code-section from the very first to the very last line A code-section has a small height =\> keeps your posting "short" but e…

This is an explanation how to use millis():

> [@Example-code for timing based on millis() easier to understand through the use of example-numbers / avoiding delay()](https://forum.arduino.cc/t/example-code-for-timing-based-on-millis-easier-to-understand-through-the-use-of-example-numbers-avoiding-delay/974017):
>
> non-blocking timing. Execute code only from time to time. There are a lot of different ways to learn programming. This thread wants to add another approach that is different to the yet existing ones. UPDATE 06.01.2023 if you are mainly interested in applying non-blocking timing you can do a quick read of this short tutorial / demonstration If you are intersted in understanding the details how it works go on reading here. I use an everyday analogon in this post to explain the basic principle …

Be the change you want to see in the world  
best regards Stefan

---

<div class="post-metadata">

**Author:** ![alto777](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/alto777/32/317385_2.png) [@alto777](https://forum.arduino.cc/u/alto777)\
**Post date:** [March 30, 2022, 4:52pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/8 "2022-03-30T16:52:27Z")

</div>

> [@PaulRB](#):
>
> That's a strange design.

Not that strange.

It's how cars work. ;-)

> **[Servo Powered Front Steering System For DIY RC Car Model Toy - AliExpress 26](https://www.aliexpress.com/item/1005001962537643.html)**
>
> Smarter Shopping, Better Living! Aliexpress.com

a7

---

<div class="post-metadata">

**Author:** ![anon73444976](https://avatars.discourse-cdn.com/v4/letter/a/439d5e/32.png) [@anon73444976](https://forum.arduino.cc/u/anon73444976)\
**Post date:** [March 30, 2022, 4:58pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/9 "2022-03-30T16:58:38Z")

</div>

> [@alto777](#):
>
> Not that strange.

It is fairly unusual to use 2 DC motors **and** servo steering.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [September 26, 2022, 4:58pm UTC](https://forum.arduino.cc/t/delay-millis-use/975217/10 "2022-09-26T16:58:58Z")

</div>

Closed on September 26, 2022, 4:58pm UTC

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
