Distance sensor HELP

Hello, i am trying to make parking sensors for garage. And i dont know how to stop arduino code when car is not in garage or when it is parked. I need something like “if distance is same for 10 secs, stop code”
Here is my code:

#define trigPin1 9
#define echoPin1 8
#define Relay1 6

#define trigPin2 10
#define echoPin2 11
#define Relay2 7

long duration, distance, UltraSensor1, UltraSensor2; //we’ll use these variable to store and generate data

char data;
String SerialData="";

void setup()
{
Serial.begin (9600);

pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(Relay1, OUTPUT);

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

}

void loop()
{
SonarSensor(trigPin1, echoPin1);
UltraSensor1 = distance;
SonarSensor(trigPin2,echoPin2);
UltraSensor2 = distance;

while(Serial.available())
{
delay(10);
data=Serial.read();
SerialData+=data;
}

if(SerialData==“display distance”)
{
Serial.print(“distance measured by the first sensor: “);
Serial.print(UltraSensor1);
Serial.println(” cm”);

Serial.print(“distance measured by the second sensor: “);
Serial.print(UltraSensor2);
Serial.println(” cm”);
Serial.println("---------------------------------------------------------------------------------------------------------");
}

SerialData="";
if(UltraSensor1 <=15)
{
digitalWrite(Relay1,LOW);
}
else
{
digitalWrite(Relay1,HIGH);
}

if(UltraSensor2 <=15)
{
digitalWrite(Relay2,LOW);
}
else
{
digitalWrite(Relay2,HIGH);
}
if(UltraSensor1 <=5)//
{
delay(200);
digitalWrite(Relay1,HIGH);
delay(200);

}

if(UltraSensor2 <=5)
{
delay(200);
digitalWrite(Relay2,HIGH);
delay(200);
}
}

// SonarSensor function used to generate and read the ultrasonic wave
void SonarSensor(int trigPinSensor,int echoPinSensor)//it takes the trigPIN and the echoPIN
{
//START SonarSensor FUNCTION
//generate the ultrasonic wave
//----------------------------------------------------------------------------------------------------------------------
digitalWrite(trigPinSensor, LOW);// put trigpin LOW
delayMicroseconds(2);// wait 2 microseconds
digitalWrite(trigPinSensor, HIGH);// switch trigpin HIGH
delayMicroseconds(10); // wait 10 microseconds
digitalWrite(trigPinSensor, LOW);// turn it LOW again
//----------------------------------------------------------------------------------------------------------------------

//read the distance
//----------------------------------------------------------------------------------------------------------------------
duration = pulseIn(echoPinSensor, HIGH);
distance= (duration/2) / 29.1;
}

/----------------------- END PROGRAM -----------------------/

sketch_feb15b.ino (2.8 KB)

Add a boolean variable named timingInProgress to your code and set it to false. Each time you read the distance compare it with the last time you read it which you have previously saved. If the distance has not changed by a significant amount and timingInProgress is false then save the value of millis() as the period start time and set timingInProgress to true. If the distance has changed significantly then set timingInProgress to false

Further on in loop(), if timingInProgress is true and the current value of millis() minus the period start time is greater than 10 seconds then you know that the distance has not changed significantly during the timing period

void SonarSensor(int trigPinSensor,int echoPinSensor) Why a void function?
Why not have your function return the range for the given pins, instead of going via global variables?

You may find that reducing the ping rate to no more than about 20 - 30 Hz will produce more stable results.

Please remember to use code tags when posting code

Thank you for fast answer. I'm trying to understand what you told me but I can't because I'm new to Arduino. Could you write me an example that I can put in my code to try and redo something if need?

unsigned int SonarSensor(int trigPinSensor,int echoPinSensor)
{
  digitalWrite(trigPinSensor, HIGH);// switch trigpin HIGH
  delayMicroseconds(10); // wait 10 microseconds
  digitalWrite(trigPinSensor, LOW);// turn it LOW again
  return (pulseIn(echoPinSensor, HIGH) / 2) / 29.1;
}

TheMemberFormerlyKnownAsAWOL:

unsigned int SonarSensor(int trigPinSensor,int echoPinSensor)

{
 digitalWrite(trigPinSensor, HIGH);// switch trigpin HIGH
 delayMicroseconds(10); // wait 10 microseconds
 digitalWrite(trigPinSensor, LOW);// turn it LOW again
 return (pulseIn(echoPinSensor, HIGH) / 2) / 29.1;
}

I added this to my code and relays starts to turn on and turn off constantly.
But never mind distance is working fine on void. But I don’t know how to stop it when distance does not change? For example when I park car I want that relays to stop until car is moved again.

dzoni28:
I added this to my code

We can’t see your code.

#define trigPin1 9                                 
#define echoPin1 8                                 
#define Relay1 6                         

#define trigPin2 10
#define echoPin2 11
#define Relay2 7

long duration, distance, UltraSensor1, UltraSensor2; //we'll use these variable to store and generate data

char data;
String SerialData="";

void setup()
{
Serial.begin (9600);                           

pinMode(trigPin1, OUTPUT);                     
pinMode(echoPin1, INPUT);                       
pinMode(Relay1, OUTPUT);                 

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

}

void loop()
{                

while(Serial.available())
{
  delay(10);
  data=Serial.read();
  SerialData+=data;
}

if(SerialData=="display distance")
{
Serial.print("distance measured by the first sensor: ");
Serial.print(UltraSensor1);
Serial.println(" cm");

Serial.print("distance measured by the second sensor: ");
Serial.print(UltraSensor2);
Serial.println(" cm");
Serial.println("---------------------------------------------------------------------------------------------------------");
}

SerialData="";
if(UltraSensor1 <=15)
{
  digitalWrite(Relay1,LOW);
}
else               
{
  digitalWrite(Relay1,HIGH);
}

if(UltraSensor2 <=15)
{
  digitalWrite(Relay2,LOW);
}
else
{
  digitalWrite(Relay2,HIGH);
}
  if(UltraSensor1 <=5)//
{
  delay(200);
  digitalWrite(Relay1,HIGH);
  delay(200);
 
}
 
if(UltraSensor2 <=5)
{
  delay(200);
  digitalWrite(Relay2,HIGH);
  delay(200);
}
}
unsigned int SonarSensor(int trigPinSensor,int echoPinSensor)
{
  digitalWrite(trigPinSensor, HIGH);// switch trigpin HIGH
  delayMicroseconds(10); // wait 10 microseconds
  digitalWrite(trigPinSensor, LOW);// turn it LOW again
  return (pulseIn(echoPinSensor, HIGH) / 2) / 29.1;

I can’t see where you call SonarSensor, and assign the return value to a variable.

Please remember to use code tags when posting code

Okay finally find code tags :smiley:
I understood you in theory but I don't know how to put it into practice (code}.

data=Serial.read();Here, you are assigning the value returned by the function “Serial.read” to the variable “data”.

Now, extend that same principle to the function “SonarSensor”.

Sorry, I don't understand you. I am giving up... I'm going to turn on and off it manually with switch. :frowning:

This timer example, Delay execution until condition has been true for X secs
from my How to Write Timers and Delays in Arduino tutorial is what you need

#include <millisDelay.h>
millisDelay executionDelay; // the delay object
unsigned long executionDelay_mS = 5000;

bool executedMethod = false;

bool condition() {  // returns when the condition is true
  return (Serial.read() == -1);  // Serial.read() returns -1 when there is nothing to read
  // other types of conditions could be  Range < 5cm etc
}
#define trigPin1 9                                 
#define echoPin1 8                                 
#define Relay1 6                         

#define trigPin2 10
#define echoPin2 11
#define Relay2 7

long duration, distance, UltraSensor1, UltraSensor2; //we'll use these variable to store and generate data

void setup() {
  
pinMode(trigPin1, OUTPUT);                     
pinMode(echoPin1, INPUT);                       
pinMode(Relay1, OUTPUT);                 

pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(Relay2, OUTPUT);
  Serial.begin(115200);
  // wait a few sec to let user open the monitor
  for (int i = 5; i > 0; i--) {
    delay(1000);
    Serial.print(i); Serial.print(' ');
  }
  Serial.println("Enter input at least every 5 secs");
}

void loop() {
  
     
  if (executionDelay.justFinished()) { // nothing read for 10 sec
    //executionDelay only returns true once after start()
    // do something here
    executedMethod = true;  // only do this once even if condition remains true for a long time
    Serial.println(" No input for 5 sec.");
  }

  if (condition()) {
    if (!executionDelay.isRunning() && (!executedMethod)) {
      // start it now
      executionDelay.start(executionDelay_mS);
    } // else already timing out don't disturb it OR has already timed out and executed

  } else { // condtion() is false  out side range etc
    // stop timer
    executionDelay.stop();
    // clear executedMethod so will execute again one condition is true for 5sec
    executedMethod = false;
  }

if(UltraSensor1 <=15)
{
  digitalWrite(Relay1,LOW);
}
else               
{
  digitalWrite(Relay1,HIGH);
}

if(UltraSensor2 <=15)
{
  digitalWrite(Relay2,LOW);
}
else
{
  digitalWrite(Relay2,HIGH);
}
  if(UltraSensor1 <=5)//
{
  delay(200);
  digitalWrite(Relay1,HIGH);
  delay(200);
 
}
 
if(UltraSensor2 <=5)
{
  delay(200);
  digitalWrite(Relay2,HIGH);
  delay(200);
}
}



void SonarSensor(int trigPinSensor,int echoPinSensor)
{
digitalWrite(trigPinSensor, LOW);// put trigpin LOW
delayMicroseconds(2);// wait 2 microseconds
digitalWrite(trigPinSensor, HIGH);// switch trigpin HIGH
delayMicroseconds(10); // wait 10 microseconds
digitalWrite(trigPinSensor, LOW);// turn it LOW again

duration = pulseIn(echoPinSensor, HIGH);
distance= (duration/2) / 29.1;
}

I added it to my code, can you check this ?

Try this code
Only one sensor implemented and using Serial input to set near or far distance

#include <millisDelay.h>
millisDelay ledDelay1; // the delay object for led
unsigned long ledDelay1_mS = 3000;

#define trigPin1 9
#define echoPin1 8
#define Relay1 6

#define trigPin2 10
#define echoPin2 11
#define Relay2 7

long duration, distance, UltraSensor1, UltraSensor2; //we'll use these variable to store and generate data
bool sensor1Near = false;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(Relay1, OUTPUT);

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

  Serial.begin(115200);
  // wait a few sec to let user open the monitor
  for (int i = 5; i > 0; i--) {
    delay(1000);
    Serial.print(i); Serial.print(' ');
  }
  Serial.println();
  Serial.println("Enter n for near and f for far");
  // set  sensor1Near based on dist
  sensor1Near = false;
  Serial.println("Currently sensor is far");
}

bool condition1() {  // returns when the condition is true
  char c = ' ';
  if (Serial.available()) {
    c = Serial.read();
  }
  if (sensor1Near) {
    // looking for > 5
    if (c == 'f') { // for testing
      //  if (UltraSensor1 > 5) { // for real sensor
      sensor1Near = false;
      Serial.println(F("Sensor is near"));
      return true;
    }
  } else {
    // looking for < 5
    if (c == 'n') { // for testing
      //if (UltraSensor1 < 5) { // for real sensor
      sensor1Near = true;
      Serial.println(F("Sensor is far"));
      return true;
    }
  }
  return false;
}

void loop() {
  if (ledDelay1.justFinished()) { // turn led off
    Serial.println(F("turn relay1 off"));
    digitalWrite(Relay1, LOW); // off
  }

  if (condition1()) {
    ledDelay1.start(ledDelay1_mS);
    Serial.println(F("turn relay1 on"));
    digitalWrite(Relay1, HIGH); // on
  }
}

void SonarSensor(int trigPinSensor, int echoPinSensor) {
  digitalWrite(trigPinSensor, LOW);// put trigpin LOW
  delayMicroseconds(2);// wait 2 microseconds
  digitalWrite(trigPinSensor, HIGH);// switch trigpin HIGH
  delayMicroseconds(10); // wait 10 microseconds
  digitalWrite(trigPinSensor, LOW);// turn it LOW again

  duration = pulseIn(echoPinSensor, HIGH);
  distance = (duration / 2) / 29.1;
}

drmpf:
Try this code
Only one sensor implemented and using Serial input to set near or far distance

#include <millisDelay.h>

millisDelay ledDelay1; // the delay object for led
unsigned long ledDelay1_mS = 3000;

#define trigPin1 9
#define echoPin1 8
#define Relay1 6

#define trigPin2 10
#define echoPin2 11
#define Relay2 7

long duration, distance, UltraSensor1, UltraSensor2; //we’ll use these variable to store and generate data
bool sensor1Near = false;

void setup() {

pinMode(trigPin1, OUTPUT);
 pinMode(echoPin1, INPUT);
 pinMode(Relay1, OUTPUT);

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

Serial.begin(115200);
 // wait a few sec to let user open the monitor
 for (int i = 5; i > 0; i–) {
   delay(1000);
   Serial.print(i); Serial.print(’ ');
 }
 Serial.println();
 Serial.println(“Enter n for near and f for far”);
 // set  sensor1Near based on dist
 sensor1Near = false;
 Serial.println(“Currently sensor is far”);
}

bool condition1() {  // returns when the condition is true
 char c = ’ ';
 if (Serial.available()) {
   c = Serial.read();
 }
 if (sensor1Near) {
   // looking for > 5
   if (c == ‘f’) { // for testing
     //  if (UltraSensor1 > 5) { // for real sensor
     sensor1Near = false;
     Serial.println(F(“Sensor is near”));
     return true;
   }
 } else {
   // looking for < 5
   if (c == ‘n’) { // for testing
     //if (UltraSensor1 < 5) { // for real sensor
     sensor1Near = true;
     Serial.println(F(“Sensor is far”));
     return true;
   }
 }
 return false;
}

void loop() {
 if (ledDelay1.justFinished()) { // turn led off
   Serial.println(F(“turn relay1 off”));
   digitalWrite(Relay1, LOW); // off
 }

if (condition1()) {
   ledDelay1.start(ledDelay1_mS);
   Serial.println(F(“turn relay1 on”));
   digitalWrite(Relay1, HIGH); // on
 }
}

void SonarSensor(int trigPinSensor, int echoPinSensor) {
 digitalWrite(trigPinSensor, LOW);// put trigpin LOW
 delayMicroseconds(2);// wait 2 microseconds
 digitalWrite(trigPinSensor, HIGH);// switch trigpin HIGH
 delayMicroseconds(10); // wait 10 microseconds
 digitalWrite(trigPinSensor, LOW);// turn it LOW again

duration = pulseIn(echoPinSensor, HIGH);
 distance = (duration / 2) / 29.1;
}

Finally someone understood that I am not a hacker and gave me finished code (I know to add other sensor It’s not problem) :smiley:
I tried the code, when I go into the serial monitor and type n for near and f for far. When I get out of the monitor nothing happens., and serial monitor is not showing current distance. Did I make a mistake somewhere?

When I get out of the monitor nothing happens.

Not sure what you mean here. The sample code does not actually read the UltraSensor but instead uses n and f to simulate the test for distance.
Check out the

  // looking for > 5[i][/i]
    if (c == 'f') { // for testing[i][/i]
      //  if (UltraSensor1 > 5) { // for real sensor

section of the code. You need to replace the if (c == … with the line below

serial monitor is not showing current distance

Ahh… well you need to add the print(UltraSensor1) statements back in.

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