Ultrasonic Sensor Problem

First off, I would just like to say that I am a beginner and barely know the basics of Arduino. I tried to make a circuit which would have a LED light up when an object is put at a distance closer than 10 cm relative to the ultrasonic sensor. I was wondering why the LED would not light up and a distance more than 0 cm would not be displayed on the Serial Monitor.

Here is my code...


const int trigpin = 11;

const int echopin = 8;

const int led = 4;

void setup() {
Serial.begin(9600);
pinMode (trigpin, OUTPUT);
pinMode (echopin, INPUT);
pinMode (led, OUTPUT);
}

void loop() {

long duration, distance;
digitalWrite (trigpin, HIGH);
delayMicroseconds(1000);
duration = pulseIn(echopin, HIGH);
distance = (duration/2)/29.1;
Serial.print (distance);
Serial.println ("CM");
delay (10);

if ((distance <= 10))
{
digitalWrite (led, HIGH);
}
else if (distance> 10);
{
digitalWrite (led, LOW);
}
}


Change :

  • delayMicroseconds(1000) to delayMicroseconds(10)
  • distance = (duration/2)/29.1 to distance_cm = 0.017 * duration_us;

Refer to instruction about Ultrasonic Sensor

It still wont work. Do you think that maybe the sensor is broken?

You need to add: digitalWrite (trigpin, LOW) after delayMicroseconds(10). If still not work, check your wiring diagram and code in comparison with the link I mentioned above. If still not work, post the image of real wiring diagram.

It still wont work so here is the attached picture. Thank you again for helping and sorry for late reply.