1

I have a HC-SR04 Ultrasonic sensor connected to my Arduino Uno. The problem I'm having is when I check the Serial Monitor to see if the sensor is working: it only says "Out of Range" regardless of the distance. I believe I may have the distance calculation wrong because the RedLED stays on and the buzzer doesn't go off.

Here's my .ino code:

#define trigPin 6
#define echoPin 7
#define RedLED 9
#define buzzer 3

int sound = 500;


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

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/5) / 29.1;


  if (distance < 20) {
   digitalWrite(RedLED, HIGH);
   sound = 1000;
}
 else {
   digitalWrite(RedLED,LOW);
 }

 if (distance > 20 || distance <= 0){
   Serial.println("Out of range");
   noTone(buzzer);
 }
 else {
   Serial.print(distance);
   Serial.println(" cm");
   tone(buzzer, sound);

 }
 delay(300);
}

1 Answers1

0

Can't post a comment so I'll post it in Answer.

Check that you have connected VCC to 5v and not to 3.3v.
I think your calculations are ok. Also to exclude calculations just print the duration and see if it changes.

sgrig
  • 111
  • 1
  • 4