# Timer in an if statement

**URL:** <https://forum.arduino.cc/t/timer-in-an-if-statement/1089587>\
**Category:** Programming\
**Created:** [February 13, 2023, 8:43am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587 "2023-02-13T08:43:03Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![vik\_vdh](https://avatars.discourse-cdn.com/v4/letter/v/51bf81/32.png) [@vik\_vdh](https://forum.arduino.cc/u/vik_vdh)\
**Post date:** [February 13, 2023, 8:43am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/1 "2023-02-13T08:43:03Z")

</div>

For My current arduino project I am building a system that can measure the volume of packages. for the lenght I need to measure the time in an If statement but i really can not get it to work do you see the mistake ? I also dont get any error messages.  
the code

//I2C LCD Toevoegen (Bibliotheek niet vergeten)  
#include \<Wire.h\>  
#include \<LiquidCrystal\_I2C.h\>  
LiquidCrystal\_I2C lcd (0x27,16,2); /// of 16, 2  
int trigPin1 = 10;  
int echoPin1 = A1;  
int trigPin2 = 3;  
int echoPin2 = A0;  
int trigPin3 = 5;  
int echoPin3 = A2;  
// Sensor 1,2 & 3 maximum afstand  
int max1 = 60;  
int max2 = 60;  
int max3= 70;  
// Timers opzetten  
unsigned long starttime;  
unsigned long meetwaarde1;  
unsigned long endtime;

void setup() {

//Sensor pinnen  
pinMode(trigPin1, OUTPUT);  
pinMode(echoPin1, INPUT);

pinMode(trigPin2, OUTPUT);  
pinMode(echoPin2, INPUT);

pinMode(trigPin3, OUTPUT);  
pinMode(echoPin3, INPUT);

//LCD Setup  
lcd.begin();  
lcd.clear();  
lcd.backlight();  
//Basistekst LCD  
lcd.setCursor(2,0);  
lcd.print("Volume");

}

void loop() {  
//starttime starte  
unsigned long starttime = millis();  
// Variabelen zetten  
int duration1, distance1, duration2, distance2, duration3, distance3;

// Sensor 1  
digitalWrite (trigPin1, HIGH);  
delayMicroseconds (10);  
digitalWrite (trigPin1, LOW);  
duration1 = pulseIn(echoPin1,HIGH);  
// De afstand is de tijd maal door de snelheid van het geluid gedeeld door 2  
distance1 = duration1 \* 0.034 / 2;  
if (distance1 \< max1) {  
int final1 = distance1;

delay(50);

```
// Sensor 2

```

digitalWrite (trigPin2, HIGH);  
delayMicroseconds (10);  
digitalWrite (trigPin2, LOW);  
duration2 = pulseIn(echoPin2,HIGH);  
// De afstand is de tijd maal door de snelheid van het geluid gedeeld door 2  
distance2 = duration2 \* 0.034 / 2;  
if (distance2 \< max2) {  
int final2 = distance2;

delayMicroseconds(50);

//sensor 3  
digitalWrite (trigPin3, HIGH);  
delayMicroseconds(10);  
digitalWrite(trigPin3,LOW);  
duration3=pulseIn(echoPin3,HIGH);  
distance3=duration3 \* 0.034 / 2;  
if (distance3 \< max3) {  
int final3 = distance3;

delayMicroseconds(50);

//boolean starttime = false  
starttime=false;

// timer starten  
if (final3\<56){  
meetwaarde1 = millis();  
if (final3\>56){  
endtime = millis();  
// tijd pakket onder sensor 3  
unsigned long elapsedtime = (endtime-meetwaarde1);

// gemeten waardes omvormen en een paar berekeningen  
const int gemetenwaarde = (final1 + final2);  
const int breedtepakket = (60-gemetenwaarde);  
const int hoogtepakket = (54-final3);  
const int opp1 = (hoogtepakket_breedtepakket);  
const int tijdsensor3 = (elapsedtime_10^-3);  
const int snelheidband = (1);  
const int lengtepakket = (tijdsensor3\*snelheidband);

lcd.setCursor(2,1);  
lcd.print (elapsedtime);  
}  
}  
}  
}  
}  
delay(4000);  
}

---

<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:** [February 13, 2023, 8:47am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/2 "2023-02-13T08:47:53Z")

</div>

Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'  
  
Use **code tags** (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 behaviour 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 fru…

---

<div class="post-metadata">

**Author:** ![LarryD](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/larryd/32/215550_2.png) [@LarryD](https://forum.arduino.cc/u/LarryD)\
**Post date:** [February 13, 2023, 8:48am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/3 "2023-02-13T08:48:56Z")

</div>

Always always always format your code with \<CTRL\>\<T\>

- Check the placement of your closing braces.

# }

```arduino
//I2C LCD Toevoegen (Bibliotheek niet vergeten)
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd (0x27, 16, 2); /// of 16, 2
int trigPin1 = 10;
int echoPin1 = A1;
int trigPin2 = 3;
int echoPin2 = A0;
int trigPin3 = 5;
int echoPin3 = A2;
// Sensor 1,2 & 3 maximum afstand
int max1 = 60;
int max2 = 60;
int max3 = 70;
// Timers opzetten
unsigned long starttime;
unsigned long meetwaarde1;
unsigned long endtime;

void setup()
{

  //Sensor pinnen
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);

  //LCD Setup
  lcd.begin();
  lcd.clear();
  lcd.backlight();
  //Basistekst LCD
  lcd.setCursor(2, 0);
  lcd.print("Volume");

}

void loop()
{
  //starttime starte
  unsigned long starttime = millis();
  // Variabelen zetten
  int duration1, distance1, duration2, distance2, duration3, distance3;

  // Sensor 1
  digitalWrite (trigPin1, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  // De afstand is de tijd maal door de snelheid van het geluid gedeeld door 2
  distance1 = duration1 * 0.034 / 2;
  if (distance1 < max1)
  {
    int final1 = distance1;

    delay(50);

    // Sensor 2
    digitalWrite (trigPin2, HIGH);
    delayMicroseconds (10);
    digitalWrite (trigPin2, LOW);
    duration2 = pulseIn(echoPin2, HIGH);
    // De afstand is de tijd maal door de snelheid van het geluid gedeeld door 2
    distance2 = duration2 * 0.034 / 2;
    if (distance2 < max2)
    {
      int final2 = distance2;

      delayMicroseconds(50);

      //sensor 3
      digitalWrite (trigPin3, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin3, LOW);
      duration3 = pulseIn(echoPin3, HIGH);
      distance3 = duration3 * 0.034 / 2;
      if (distance3 < max3)
      {
        int final3 = distance3;

        delayMicroseconds(50);

        //boolean starttime = false
        starttime = false;

        // timer starten
        if (final3 < 56)
        {
          meetwaarde1 = millis();
          if (final3 > 56)
          {
            endtime = millis();
            // tijd pakket onder sensor 3
            unsigned long elapsedtime = (endtime - meetwaarde1);

            // gemeten waardes omvormen en een paar berekeningen
            const int gemetenwaarde = (final1 + final2);
            const int breedtepakket = (60 - gemetenwaarde);
            const int hoogtepakket = (54 - final3);
            const int opp1 = (hoogtepakketbreedtepakket);
            const int tijdsensor3 = (elapsedtime10 ^ -3);
            const int snelheidband = (1);
            const int lengtepakket = (tijdsensor3 * snelheidband);

            lcd.setCursor(2, 1);
            lcd.print (elapsedtime);
          }
        }
      }
    }
  }
  delay(4000);
}

```

---

<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:** [February 13, 2023, 8:49am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/4 "2023-02-13T08:49:23Z")

</div>

> [@vik\_vdh](#):
>
> }  
> }  
> }  
> }  
> }

Use Auto format in the IDE to eliminate such silly code layouts

---

<div class="post-metadata">

**Author:** ![GrandPete](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/grandpete/32/1126625_2.png) [@GrandPete](https://forum.arduino.cc/u/GrandPete)\
**Post date:** [February 13, 2023, 9:03am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/5 "2023-02-13T09:03:06Z")

</div>

Hi!

please format your code correctly with the \</\> button when you edit the post.

> [@vik\_vdh](#):
>
> void loop() {  
> //starttime starte  
> unsigned long starttime = millis();

this way, your timer is set to millis() value at each loop. You probably need to set up starttime at the very end of Setup() (and not beginiing of the loop() then refresh it (starttime = millis() only after a comparaison occurs. for example:

```arduino
Setup(){

int duration1, distance1, duration2.... // setup is the better place to instanciate your value. No need to instanciate at each loop().
startime = millis(); // start of your timer
} // end of setup

Loop(){

if (millis()-starttime)> waiting_delay){ // elapsed time since last "starttime =millis()"
starttime = millis(); // the If statment was correct, then you reset your timer
.... // do what you need here

```

a little remark: you use 3 consecutive times the pulsIn function. You may code it as a general function and send it the proper arguments

```arduino
> Int READ_ULTRASONIC(int PIN_TRIG, int PIN_ECHO, int DISTANCE){
> 
> digitalWrite (PIN_TRIG, HIGH);
> delayMicroseconds(10);
> digitalWrite(PIN_TRIG,LOW);
> int duration=pulseIn(PIN_ECHO,HIGH);
> DISTANCE=duration* 0.034 / 2;
> }

```

so in your code you can use it this way

```arduino
> //Sensor 1
> if (READ_ULTRASONIC(trigPin1, echoPin1, distance1)) {
> if (distance1 < max1) {
> int final1 = distance1;
> 
> delay(50);
> 
> //Sensor 2
> if (READ_ULTRASONIC(trigPin2, echoPin2, distance2)) {
> if (distance2 < max2) {
> ......
> 
int final2 = distance2;
}}

```

---

<div class="post-metadata">

**Author:** ![vik\_vdh](https://avatars.discourse-cdn.com/v4/letter/v/51bf81/32.png) [@vik\_vdh](https://forum.arduino.cc/u/vik_vdh)\
**Post date:** [February 13, 2023, 9:06am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/6 "2023-02-13T09:06:42Z")

</div>

thanks i will give this a try and that is a great tip wich i for sure will use.

---

<div class="post-metadata">

**Author:** ![GrandPete](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/grandpete/32/1126625_2.png) [@GrandPete](https://forum.arduino.cc/u/GrandPete)\
**Post date:** [February 13, 2023, 9:14am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/7 "2023-02-13T09:14:14Z")

</div>

if it is a new code, if you are a beginner, never hesitate to code step by step, even when using an example or code grabbet on the web.  
Then you can observe the functionning of basic functions (here the ultrasonic measurment AND timers), code it properly then assemble it in a more sophisticated code.

Wish you luck with your project! 👍

Some stuff make me wonders:

- is the package on a moove when measuring its dimensions?
- I focus on your timer coding but it is not clear why the 3D measures are made under a timer (so my idea the package is on an horizontal move in front of the sensor)
- for this kind of project in industry (airport, packaging etc...) I bet there is a beam sensor that may detect an incoming object (the box "cut" the ray of light) so the lenght of the object can be determine this way. but It works only for 1 dimension!

---

<div class="post-metadata">

**Author:** ![gcjr](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gcjr/32/314015_2.png) [@gcjr](https://forum.arduino.cc/u/gcjr)\
**Post date:** [February 13, 2023, 9:31am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/8 "2023-02-13T09:31:50Z")

</div>

can you describe your algorithm? why is each distance measurement as well as the time measurement nested within the preceding measurement?

presumably you're trying to measure the length of a package by capturing a timestamp when the package is 1st detected and then a timestamp after it is no longer detected. but it appears that that 2nd timestamp measurement is nested within the condition for the 1st distance measure rather than when the condition is NOT true

---

<div class="post-metadata">

**Author:** ![vik\_vdh](https://avatars.discourse-cdn.com/v4/letter/v/51bf81/32.png) [@vik\_vdh](https://forum.arduino.cc/u/vik_vdh)\
**Post date:** [February 15, 2023, 11:53am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/9 "2023-02-15T11:53:11Z")

</div>

The package is indeed on the move. We were given a conveyer belt and with that we needed to make something to sort the packages. The width and height are measured with the measurements of 2 ultrasonic sensors. To save 2 extra sensors we decided to measure that via: s(length package)= v(speed conveyor belt)\*t(the time that the package is detected.  
And the tip you gave to measure one dimension is already in use in our project but thanks anyways.

---

<div class="post-metadata">

**Author:** ![camsysca](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/camsysca/32/1015228_2.png) [@camsysca](https://forum.arduino.cc/u/camsysca)\
**Post date:** [February 15, 2023, 12:25pm UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/10 "2023-02-15T12:25:00Z")

</div>

> [@GrandPete](#):
>
> for this kind of project in industry (airport, packaging etc...) I bet there is a beam sensor that may detect an incoming object (the box "cut" the ray of light) so the lenght of the object can be determine this way. but It works only for 1 dimension!

This is true, but often the moving object changes direction at some point(hits an end stop and then is pushed sideways onto a second belt, for example), so the second dimension can be then measured during that travel by the same technique; it really depends on the case circumstances.

---

<div class="post-metadata">

**Author:** ![vik\_vdh](https://avatars.discourse-cdn.com/v4/letter/v/51bf81/32.png) [@vik\_vdh](https://forum.arduino.cc/u/vik_vdh)\
**Post date:** [February 17, 2023, 8:04am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/11 "2023-02-17T08:04:36Z")

</div>

should i use a while function?

---

<div class="post-metadata">

**Author:** ![gcjr](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gcjr/32/314015_2.png) [@gcjr](https://forum.arduino.cc/u/gcjr)\
**Post date:** [February 17, 2023, 10:36am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/12 "2023-02-17T10:36:59Z")

</div>

presumably you're suggesting that after detecting a package the code would wait for the end of the package.

ok, lets consider that approach. what would the code wait for and where in the code would it wait?

(also bear in mind that time is needed between ultrasonic pings to allow the previous ping energy to dissipate so that the following detection is not recognizing the earlier ping from a more distance object)

(another thing to consider it capturing the code that measures distance in a sub-function with arguments for the 2 pins and returns the distance)

---

<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:** [August 16, 2023, 10:37am UTC](https://forum.arduino.cc/t/timer-in-an-if-statement/1089587/13 "2023-08-16T10:37:22Z")

</div>

Closed on August 16, 2023, 10:37am UTC

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