Advertisement
BlackSunFL

Alarm Sound Arduino

Nov 19th, 2024
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 2.28 KB | Software | 0 0
  1. #include <Wire.h>
  2. #include <LiquidCrystal_I2C.h>
  3.  
  4. // Initialize the LCD (I2C address: 0x27, 16 columns, 2 rows)
  5. LiquidCrystal_I2C lcd(0x27, 16, 2);
  6.  
  7. // Defines pins numbers
  8. const int trigPin = 9;
  9. const int echoPin = 10;
  10. const int buzzerPin = 3; // Buzzer connected to pin 3
  11.  
  12. // Defines variables
  13. long echoDuration; // Changed variable name to avoid conflict
  14. int distance;
  15. const int thresholdDistance = 20; // Distance in cm to trigger the alarm
  16.  
  17. void setup() {
  18.   // Set up the pins
  19.   pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  20.   pinMode(echoPin, INPUT);  // Sets the echoPin as an Input
  21.   pinMode(buzzerPin, OUTPUT); // Sets the buzzerPin as an Output
  22.  
  23.   // Initialise Serial Monitor
  24.   Serial.begin(9600);
  25.  
  26.   // Initialise the LCD
  27.   lcd.init();
  28.   lcd.backlight();
  29.   lcd.setCursor(0, 0);
  30.   lcd.print("Distance: ");
  31. }
  32.  
  33. void loop() {
  34.   // Clears the trigPin
  35.   digitalWrite(trigPin, LOW);
  36.   delayMicroseconds(2);
  37.  
  38.   // Sets the trigPin on HIGH state for 10 microseconds
  39.   digitalWrite(trigPin, HIGH);
  40.   delayMicroseconds(10);
  41.   digitalWrite(trigPin, LOW);
  42.  
  43.   // Reads the echoPin, returns the sound wave travel time in microseconds
  44.   echoDuration = pulseIn(echoPin, HIGH);
  45.  
  46.   // Calculating the distance
  47.   distance = echoDuration * 0.034 / 2; // Speed of sound wave divided by 2 (go-and-back)
  48.  
  49.   // Prints the distance on the Serial Monitor
  50.   Serial.print("Distance: ");
  51.   Serial.println(distance);
  52.  
  53.   // Display the distance on the LCD
  54.   lcd.setCursor(10, 0); // Move cursor to position
  55.   lcd.print("    ");    // Clear previous value
  56.   lcd.setCursor(10, 0);
  57.   lcd.print(distance);
  58.   lcd.print("cm");
  59.  
  60.   // Checks if the distance is below the threshold
  61.   if (distance < thresholdDistance) {
  62.     // Generate intermittent sound
  63.     tone(buzzerPin, 1000); // 1000 Hz frequency
  64.     delay(300); // Sound on for 300 ms
  65.     noTone(buzzerPin); // Turn off sound
  66.     delay(300); // Sound off for 300 ms
  67.  
  68.     // Update LCD with alarm message
  69.     lcd.setCursor(0, 1);   // Second row for alarm message
  70.     lcd.print("ALARM! Too Close");
  71.   } else {
  72.     noTone(buzzerPin); // Turn off the sound if the distance is safe
  73.     lcd.setCursor(0, 1); // Clear alarm message
  74.     lcd.print("                ");
  75.   }
  76.  
  77.   delay(100); // Delay to avoid excessive updates
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement