distance warning system

I am trying to create a program where an ultrasound sensor measures distance.

Create a sketch that calls on the ultrasound file, then

lights a green LED if d > 20 cm

lights a yellow LED if 20 > d > 10 cm

lights a red LED if d < 10 cm

You should have a buzzer making a tone that increases in pitch as you cross over from Grn, Ylw, Red

You should have a serial monitor indicating distance. It should read: “Distance is ___ cm”

I also attached what i have done so far. I am getting zero all the time and i don’t know why. Any guidance will be appreciated. Thank you

Measuring_distance.ino (1.23 KB)

ultra.ino (306 Bytes)

Please post your code - those of us on mobile devices can't see your code.

Circuit diagram will also be useful.

Getting all zero for distance often means miswired/faulty sensor.

You set your input pin as an output:

  pinMode (echoPin, OUTPUT);

unsigned long ultrasound();
#define trigPin 16
#define echoPin 14
#define buzzer 13
#define red 2
#define yellow 0
#define green 4
int sound = 250;

void setup() {

Serial.begin (9600);
pinMode (trigPin, OUTPUT);
pinMode (echoPin, OUTPUT);
pinMode (red, OUTPUT); // setting them to light up
pinMode (yellow, OUTPUT);
pinMode (green, OUTPUT);
pinMode (buzzer, OUTPUT);

// put your setup code here, to run once:


void loop() {

int duration, distance;
digitalWrite (trigPin, LOW);
delay (1);

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

digitalWrite (trigPin, LOW);

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

if (distance > 20)

digitalWrite (green, HIGH);
sound = 250;

else {
digitalWrite(green, LOW);

if ((distance < 20)&&(distance >10))
digitalWrite (yellow, HIGH);
sound = 260;

digitalWrite (yellow, LOW);
if (distance <10)
digitalWrite (red, HIGH);
sound = 270;
digitalWrite (red, LOW);

Serial.print(“Distance is “);
Serial.println(” cm”);
tone (buzzer, sound);

delay (500);


You might want to resolve the issue Pert pointed out in reply #3.

unsigned long ultrasound(); Where is it?

Please remember to use code tags when posting code.

Thank you SHANON. That was my only mistake. Really appreciate your help everyone