1

I'm working on a project which has falling objects non stop, I only want to detect when objects block the sensors set trigger area. Any suggestions would be great!

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin1 9 // LED 1

int maximumRange = 300; // Maximum range needed
int minimumRange = 10; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
    Serial.begin(9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(LEDPin1, OUTPUT);
}

void loop() {
    /* The following trigPin/echoPin cycle is used to determine the
    distance of the nearest object by bouncing soundwaves off of it. */
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

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

    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    //Calculate the distance (in cm) based on the speed of sound.
    distance = duration/58.2;

    //If the distance is beyond the limits - then nothing happens ie,
    //more than 3 meters or less than 10 cm
    if (distance >= maximumRange || distance <= minimumRange) {
        Serial.println("Nothing Happens");
        digitalWrite(LEDPin1, LOW);
    } else {
        Serial.println("Trigger");
        digitalWrite(LEDPin1, HIGH);
        delay(200);
        delay(50);
    }
}

Arduino uno 4 pin ultrasonic sensor

3
  • Compared to the "Arduino Basics: HC-SR04 Ultrasonic Sensor", in case of "Nothing Happens", why you have removed the delay(50); ? – J. Piquard Dec 6 '16 at 21:22
  • Please elaborate on this question. – sa_leinad Dec 7 '16 at 1:57
  • Objects fall every 20sec approx. Every time an object passes through my target range the led turns on. I'm wonder how to either write a delay or if else statement that would only trigger led to light up in the event these objects start to pile up. So say my target range is blocked for more than 15 sec... then the led would light up. – Awheat54 Dec 7 '16 at 4:29
1

Based on this enter image description here You need at least 10mS delay from each readings to prevent unstable readings.

void loop() {
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

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

    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    distance = duration/58.2;

    if (distance >= maximumRange || distance <= minimumRange) {
        Serial.println("Nothing Happens");
        digitalWrite(LEDPin1, LOW);
    } else {
        Serial.println("Trigger");
        digitalWrite(LEDPin1, HIGH);
    }

delay(10);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.