Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const int TRIG_PIN = 9;
- const int ECHO_PIN = 10;
- const int BUZZER = 11;
- int LED = 12;
- long duration;
- int distance;
- int safetyDistance;
- void setup() {
- Serial.begin(9600);
- pinMode(TRIG_PIN,OUTPUT);
- pinMode(ECHO_PIN,INPUT);
- pinMode (BUZZER , OUTPUT);
- }
- void loop() {
- // Clears the trigPin
- digitalWrite(TRIG_PIN, LOW);
- delayMicroseconds(2);
- // Sets the trigPin on HIGH state for 10 micro seconds
- digitalWrite(TRIG_PIN, HIGH);
- delayMicroseconds(10);
- digitalWrite(TRIG_PIN, LOW);
- // Reads the echoPin, returns the sound wave travel time in microseconds
- duration = pulseIn(ECHO_PIN, HIGH);
- // Calculating the distance
- distance= duration*0.034/2;
- safetyDistance = distance;
- if (safetyDistance >= 5 && safetyDistance <= 10 ){
- for(int fadeValue = 10 ; fadeValue <= 200; fadeValue +=5)
- analogWrite(BUZZER, fadeValue);
- }
- else if (safetyDistance >= 10 && safetyDistance <= 18 ){
- for(int fadeValue = 200 ; fadeValue >= 50; fadeValue -=5)
- analogWrite(BUZZER, fadeValue);
- }
- else if (safetyDistance >= 18 && safetyDistance <= 20 ){
- for(int fadeValue = 200 ; fadeValue >= 0; fadeValue -=5)
- analogWrite(BUZZER, fadeValue);
- }
- // Prints the distance on the Serial Monitor
- Serial.print("Distance: ");
- Serial.println(distance);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement