Measuring distance once only

I'm trying to turn on and off my dc motors with an IR receiver and it works. However, the dc motors are supposed to stop 20cm before an obstacle (Measuring distance using an ultrasonic sensor hc-sr04). The code I wrote only checks for the distance once when I press the On button. Any help is appreciated :slight_smile:

Here is the code:

#include <IRremote.h>

#include <NewPing.h>



int IrReceiverPin = 52;

decode_results results;

IRrecv irrecv(IrReceiverPin);

int RECV_PIN = 52;// the pin where you connect the output pin of IR sensor

int distance = 0;

NewPing sensor (6 , 5, 100); // trig,echo,max distance in cm





void setup() {

Serial.begin(9600);

pinMode(LED_BUILTIN, OUTPUT);

Serial.println("Starting IR-receiver...");

irrecv.enableIRIn();

Serial.println("IR-receiver active");

digitalWrite(LED_BUILTIN, LOW);

pinMode(8,OUTPUT);//Motor 1

pinMode(9,OUTPUT);//Motor 1

pinMode(12,OUTPUT);//Motor 2

pinMode(13,OUTPUT);//Motor 2

}





void loop() {

if (irrecv.decode(&results)) {

distance = sensor.ping_cm();

Serial.print("Distance is:");

Serial.println(sensor.ping_cm());

Serial.println(results.value, HEX);



irrecv.resume();



switch (results.value) {

case 0xFF02FD or 0xFFFFFFFF: // button ON

while (distance == 0)

digitalWrite(8, HIGH);

digitalWrite(9,LOW);

digitalWrite(12,HIGH);

digitalWrite(13,LOW);

break;

while (distance <= 20)

digitalWrite(8,LOW);

digitalWrite(9,LOW);

digitalWrite(12,LOW);

digitalWrite(13,LOW);

break;

break;



case 0xFF9867 : // button OFF

digitalWrite(8,LOW);

digitalWrite(9,LOW);

digitalWrite(12,LOW);

digitalWrite(13,LOW);

break;

}



}



}

In your while loops, only the first line after while is part of the loop… you may need some { braces } to gather together several simp,e statements, all to be part of the while body.

Also, as written, the while loops are infinite in nature as you do never solicit the distance again from your sensor. The while condition does not change, if it ever was true, your code gets stucked in the while.

Solution: you must read the distance again and again as you test for the distances that matter to what you want to digital write.

a7

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