-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultrasonic.ino
43 lines (37 loc) · 2.29 KB
/
ultrasonic.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <LiquidCrystal.h> //Load Liquid Crystal Library
LiquidCrystal LCD(7, 6, 5, 4, 3, 2); //Create Liquid Crystal Object called LCD
int trigPin = 11; //Sensor Trip pin connected to Arduino pin 11
int echoPin = 10; //Sensor Echo pin connected to Arduino pin 10
int myCounter = 0; //declare your variable myCounter and set to 0
int servoControlPin = 6; //Servo control line is connected to pin 6
float pingTime; //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in centimeters
float speedOfSound = 776.5; //Speed of sound in miles per hour when temp is 77 degrees.
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
LCD.begin(16, 2); //Tell Arduino to start your 16 column 2 row LCD
LCD.setCursor(0, 0); //Set LCD cursor to upper left corner, column 0, row 0
LCD.print("Target Distance:"); //Print Message on First Row
}
void loop() {
digitalWrite(trigPin, LOW); //Set trigger pin low
delayMicroseconds(2000); //Let signal settle
digitalWrite(trigPin, HIGH); //Set trigPin high
delayMicroseconds(15); //Delay in high state
digitalWrite(trigPin, LOW); //ping has now been sent
delayMicroseconds(10); //Delay in high state
pingTime = pulseIn(echoPin, HIGH); //pingTime is presented in microseconds
pingTime = pingTime / 1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
pingTime = pingTime / 3600; //convert pingtime to hours by dividing by 3600 (seconds in an hour)
targetDistance = speedOfSound * pingTime; //This will be in miles, since speed of sound was miles per hour
targetDistance = targetDistance / 2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
targetDistance = targetDistance * 2.54 * 100; //Convert miles to centimeters by multiplying by 2.54 (centimeters per inch) and 100 to convert to centimeters.
LCD.setCursor(0, 1); //Set cursor to first column of second row
LCD.print(" "); //Print blanks to clear the row
LCD.setCursor(0, 1); //Set Cursor again to first column of second row
LCD.print(targetDistance); //Print measured distance
LCD.print(" cm"); //Print your units.
delay(250); //pause to let things settle
}