# Using millis() as timer with ultrasonic sensor

**URL:** <https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247>\
**Category:** Programming\
**Created:** [November 1, 2018, 11:23am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247 "2018-11-01T11:23:13Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![UserArduino](https://avatars.discourse-cdn.com/v4/letter/u/9de053/32.png) [@UserArduino](https://forum.arduino.cc/u/UserArduino)\
**Post date:** [November 1, 2018, 11:23am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/1 "2018-11-01T11:23:13Z")

</div>

Hi guys !

I'm a beginner and I recently wrote a code using millis. This program supposedly needs to print the signal " cut tape" only when the result of the ultrasonic sensor is less than 30 cm for 5 seconds. However, once I ran the program, it stills prints " Cut tape" even though it the period haven't reach 5 secs.

Can anyone help me to solve the issue ?

This is my code. Ignore the codes for servo for now as it is in development mode. Thank you.

const unsigned long period= 5000;// init period=5000.  
int trigPin = 13; // Trigger  
int echoPin = 12; // Echo  
long duration, cm, inches;  
unsigned long startMillis; //some global variables available anywhere in the program  
unsigned long currentMillis;

#include \<Servo.h\>

Servo myservo; // create servo object to control a servo  
// twelve servo objects can be created on most boards

int pos = 0; // variable to store the servo position

void setup() {  
myservo.attach(9); // attaches the servo on pin 9 to the servo object  
//Serial Port begin  
Serial.begin(9600);  
//Define inputs and outputs  
pinMode(trigPin, OUTPUT);  
pinMode(echoPin, INPUT);  
startMillis= millis();  
}

void loop() {  
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.  
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:  
//pinMode(trigPin, OUTPUT);  
digitalWrite(trigPin, LOW);  
delayMicroseconds(10);  
digitalWrite(trigPin, HIGH);  
delayMicroseconds(10);  
digitalWrite(trigPin, LOW);

// Read the signal from the sensor: a HIGH pulse whose  
// duration is the time (in microseconds) from the sending  
// of the ping to the reception of its echo off of an object.  
pinMode(echoPin, INPUT);  
duration = pulseIn(echoPin, HIGH);

// Convert the time into a distance  
cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343  
Serial.print(cm);  
Serial.print("cm");

while( cm \< 30)  
{ here: currentMillis= millis();  
if((currentMillis-startMillis)\<period )  
{ goto here;}// less than 5s jump to 'here'.  
else if(( currentMillis-startMillis )== period)  
{ Serial.print(" Cut tape"); }

startMillis = currentMillis;// to save the latest time so can get the diff when looping again.  
//delay(50);  
break;  
}

delay(150);  
}

---

<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:** [November 1, 2018, 11:36am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/2 "2018-11-01T11:36:25Z")

</div>

```cpp
  while( cm < 30)

```

It is extremely unlikely that you want a while statement here. I think that each time through loop() you need to measure the distance again, and do something IF cm less than 30.

You should read up on scope, and minimize the use of global variables, especially ones that you never use (like inches).

You should use meaningful names. currentMillis? If someone asks you what time it is, do you look at your watch and say "The current second is ..."? Or, do you say "It is now ..."?

startMillis is supposed to hold the time that some event occurred. Why not name the variable for the event that was supposed to have occurred?

The code you posted hasn't a hope in hell of compiling. If you are going to annotate your code to describe what is happening, use comments, so that the code can still be compiled.

Try again to explain what is supposed to trigger the "Cut tape" message to be printed. It sounds like the measured distance needs to be below 30 cm for 5 continuous seconds before that message is triggered.

If that is the case, you need to define what should happen if the distance goes about 30 before the 5 seconds has elapsed.

If the distance just needs to drop below 30 for message to be printed, but the message should be printed 5 seconds after that happens, then the code would be very different from that to print the message if the distance is less than 30 for 5 seconds.

---

<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:** [November 1, 2018, 11:44am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/3 "2018-11-01T11:44:07Z")

</div>

Why are you using goto ?  
In doing so you have created a while loop so why not use while in the first place if that is what you want ?

```cpp
   else if (( currentMillis - startMillis ) == period)

```

Do not test for equality here, use \>= to avoid any problem if something causes the equality to be missed

```cpp
 while ( cm < 30)

```

Will the value of cm ever change in this while loop ? Answer, no, so why test its value

Why are cm and inches declared as long ? What range of values do you expect to hold in the variables ?

---

<div class="post-metadata">

**Author:** ![UserArduino](https://avatars.discourse-cdn.com/v4/letter/u/9de053/32.png) [@UserArduino](https://forum.arduino.cc/u/UserArduino)\
**Post date:** [November 3, 2018, 8:43am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/4 "2018-11-03T08:43:06Z")

</div>

> PaulS:
> 
> ```arduino
>   while( cm < 30)
> 
> ```
> 
> Try again to explain what is supposed to trigger the "Cut tape" message to be printed. It sounds like the measured distance needs to be below 30 cm for 5 continuous seconds before that message is triggered.

Hi PaulS and UKHelibob, I actually wanted to do what you said previously, which is measured distance needs to be below 30 cm for 5 continuous seconds before that message is triggered. So, I need to use the while loop to ensure that the reading from ultrasonic sensor is 30 cm continuously for 5s before the message "Cut Tape" is printed. Supposedly, if it is less than 30cm for the period of lesser than 5s, it jumps back to 'here' to ensure the reading is less 30 cm for 5s. If the reading goes greater than 29cm, it exits the while loop altogether.

"If that is the case, you need to define what should happen if the distance goes about 30 before the 5 seconds has elapsed."

Can you guys suggest any codes to implement this ? It seems to work but I as I said earlier I need to eliminate the "Cut tape" message being printed out if the reading is not continuously less than 30cm for period of 5s.

I used a library for ultrasonic sensor which used long for cm and inches, I will change it to appropriate length later.

Thank you !

---

<div class="post-metadata">

**Author:** ![Robin2](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robin2/32/216045_2.png) [@Robin2](https://forum.arduino.cc/u/Robin2)\
**Post date:** [November 3, 2018, 10:01am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/5 "2018-11-03T10:01:53Z")

</div>

> UserArduino:  
> when the result of the ultrasonic sensor is less than 30 cm for 5 seconds.

The way to do that is like this pseudo code

```arduino
if (distance > 30) {
  lastLongMeasureTime = millis(); // reset the clock if the distance is too great
}

if (millis() - lastLongMeasureTime >= 5000) {
    // distance has been under 30 for a full 5 seconds
    // do stuff
}

```

...R

---

<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:** [November 5, 2018, 12:40pm UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/6 "2018-11-05T12:40:10Z")

</div>

> Can you guys suggest any codes to implement this ?

Implement what? Re-read your post, and see if you can figure out what "this" is?

Where are the answers to ALL of the questions that you've been asked? We can NOT see your project, so we can't help you structure your code correctly with nothing more than vague hand-waving requirements. And, you are not helping clarify the requirements.

---

<div class="post-metadata">

**Author:** ![UserArduino](https://avatars.discourse-cdn.com/v4/letter/u/9de053/32.png) [@UserArduino](https://forum.arduino.cc/u/UserArduino)\
**Post date:** [November 13, 2018, 5:57am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/7 "2018-11-13T05:57:37Z")

</div>

> PaulS:  
> Implement what? Re-read your post, and see if you can figure out what "this" is?
> 
> Where are the answers to ALL of the questions that you've been asked? We can NOT see your project, so we can't help you structure your code correctly with nothing more than vague hand-waving requirements. And, you are not helping clarify the requirements.

Hi PaulS,

So this is really what I'm trying to do.

1. I'm using an ultrasonic sensor to detect the presence of a box. The box will be on a conveyor belt. I expect it takes 5 secs to pass the ultrasonic sensor. Thus, I thought that when the ultrasonic reading is less than 30 cm for a continuous period of 5 secs , it means that there is a presence of a box. So when the statement of ( ultrasonic reading is less than 30 cm for a continuous period of 5 secs) is TRUE, the message " Cut the tape" should be displayed.

2. If the statement of ( ultrasonic reading is less than 30 cm for a continuous period of 5 secs) is FALSE, the message " Cut the tape" should not be displayed.

3. I would like to add here that the " Cut the tape" message code is just being used to test my concept. If my code works, I will replace the "Cut the tape" message code with codes to rotate a servo motor for 90 degrees.

I hope this explains what I'm trying to do. Please do advise me further on how to eliminate the problem below. Thank you.

> UserArduino:  
> Hi guys !
> 
> I'm a beginner and I recently wrote a code using millis. This program supposedly needs to print the signal " cut tape" only when the result of the ultrasonic sensor is less than 30 cm for 5 seconds. However, once I ran the program, it stills prints " Cut tape" even though it the period haven't reach 5 secs.
> 
> Can anyone help me to solve the issue ?
> 
> This is my code. Ignore the codes for servo for now as it is in development mode. Thank you.

---

<div class="post-metadata">

**Author:** ![UserArduino](https://avatars.discourse-cdn.com/v4/letter/u/9de053/32.png) [@UserArduino](https://forum.arduino.cc/u/UserArduino)\
**Post date:** [November 13, 2018, 6:19am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/8 "2018-11-13T06:19:29Z")

</div>

> Robin2:  
> The way to do that is like this pseudo code
> 
> ```arduino
> if (distance > 30) {
> 
> ```

lastLongMeasureTime = millis(); // reset the clock if the distance is too great  
}

if (millis() - lastLongMeasureTime \>= 5000) {  
&nbsp; &nbsp; // distance has been under 30 for a full 5 seconds  
&nbsp; &nbsp; // do stuff  
}

> ```arduino
> 
> ...R
> 
> ```

Hi Robin2 ,

I have a doubt, what happens if the distance is less than 30? Because there is no code for distance\< 30, and millis() would not have any value to be returned in the code "if (millis() - lastLongMeasureTime \>= 5000)".

---

<div class="post-metadata">

**Author:** ![Robin2](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robin2/32/216045_2.png) [@Robin2](https://forum.arduino.cc/u/Robin2)\
**Post date:** [November 13, 2018, 8:00am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/9 "2018-11-13T08:00:06Z")

</div>

> UserArduino:  
> I have a doubt, what happens if the distance is less than 30?

Allay your doubt by trying it. The Arduino is a great system for learning-by-doing.

Think about it. You said in your Original Post "only when the result of the ultrasonic sensor is less than 30 cm for 5 seconds". That means that you don't care a hoot what the distance is when it is less than 30. Your only concern is that it is not more than 30.

...R

---

<div class="post-metadata">

**Author:** ![J-M-L](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/j-m-l/32/766245_2.png) [@J-M-L](https://forum.arduino.cc/u/J-M-L)\
**Post date:** [November 13, 2018, 8:04am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/10 "2018-11-13T08:04:08Z")

</div>

What robinS expects is for you to add and try code around this... we won’t write your full project fir you here...

Edit: robin answered faster!

---

<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:** [November 13, 2018, 12:03pm UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/11 "2018-11-13T12:03:48Z")

</div>

> 1. I'm using an ultrasonic sensor to detect the presence of a box.

That is will NOT do. In can detect that there is, or is not, something some distance away. It is up to you to make sense of the distance value. Whether the thing that is x units of measure away is a box on a conveyor belt or Santa Claus on a red-nosed reindeer is not something that the sensor can tell you.

> I expect it takes 5 secs to pass the ultrasonic sensor.

I am now 100 % certain that you are using the wrong sensor. A break-beam sensor is far more appropriate.

You will have a far easier time determining that the sensor is, or is not, seeing light (because there is, or is not, something in the way), and when it starts or stops seeing the light.

You can record when the state changes from nothing in the way to something in the way. You can record when the state changes from something in the way to nothing in the way. One of those events is the trigger to "cut the tape" IF the time between the two events is long enough.

Whether the thing blocking the light is a box on a conveyor belt or Santa Claus on a red-nosed reindeer is not something that the sensor can tell you, so you must still use some common sense.

---

<div class="post-metadata">

**Author:** ![UserArduino](https://avatars.discourse-cdn.com/v4/letter/u/9de053/32.png) [@UserArduino](https://forum.arduino.cc/u/UserArduino)\
**Post date:** [November 16, 2018, 9:42am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/12 "2018-11-16T09:42:21Z")

</div>

> PaulS:  
> That is will NOT do. In can detect that there is, or is not, something some distance away. It is up to you to make sense of the distance value. Whether the thing that is x units of measure away is a box on a conveyor belt or Santa Claus on a red-nosed reindeer is not something that the sensor can tell you.

Hi PaulS,

I do see your point there, but on the conveyor belt there would only be the box. If anything else passed the ultrasonic sensor( for an example: someone just waved their hands across the ultrasonic sensor) the "Cut the tape" message should not be displayed. In order to do that, I wrote the code below initially.

while( cm \< 30)  
{ here: currentMillis= millis();

if((currentMillis-startMillis)\<period )

{ goto here;}// less than 5s jump to 'here'.

else if(( currentMillis-startMillis )\>= period)

{ Serial.print(" Cut tape"); }

I just made an assumption the box would take 5s to pass the ultrasonic sensor. So, after the box has passed, a servo motor should move ( for now I displayed cut the tape message). So, if something else passed the ultrasonic sensor ( for ex: someone waved their hands less than 30 cm in front of the sensor), the cut the tape message should not be displayed because a quick wave the hands might take 1 s . So, I was writing the code to achieve this objective. However, it didn't work as I expected. But, I'm sure there is a way to do it with millis() but  
I just don't know how to write the code for it.

(ps: I did search on break-beam sensor, but it seems to have the same concept has ultrasonic sensor and I think that the same problem will arise too.)

---

<div class="post-metadata">

**Author:** ![UserArduino](https://avatars.discourse-cdn.com/v4/letter/u/9de053/32.png) [@UserArduino](https://forum.arduino.cc/u/UserArduino)\
**Post date:** [November 16, 2018, 9:58am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/13 "2018-11-16T09:58:28Z")

</div>

Hi guys,

I modified my code to a new one. This time I think I saw why it doesn't work. Please have a look on my code first.

```cpp
const unsigned long period= 5000;// init period=5000.
int trigPin = 13;    // Trigger
int echoPin = 12;    // Echo
long duration, cm, inches;
unsigned long startMillis;  //some global variables available anywhere in the program
unsigned long currentMillis;

#include <Servo.h> 
 
Servo myservo;  // create servo object to control a servo 
                // twelve servo objects can be created on most boards
 
int pos = 0;    // variable to store the servo position 

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object  
  //Serial Port begin
  Serial.begin(9600);
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
startMillis= millis();
}

void loop() {
  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  //pinMode(trigPin, OUTPUT);
  //startMillis= millis();
  digitalWrite(trigPin, LOW);
  delayMicroseconds(10);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
 
  // Convert the time into a distance
  cm = (duration/2) / 29.1;    // Divide by 29.1 or multiply by 0.0343
  Serial.print(cm);
  Serial.print("cm");
  currentMillis= millis();
  
  while( (cm < 30) && ( currentMillis-startMillis )>= period)
  {        
    Serial.print("Cut the tape");
        
    startMillis = millis();// to save the latest time so can get the diff when looping again.    
  //delay(50);
  break;
  }
  
  delay(150);

}

```

I noticed that after 1 loop, the period might be \>=5 seconds even though there is something that passed the ultrasonic sensor for a distance less than 30 cm for a period less than 5s. For an example, a quick 1 sec hand wave might still trigger the cut the tape message to be displayed due to the fact that the period from previous looping has achieved 5 s. It is going back to square one, but it seems more clear to me. I will try to do what RobinS suggested and will get back here. Thanks for the help and patience guys.

---

<div class="post-metadata">

**Author:** ![Robin2](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robin2/32/216045_2.png) [@Robin2](https://forum.arduino.cc/u/Robin2)\
**Post date:** [November 16, 2018, 10:01am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/14 "2018-11-16T10:01:46Z")

</div>

> UserArduino:  
> I just made an assumption the box would take 5s to pass the ultrasonic sensor. So, after the box has passed, a servo motor should move ( for now I displayed cut the tape message). So, if something else passed the ultrasonic sensor ( for ex: someone waved their hands less than 30 cm in front of the sensor), the cut the tape message should not be displayed because a quick wave the hands might take 1 s . So, I was writing the code to achieve this objective.

That sounds like a different specification from what was in your Original Post "when the result of the ultrasonic sensor is less than 30 cm for 5 seconds". And if I understand the piece I have quoted it will be simpler to implement.

Just record the value of millis() when the sensor first detects the box and ignore other detections for N millisecs. Something like this pseudo code

```arduino
void loop() {
   if (boxDetected == false) {
      sensorDistance = read sensor();
      if (sensorDistance < 30) {
         boxDetected = true;
         boxDetectedTime = millis();
         start something;
       }
    }
    if (boxDetected == true) {
         if (millis() - boxDetectedMillis >= interval) {
            boxDetected = false;
            stop something;
          }
     }
}

```

...R

---

<div class="post-metadata">

**Author:** ![J-M-L](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/j-m-l/32/766245_2.png) [@J-M-L](https://forum.arduino.cc/u/J-M-L)\
**Post date:** [November 16, 2018, 10:03am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/15 "2018-11-16T10:03:03Z")

</div>

well that's because the code you wrote does not match your objective..

you should detect when the distance GOES below 30cm, note that start time and then detect when it GOES again back to above 30cm and compare the current time to the start time. if it's "long enough" then "cut the tape"

so you could think of this as a simple state machine:

the loop would just be a switch on current State:

Initial state = WAITING\_FOR\_PROXIMITY\_SIGNAL\_START  
possible event of interest =\> distance \< 30cm  
Action in case this event happens ==\> record start time and change current State to WAITING\_FOR\_PROXIMITY\_SIGNAL\_END

in the WAITING\_FOR\_PROXIMITY\_SIGNAL\_END state  
possible event of interest =\> distance \>= 30cm  
Action in case this event happens ==\> record end time and change current State to HANDLE\_SIGNAL

in the HANDLE\_SIGNAL state  
compare duration (end time - start time) to a threshold, and do something meaningful with it  
then change current State to WAITING\_FOR\_PROXIMITY\_SIGNAL\_START

Something like this

```cpp
enum : byte {WAITING_FOR_PROXIMITY_SIGNAL_START, WAITING_FOR_PROXIMITY_SIGNAL_END, HANDLE_SIGNAL} currentState;
const unsigned long boxMovementThreshold = 5000ul;
const unsigned int boxPresenceThreshold = 30u;

unsigned int getDistance()
{
  unsigned int cm = 100; // whatever you want
  // measure distance
  return cm;
}

void setup() {
  Serial.begin(115200);
  // do initializations
  // ...
  currentState = WAITING_FOR_PROXIMITY_SIGNAL_START;
}

void loop() {
  static unsigned long proximityStartTime, proximityEndTime;

  switch (currentState)
  {
    case WAITING_FOR_PROXIMITY_SIGNAL_START:
      if (getDistance() < boxPresenceThreshold) {
        proximityStartTime = millis();
        currentState = WAITING_FOR_PROXIMITY_SIGNAL_END;
      }
      break;

    case WAITING_FOR_PROXIMITY_SIGNAL_END:
      if (getDistance() >= boxPresenceThreshold) {
        proximityEndTime = millis();
        currentState = HANDLE_SIGNAL;
      }

      // you could aslo check millis() against proximityStartTime if you want to implement an alarm of something stuck
      if (millis() - proximityStartTime >= (10 * boxMovementThreshold)) {
        Serial.println(F("ALERT DEAD BODY STUCK UNDER THE DETECTOR"));
        // could create another state and move there to blink a light or turn off the belt or whatever
      }
      break;

    case HANDLE_SIGNAL:
      if ((proximityEndTime - proximityStartTime) >= boxMovementThreshold) {
        Serial.println(F("cut the tape"));
      } else {
        Serial.println(F("false positive"));
      }
      currentState = WAITING_FOR_PROXIMITY_SIGNAL_START;
      break;
  }
}

```

(typed here, totally untested)

---

<div class="post-metadata">

**Author:** ![Robin2](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robin2/32/216045_2.png) [@Robin2](https://forum.arduino.cc/u/Robin2)\
**Post date:** [November 16, 2018, 10:07am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/16 "2018-11-16T10:07:31Z")

</div>

> J-M-L:  
> so you could think of this as a simple state machine:

**@UserArduino** I did not use that language but that is what my pseudo code in Reply #13 does - boxDetected is my state variable

...R

---

<div class="post-metadata">

**Author:** ![J-M-L](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/j-m-l/32/766245_2.png) [@J-M-L](https://forum.arduino.cc/u/J-M-L)\
**Post date:** [November 16, 2018, 10:29am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/17 "2018-11-16T10:29:49Z")

</div>

> Robin2:  
> **@UserArduino** I did not use that language but that is what my pseudo code in Reply #13 does - boxDetected is my state variable
> 
> ...R

Indeed Robin - was typing my answer as you were typing yours (did not see your post until after I posted)

---

<div class="post-metadata">

**Author:** ![Robin2](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robin2/32/216045_2.png) [@Robin2](https://forum.arduino.cc/u/Robin2)\
**Post date:** [November 16, 2018, 11:54am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/18 "2018-11-16T11:54:08Z")

</div>

> J-M-L:  
> Indeed Robin - was typing my answer as you were typing yours (did not see your post until after I posted)

I figured that which is why I addressed Reply #15 to the OP - so that he could see that you and I are on the same page 🙂

...R

---

<div class="post-metadata">

**Author:** ![UserArduino](https://avatars.discourse-cdn.com/v4/letter/u/9de053/32.png) [@UserArduino](https://forum.arduino.cc/u/UserArduino)\
**Post date:** [November 19, 2018, 6:29am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/19 "2018-11-19T06:29:02Z")

</div>

Hi @Robin2 and @J-M-L,

before you guys replied , I wrote my code based on the code suggested by @Robin2 as follows.

> Robin2:  
> The way to do that is like this pseudo code
> 
> ```arduino
> if (distance > 30) {
> 
> ```

lastLongMeasureTime = millis(); // reset the clock if the distance is too great  
}

if (millis() - lastLongMeasureTime \>= 5000) {  
&nbsp; &nbsp; // distance has been under 30 for a full 5 seconds  
&nbsp; &nbsp; // do stuff  
}

> ```arduino
> 
> ...R
> 
> ```

I did some manual retracing of the output and made improvements as I wrote the new code. I ran the code and it seems to work fine and the problem I had was solved. This is my code. Please have a look and point out if there is any mistake. Please ignore the servo motor codes for now. Btw, thanks alot guys and everyone else who has spent some time writing some codes and gave me some suggestions. I'll look through the codes written by @Robin2 and @J-M-L . I do have another question about sensors but I think I'll open a new thread and post the link here as well. Thank you.

```arduino
//Code written by UserArduino ( Arduino.cc username) with the help of forum users.
const unsigned long period= 5000;// init period=5000.
int trigPin = 13;    // Trigger
int echoPin = 12;    // Echo
long duration, cm, inches;
unsigned long startMillis;  //some global variables available anywhere in the program
unsigned long currentMillis;
unsigned long lastLongMeasureTime;

#include <Servo.h> 
 
Servo myservo;  // create servo object to control a servo 
                // twelve servo objects can be created on most boards
 
int pos = 0;    // variable to store the servo position 

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object  
  //Serial Port begin
  Serial.begin(9600);
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
//startMillis= millis();
}

void loop() {
  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  //pinMode(trigPin, OUTPUT);
  //startMillis= millis();
  digitalWrite(trigPin, LOW);
  delayMicroseconds(10);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
 
  // Convert the time into a distance
  cm = (duration/2) / 29.1;    // Divide by 29.1 or multiply by 0.0343
  Serial.print(cm);
  Serial.print("cm");
  //currentMillis= millis();
  
  if (cm > 30) 
  {
    lastLongMeasureTime = millis(); // reset the clock if the distance is too great
  }

else if (cm<30 && (millis() - lastLongMeasureTime )>= 5000) 
{
    // distance has been under 30 for a full 5 seconds
    // do stuff
    Serial.print("Cut the tape");
    
    if ((millis()- lastLongMeasureTime)>=5000)
    { lastLongMeasureTime = millis(); } //This is to update the lastLongMeasureTime with current time to prevent repetitive "cut the tape" message to be displayed.
}
  delay(150);

}

```

---

<div class="post-metadata">

**Author:** ![Robin2](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robin2/32/216045_2.png) [@Robin2](https://forum.arduino.cc/u/Robin2)\
**Post date:** [November 19, 2018, 8:45am UTC](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247/20 "2018-11-19T08:45:44Z")

</div>

If it works then you have solved your problem. If you are planning to extend the program further it would be a good idea to avoid the use of delay() and delayMicroseconds() and use mills() (or micros() ) so that there is no blocking timing.

...R

[Next page](https://forum.arduino.cc/t/using-millis-as-timer-with-ultrasonic-sensor/554247.md?page=2)
