// Constants for digital pins
const int trigPin = 13; // Digital pin for the trigger signal
const int echoPin = 12; // Digital pin for the echo signal
const int buzzerPin1 = 4; // Digital pin for the buzzer
const int buzzerPin2 = 3; // Digital pin for the buzzer
const int buzzerPin3 = 2; // Digital pin for the buzzer
const int buzzerPin4 = 1; // Digital pin for the buzzer
// Constant for the analog pin
const int potPin = A0; // Analog pin for the potentiometer
// Variables for the ultrasonic sensor
float duration, distance;
// Variable for the potentiometer value
int potValue;
void setup() {
// Setup for digital pins
pinMode(trigPin, OUTPUT); // Set the trigger pin as an output
pinMode(echoPin, INPUT); // Set the echo pin as an input
pinMode(buzzerPin1, OUTPUT); // Set the buzzer pin as an output
pinMode(buzzerPin2, OUTPUT); // Set the buzzer pin as an output
pinMode(buzzerPin3, OUTPUT); // Set the buzzer pin as an output
pinMode(buzzerPin4, OUTPUT); // Set the buzzer pin as an output
// No setup for analog pin required (no need to set pinMode for analog input)
// Initialize serial communication
Serial.begin(9600);
}
void loop() {
readUltrasonic();
readPot();
controlBuzzer();
delay(distance);
}
// Reading a digital input
void readUltrasonic() {
// Send a low pulse to ensure the trigger pin is low
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // Wait for 2 microseconds
// Send a high pulse to trigger the ultrasonic sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Wait for 10 microseconds to ensure the pulse is sent
digitalWrite(trigPin, LOW); // Set the trigger pin back to low
// Measure the duration of the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance based on the duration
// Speed of sound is approximately 0.0343 cm/us
// Dividing by 2 because the pulse travels to the object and back
distance = (duration * 0.0343) / 2;
// Display the calculated distance
Serial.print("Distance: ");
Serial.println(distance);
}
// Reading an analog input
void readPot() {
// Read the analog input from the potentiometer
potValue = analogRead(potPin); // Read the value from the potentiometer (0-1023)
// Display the potentiometer value
Serial.print("Potentiometer Value: ");
Serial.println(potValue);
}
void controlBuzzer() {
// Map the potentiometer value (0-1023) to a PWM value (0-255)
int pwmValue = map(potValue, 0, 1023, 0, 255);
// Generate the tone at a specific frequency
tone(buzzerPin1, pwmValue, distance);
delay(distance + 50);
tone(buzzerPin2, (pwmValue/2 + (pwmValue/4)), distance);
delay(distance + 50);
tone(buzzerPin3, (pwmValue/2), distance);
delay(distance + 50);
tone(buzzerPin4, (pwmValue/4), distance);
}