#include <SoftwareSerial.h>
int buzzerPin = 8; // Pin number the buzzer is connected
int echoPin = 11; // Echo Pin of the ultrasonic sensor
int trigPin = 12; // Trigger Pin of the ultrasonic sensor
unsigned long previousMillis = 0; // Store the previous trigger time for buzzer
int maxBeepInterval = 1000; // Max beep interval
int minBeepInterval = 300; // Min beep interval
int frequency = 1000; // Buzzer frequency in Hz
float distance; // Distance of the object from sensor
long echoTime; // Time taken for the echo
int triggerAlarmDistance = 40; // Buzzer will be triggered if the distance is less than this value (cm)
const int ledPin = 13;
long duration;
void setup() {
pinMode(buzzerPin, OUTPUT); // Set pin modes
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // Initialize serial communication
}
void loop() {
{
digitalWrite(trigPin, LOW); // Set the trigger pin of the SR04 sensor to low
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Send a pulse
delayMicroseconds(10);
digitalWrite(trigPin, LOW); // Set the trigger pin low
echoTime = pulseIn(echoPin, HIGH); // Measure echo time
distance = echoTime * 0.0340 / 2; // Calculate distance
if (distance < triggerAlarmDistance) { // If object is within trigger distance
unsigned long currentMillis = millis();
int val = map(distance, 2, triggerAlarmDistance, minBeepInterval, maxBeepInterval); // Map distance to beep interval
Serial.println("Sent SMS!");
Serial.println("Dustbin is at maximum level");
if (currentMillis - previousMillis >= val) { // Check if it's time to trigger the buzzer
tone(buzzerPin, frequency, val * 0.75); // Trigger the buzzer
previousMillis = currentMillis; // Save current time
}
}
delay(6000); // Delay before next
}
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = 0.034 * (duration / 2);
if (distance < 27)
{
digitalWrite(ledPin, HIGH);
delay(1000);
}
else
{
digitalWrite(ledPin, LOW);
}
delay(300);
}