Distance Sensor
This months project is a really cool and simple build distance sensor using leds as well as a buzzer, with of course Arduino. For me I appreciated getting the ping sensor mainly because I only have one and its in use now so having two is handy.
-Leds
-Buzzer
-Sensor
-Uno
-Breadboard
-Resistors
-Jumpers
Step#1:
Begin by placing leds into breadboard negative facing left, as well insert buzzer and sensor. This setup is quite simple and their isnt really much work making these connections. if you find your leds are not lighting up try flipping them.
Step#3: Connecting to Arduino
Gather you jumper wires and connect one end from each led the leds are connected to the Arduino digital in pins. Pin 8-12. Next the Buzzer is connected to pin 3. The sensor is connected to 5v, ground, and trig is connected to pin 6 and echo is connected to pin 6. I shouldnt have to mention ground to ground on arduino and 5v to 5v....
Step#4: Load Up Code
// License: GNU General Public License
// Creation Crate Month 3 - Distance Detector
#define red2 13
#define red1 12
#define yellow2 11
#define yellow1 10
#define white2 9
#define white1 8
#define buzzer 3
#define trigPin 7
#define echoPin 6
int sound = 250;
long duration, distance;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(white1, OUTPUT);
pinMode(white2, OUTPUT);
pinMode(yellow1, OUTPUT);
pinMode(yellow2, OUTPUT);
pinMode(red1, OUTPUT);
pinMode(red2, OUTPUT);
pinMode(buzzer, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
// send out pulse waves for measuring the distance of an object
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// the amount of time it took for the pulse to return
duration = pulseIn(echoPin, HIGH);
// distance in cm
distance = duration / 58.2; //(duration / 2) / 29.1;
// manipulate leds based on distance calculated
if (distance <= 40) {
digitalWrite(white1, HIGH);
sound = 900;
}
else {
digitalWrite(white1, LOW);
}
if (distance < 30) {
digitalWrite(white2, HIGH);
sound = 1000;
}
else {
digitalWrite(white2, LOW);
}
if (distance < 20) {
digitalWrite(yellow1, HIGH);
sound = 1100;
}
else {
digitalWrite(yellow1, LOW);
}
if (distance < 15) {
digitalWrite(yellow2, HIGH);
sound = 1200;
}
else {
digitalWrite(yellow2, LOW);
}
if (distance < 10) {
digitalWrite(red1, HIGH);
sound = 1300;
}
else {
digitalWrite(red1, LOW);
}
if (distance < 5) {
digitalWrite(red2, HIGH);
sound = 1400;
}
else {
digitalWrite(red2, LOW);
}
Serial.print("Duration: ");
Serial.print(duration);
Serial.print(", ");
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(", ");
// if object is too far, turn buzzer off
if (distance > 40 || distance <= 0) {
Serial.println("Out of range");
noTone(buzzer);
}
else {
Serial.println("in");
tone(buzzer, sound);
}
delay(500);
}