Saturday, August 5, 2017

Moving dot display of Distance

Moving Dot Display of distance (Ultrasonic)

The further the object is from the sensor the more LEDs turn on. Each LED is calibrated for 10cm. If you're using a 4 pin ultrasonic sensor (eg HC-SR04) simply jumper the echo (sig) and the trig pin together.



Challenge add a sound output alarm when things get too close

--------------------------- Copy Code Below
const int pingPin = 7;

void setup()
{
// initialize serial communication:
Serial.begin(9600);
}

void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration;
long cm;

// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);

// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

// convert the time into a distance
 cm = microsecondsToCentimeters(duration);

if (cm > 2 && cm < 4)
digitalWrite(13, HIGH);
else if (cm > 4 && cm < 6)
digitalWrite(12, HIGH);
else if (cm > 6 && cm < 8)
digitalWrite(11, HIGH);
else if (cm > 8 && cm < 10)
digitalWrite(10, HIGH);
else if (cm > 10 && cm < 11)
digitalWrite(9, HIGH);
else if (cm > 12)
digitalWrite(8, HIGH);
  
 Serial.print(cm);
 Serial.print("cm");
 Serial.println();
 delay(100);
if (cm < 10)
{
tone(6, 1000);
}
else
{
noTone(6);
}
 digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
digitalWrite(12, LOW);
digitalWrite(13,LOW);
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance traveled.
  return microseconds / 29 / 2;
}

No comments:

Post a Comment