-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUltrasonic Buzzer
More file actions
48 lines (39 loc) · 2.56 KB
/
Ultrasonic Buzzer
File metadata and controls
48 lines (39 loc) · 2.56 KB
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
44
45
46
47
48
//Set Up: Ultrasonic trigPin in 9, Ultrasonic echoPin in 10, Ultrasonic Vcc in 5v, Ultrasonic Gnd in power GND
//Set Up; LED in pin 11, GND in digital GND, resistor connected to
const int trigPin = 9; //defines trig to what pin
const int echoPin = 10; //deinfes echo to what pin
const int buzzer = 6; //##
long duration; //defines variable for the travel time it takes to get from the sensor to the interger
//"long" is a data type that means it can store 32 bits, and "duration" is the name of the variable
int distance; //integer variable for the distance
int safetyDistance; //##
void setup() {
pinMode(trigPin,OUTPUT); //trigPin defined as output
pinMode(echoPin,INPUT); //echoPin defined as input
Serial.begin(9600); //start serial communication for showing results on the Serial Monitor in the loop
//serial communication is used for communication between the arduino board and another device (in this case, the sensor) https://www.arduino.cc/reference/en/language/functions/communication/serial/
pinMode(buzzer,OUTPUT); //##
}
void loop() {
digitalWrite(trigPin,LOW); //makes sure the pin is clear
delayMicroseconds(2); //keeps sensor from emitting any waves for (x) microseconds
digitalWrite(trigPin,HIGH); //creates ultrasonic sound wave
delayMicroseconds(10); //sends out ultrasonic sound wave for (x) microseconds
digitalWrite(trigPin,LOW); //stops sensor from emitting ultrasonic waves
duration = pulseIn(echoPin,HIGH); // "pulseIn()" with "duration" reads the travel time; pulseIn waits for echoPin to go HIGH, caused by the bounced sound wave till when the pin goes LOW and records that time in microsecondsd
distance = duration*0.034/2; //to get the distance, the duration is multiplied times 0.034 (the speed of the wave) and divded by two
safetyDistance = distance; //##variable "safetyDistance" correlates with distance recorded from ultrasonic sensor
if (safetyDistance <= 10){ //if distance is less than or equal to (safetyDistance <= 10), then...
digitalWrite(buzzer,HIGH); //...then the buzzer turns on
delay(150);
digitalWrite(buzzer,LOW);
delay(150);
}
else{ //if not that^ (if distance is greater than x away), then...
digitalWrite(buzzer,LOW); //...then buzzer is off
//no delay is needed because after they turn on, the code will re-loop and go through the if else again
}
Serial.print("Distance:"); //prints the value of the distance on the Serial Monitor
Serial.println(distance); //says "distance" in serial monitor
}
// https://www.youtube.com/watch?v=ZejQOX69K5M