Using Push button to activate HC-SR04 ultrasonic Sesnor

Dear all,

I am working on a project currently and i faced some problems with it.

How i want to implement the project is:

When i pressed and released the push button, the HC-SR04 ultrasonic Sesnor will start sensing and display the distance constantly in the serial monitor.

when i pressed and release the push button again, the HC-SR04 ultrasonic Sesnor will stop sensing.

However what is happening currently is i need to press and hold the push button to produce the distance constantly and to display in the serial monitor. I believe de-bouncing is needed.

Anyone has any better recommendations to produce the way I want in this project?

#define trigPin 52
#define echoPin 53
#define togglePin 8
int maximumRange = 400; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() 

{
  // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
}

void loop() 
{
  // put your main code here, to run repeatedly:  
   if (digitalRead(togglePin)== HIGH)
   {
  // reset the trigger status
   digitalWrite(trigPin, LOW); 
   delayMicroseconds(2);
  
  // activate the trigger status 
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(10);
  
  // de-activate the trigger status   
   digitalWrite(trigPin, LOW);
   
  
  /* 1) start recording the timing when see a HIGH in echoPin and 
     2) stop recording the timing when see a LOW in echoPin */  
   duration = pulseIn(echoPin, HIGH);

  // Calculate the distance (in cm) based on the speed of sound.
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
   distance = duration/(29.1*2);

   if (duration == 0 && digitalRead(echoPin) == HIGH) 
   {
        pinMode(echoPin, OUTPUT);
        digitalWrite(echoPin, LOW);
        delay(10);
        pinMode(echoPin, INPUT); 
   }
   else if (distance >= maximumRange)
   {
        Serial.print("OUT OF RANGE");
        Serial.println();
   }
   else
   {
        Serial.print("1st Sensor: ");
        Serial.print("Distance: ");
        Serial.print(distance);
        Serial.print("cm");
        Serial.println();
   }
  //Delay 100ms before next reading.
   delay(100);
   }
}

It is doing exactly what you programmed it to do.

What you have to do is to remember the last button state and only trigger when the current button is pressed and the last state was unpressed. Then use that event to toggle a logic variable that controls if you pulse and display or not.

Grumpy_Mike:
It is doing exactly what you programmed it to do.

What you have to do is to remember the last button state and only trigger when the current button is pressed and the last state was unpressed. Then use that event to toggle a logic variable that controls if you pulse and display or not.

I have tried but i still cannot get the results i want. Can anyone share the code here? Thank you very much :slight_smile:

I have tried but i still cannot get the results i want.

So post the code where you implemented what I told you and we can see where you went wrong.

Here is my code that I used and it worked to switch on and off the reading of the sensor

int pushbutton=2;
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(pushbutton,INPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {

// Clears the trigPin
if(digitalRead(pushbutton)==HIGH){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds

duration = pulseIn(echoPin, HIGH);

// Calculating the distance
distance= duration*0.034/2;

// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
delay(1000);
}
}

This is a photo of the switch I am using , it is not a push button.

images.jpg

Please read the how to use the forum sticky post about posting code.

the 'button' you linked a picture of is not a pushbutton, it's a switch.

a pushbutton is something that automatically (usually by spring) returns to a natural state after being actuated.

the switch you linked will operate much like an on/off switch, thus, when you flip the switch to it's 'on' position, it is registering the high voltage you wanted it to, and running the range sensor.

when it is returned to the 'off' state, it doesn't.

if you want to use the switch as a pushbutton, so that you flick it to on, then off, then yes, you'll need to essentially 'debounce' the signal, but in this case, because the switch could be on for 1 ms, or 2 seconds before it goes back to low, you can't just use a default time for it..

the following code should work for a push button, a momentary switch, or a manual switch like what it sounds like you're using.

what it does - when the input changes from low to high, toggle the sonar. (using ! in front of a variable basically inverts the value; so with a boolean variable x, x = 1, !x = 0 )

boolean sonarOn = false;
boolean sonarSwitchLast = false;

if (digitalRead(togglePin)== HIGH)
 {
 if (!sonarSwitchLast)
 {
 sonarOn = !sonarOn;
 sonarSwitchLast = true;
 }
 }
else
 {
 if (sonarSwitchLast)
 {
 sonarSwitchLast = !sonarSwitchLast;
 }
 }

if (sonarOn)
{
 //do the sonar reading thing here
}

(sorry about the weird indentations, i learned programming starting with QuickBasic, so i have some weird habits stemming from needing to be able to print out my code, and have it marked on with pen by an instructor)

if you run into issues where it runs sparadically when you have NOT flipped the switch, look into the 'standard' debounce options, and insert a second check (in the same if statements) to make sure the switch has been on for a set amount of time before registering it as definetly on

@ dananabil seems to have hijacked this thread. That is against the forum rules.

Please read this:- How to use this forum