Ultrasonic using Millis

Hi guys, im trying to get some help on my project, it is a water level monitoring using Ultrasonic sensor HC-SR04. Im having a difficulty in figuring out how to use the millis() function because i didnt get my desired output in my program. Heres my program..

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
long duration;
int distance;

unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;


void setup() {
pinMode(trigPin, OUTPUT); 
pinMode(echoPin, INPUT); 
Serial.begin(9600); 
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delay(500);
digitalWrite(trigPin, HIGH);
delay(500);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;

Serial.print("Distance: ");
Serial.println(distance);

 if(distance <=10 && (currentMillis - previousMillis >= 5000){
     
       Serial.println("SMS sent 1");
       previousMillis = currentMillis;
     }     
   if(distance >=11 && distance <=25 && (currentMillis - previousMillis >=10000){
    
      
       Serial.println("SMS sent 2");
         previousMillis = currentMillis;
   
 }
}

the prob is lets just say in 3 seconds after the prgram start the sensor read an output of <10 the serial monitor will only output the distance but when the time goes in 5 seconds it will output the distance and the message.. but when the distance hit the 2nd condition or >10 distance it didnt print out the next messege until the time when the program start hit 10secs the it will repeat...

i hope guys you get my point. I appreciate any help tnx :slight_smile:

i just want to get the proper construction of my code so that if every time either in the condition is met
it will print out an output then it will follow the interval to send again an output...

sorry for my bad english :)..

i just want to get the proper construction of my code

Start by Auto formatting it in the IDE and using code tags when you post it here

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
long duration;
int distance;

unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;


void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}
void loop()
{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delay(500);
  digitalWrite(trigPin, HIGH);
  delay(500);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  Serial.print("Distance: ");
  Serial.println(distance);
  if (distance <= 10)
  {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= 5000)
    {
      Serial.println("SMS sent 1");
      previousMillis = currentMillis;
    }
    if (distance >= 11 && distance <= 25)
    {
      unsigned long currentMillis = millis();
      if (currentMillis - previousMillis >= 10000)
      {
        Serial.println("SMS sent 2");
        previousMillis = currentMillis;
      }
    }
  }
}

That will not fix anything but may help others in helping you

Does the example sketch work?

/**
   HC-SR04 Demo
   Demonstration of the HC-SR04 Ultrasonic Sensor
   Date: August 3, 2016
   Description:
    Connect the ultrasonic sensor to the Arduino as per the
    hardware connections below. Run the sketch and open a serial
    monitor. The distance read from the sensor will be displayed
    in centimeters and inches.
   Hardware Connections:
    Arduino | HC-SR04
    -------------------
      5V    |   VCC
      9     |   Trig
      10    |   Echo
      GND   |   GND
   License:
    Public Domain
*/

// Pins
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;

// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;

void setup() {

  // The Trigger pin will tell the sensor to range find
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);

  //Set Echo pin as input to measure the duration of 
  //pulses coming back from the distance sensor
  pinMode(ECHO_PIN, INPUT);

  // We'll use the serial monitor to view the sensor output
  Serial.begin(9600);
}

void loop() {

  unsigned long t1;
  unsigned long t2;
  unsigned long pulse_width;
  float cm;
  float inches;

  // Hold the trigger pin high for at least 10 us
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait for pulse on echo pin
  while ( digitalRead(ECHO_PIN) == 0 );

  // Measure how long the echo pin was held high (pulse width)
  // Note: the micros() counter will overflow after ~70 min
  t1 = micros();
  while ( digitalRead(ECHO_PIN) == 1);
  t2 = micros();
  pulse_width = t2 - t1;

  // Calculate distance in centimeters and inches. The constants
  // are found in the datasheet, and calculated from the assumed speed
  //of sound in air at sea level (~340 m/s).
  cm = pulse_width / 58.0;
  inches = pulse_width / 148.0;

  // Print out results
  if ( pulse_width > MAX_DIST ) {
    Serial.println("Out of range");
  } else {
    Serial.print(cm);
    Serial.print(" cm \t");
    Serial.print(inches);
    Serial.println(" in");
  }

  // Wait at least 60ms before next measurement
  delay(60);
}

If this works, make modifications as needed.

tnx for correcting my post UKHeliBob

delay(500);
digitalWrite(trigPin, HIGH);
delay(500);

1/2 second each ???

i didnt have any problems about the Ultrasonic Sensor

kalyegwapo14:
i dont have any problems about the Ultrasonic Sensor

Good.

“ it happens that when the if conditions hit it will sent out an output if the elapsed time is reached but when the sensor instantly changed from the first condition to second is that it doesnt show an instant output.”

Having trouble with understanding this statement.

Please tell us exactly what you want to happen.

tnx for the concern :slight_smile:
i already updated my post tnx

the prob is lets just say in 3 seconds after the prgram start the sensor read an output of <10 the serial monitor will only output the distance but when the time goes in 5 seconds it will output the distance and the message.. but when the distance hit the 2nd condition or >10 distance it didnt print out the next messege until the time when the program start hit 10secs the it will repeat...

Please do not change/update your original post.

Respond to questions in a new post.

When the sensor reads <=10 and stays there, do you want to print "SMS sent 1" every 5 seconds
as long as the level is <=10?

larryd:
Please do not change/update your original post.

Respond to questions in a new post.

When the sensor reads <=10 and stays there, do you want to print "SMS sent 1" every 5 seconds
as long as the level is <=10?

sry for updating my post ..

yes and it will instantly print message 2 if the distance suddenly hit the >10 and it will print every 10 seconds as long as the level is >10

it will instantly print message 2 if the distance suddenly hit the >10 and it will print every 10 seconds as long as the level is >10

distance >10

or

distance >=11 && distance <=25

?

larryd:
distance >10

or

distance >=11 && distance <=25

?

the

distance >=11 && distance <=25

sir

This is not tested.

Please try the sketch:

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
long duration;
int distance;

unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;

bool Flag1 = false;
bool Flag2 = false;

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}
void loop()
{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delay(500);
  digitalWrite(trigPin, HIGH);
  delay(500);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.println(distance);

  //*****************************************
  //have we reached our level: <=10?
  if (Flag1 == false && distance <= 10)
  {
    Flag1 = true;

    //start timing
    previousMillis = millis();
  }

  else
  {
    Flag1 = false;
  }

  //*****************************************
  //have we reached our level: >=11 and <=25?
  if (Flag2 == false && distance >= 11 && distance <= 25)
  {
    Flag2 = true;

    //print immediately
    Serial.println("SMS sent 2");

    //start timing
    previousMillis2 = millis();
  }
  else
  {
    Flag2 = false;
  }

  //*****************************************
  if (distance <= 10)
  {
    unsigned long currentMillis = millis();
    
    if (currentMillis - previousMillis >= 5000)
    {
      Serial.println("SMS sent 1");
      previousMillis = currentMillis;
    }
  }

  //*****************************************
  if (distance >= 11 && distance <= 25)
  {
    unsigned long currentMillis = millis();
    
    if (currentMillis - previousMillis2 >= 10000)
    {
      Serial.println("SMS sent 2");
      previousMillis2 = currentMillis;
    }
  }

} //END of loop()

Edit: Oops
bool Flag1 = false;
bool Flag1 = false;
Should be
bool Flag1 = false;
bool Flag2 = false;

Code has been updated.

okay sir i'll try it :slight_smile:

this is the output sir

IMG_20200122_170505.jpg

IMG_20200122_170451.jpg

in the image that i attached sir it shows it print message if the distance is <10 and if the distance is >=11 && distance <=25 but it didnt print message every 5 seconds or 10 secs..

IMG_20200122_170505.jpg

IMG_20200122_170451.jpg

Your delay(500) are probably causing some updating problems.

Try this: EDIT use code in post #18

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
long duration;
int distance;

unsigned long previousMillis;
unsigned long previousMillis2;
unsigned long distanceMillis;

bool Flag1 = false;
bool Flag2 = false;

//***************************************************************************
void setup()
{
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

//***************************************************************************
void loop()
{
  //*****************************************
  //get distance every 500 milli seconds

  if (millis() - distanceMillis >= 500)
  {
    //resart timing
    distanceMillis = millis();

    getDistance();

  }

  //*****************************************
  //have we reached our level: <=10?
  if (Flag1 == false && distance <= 10)
  {
    Flag1 = true;

    //print immediately
    Serial.println("SMS sent 1");

    //start timing
    previousMillis = millis();
  }

  else
  {
    Flag1 = false;
  }

  //*****************************************
  //have we reached our level: >=11 and <=25?
  if (Flag2 == false && distance >= 11 && distance <= 25)
  {
    Flag2 = true;

    //print immediately
    Serial.println("SMS sent 2");

    //start timing
    previousMillis2 = millis();
  }

  else
  {
    Flag2 = false;
  }

  //*****************************************
  if (distance <= 10)
  {
    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= 5000)
    {
      Serial.println("SMS sent 1");
      previousMillis = currentMillis;
    }
  }

  //*****************************************
  if (distance >= 11 && distance <= 25)
  {
    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis2 >= 10000)
    {
      Serial.println("SMS sent 2");
      previousMillis2 = currentMillis;
    }
  }

} //END of loop()

//***************************************************************************
void getDistance()
{
  // Clears the trigPin
  //  digitalWrite(trigPin, LOW);
  //  delay(500);
  //  digitalWrite(trigPin, HIGH);
  //  delay(500);
  //  digitalWrite(trigPin, LOW);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.println(distance);

} //EN of getDistance()

ok sir i'll try it

Sorry, I found a major problem. :confused:

Try this sketch instead :slight_smile:

//Version 3.0

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;

// defines variables
unsigned long duration;
unsigned int distance;

unsigned long previousMillis;
unsigned long previousMillis2;
unsigned long distanceMillis;

bool Flag1 = false;
bool Flag2 = false;

//***************************************************************************
void setup()
{
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

//***************************************************************************
void loop()
{
  //*****************************************
  //get distance every 500ms
  if (millis() - distanceMillis > 500)
  {
    //resart timing
    distanceMillis = millis();

    getDistance();

  }

  //*****************************************
  //have we reached our level: <=10?
  if(Flag1 == false && distance <= 10)
  {
    Flag1 = true;
    //print immediately
    Serial.println("SMS sent 1");

    //start timing
    previousMillis = millis();
  }

  else if (distance > 10)
  {
    Flag1 = false;
  }

  //*****************************************
  //have we reached our level: >=11 and <=25?
  if (Flag2 == false && distance >= 11 && distance <= 25)
  {
    Flag2 = true;

    //print immediately
    Serial.println("SMS sent 2");

    //start timing
    previousMillis2 = millis();
  }

  else if (distance < 11)
  {
    Flag2 = false;
  }

  //*****************************************
  if (distance <= 10)
  {
    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= 5000)
    {
      Serial.println("SMS sent 1");
      previousMillis = currentMillis;
    }
  }

  //*****************************************
  if (distance >= 11 && distance <= 25)
  {
    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis2 >= 10000)
    {
      Serial.println("SMS sent 2");
      previousMillis2 = currentMillis;
    }
  }

} //END of loop()

//***************************************************************************
void getDistance()
{
  // Clears the trigPin
  //  digitalWrite(trigPin, LOW);
  //  delay(500);
  //  digitalWrite(trigPin, HIGH);
  //  delay(500);
  //  digitalWrite(trigPin, LOW);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.println(distance);

} //END of getDistance()

ok sir :slight_smile: