safwan092

Simple-Alarm-System-Ultrasonic-Buzzers

Nov 21st, 2020
929
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. int BuzzerPin = 5;   // ~(PWM)
  3. int trigPin = 9;
  4. int echoPin = 10;
  5.  
  6. void setup(){
  7.  
  8.   Serial.begin(9600);
  9.   pinMode(BuzzerPin, OUTPUT);
  10.   pinMode(trigPin, OUTPUT);
  11.   pinMode(echoPin, INPUT);
  12. }
  13.  
  14. void loop(){
  15.  
  16.   digitalWrite(trigPin, LOW);
  17.   delayMicroseconds(2);
  18.   digitalWrite(trigPin, HIGH);
  19.   delayMicroseconds(10);
  20.   digitalWrite(trigPin, LOW);
  21.  
  22.   long duration = pulseIn(echoPin, HIGH);
  23.  
  24. /*
  25.  *
  26.  * Speed = Distance / Time   =>   Distance = Time * Speed
  27.  *
  28.  * Speed of Sound = 340 m/s = 34000 cm/s = 0.034 cm/us
  29.  *
  30.  */
  31.  
  32.   float distance = duration * 0.034 / 2. ;
  33.  
  34.   Serial.print("Distance = ");
  35.   Serial.print(distance);
  36.   Serial.println(" cm");
  37.  
  38.   if(distance<100){
  39.  
  40.     analogWrite(BuzzerPin, 255);      // Almost any value can be used except 0 and 255
  41.     delay(100);
  42.     analogWrite(BuzzerPin, 155);      // Almost any value can be used except 0 and 255
  43.     delay(100);
  44.   }
  45.   else{
  46.     analogWrite(BuzzerPin, 0);      // Almost any value can be used except 0 and 255
  47.     }
  48.  
  49.   delay(5);
  50.  
  51. }
  52.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×