// Constans for digital pins
const int usTrig = 13; // Digital pin for the trigger signal
const int usEcho = 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
// Constant for the analog pin
const int potPin = A0; // Analog pin for the potentiometer
// Variables for the ultrasonic sensor
float duration, distance;
int condition;
// Variable for the potentiometer value
int potValue;
void setup() {
// Setup for digital pins
pinMode(usTrig, OUTPUT); // Sets the trigger pin as an output
pinMode(usEcho, INPUT); // Sets the echo pin as an output
pinMode(BuzzerPin1, OUTPUT); // Sets the buzzer pin as an output
pinMode(BuzzerPin2, OUTPUT); // Sets the buzzer pin as an output
// No setup for analog pin required (no need to set pinMode for analog input)
// Initialise serial communication
Serial.begin(9600);
}
void loop() {
readUltrasonic();
readPot();
MotionSensor();
delay(1000);
}
// Reading a digital input
void readUltrasonic() {
// Send a low pulse to ensure the trigger pin is low
digitalWrite(usTrig, LOW);
delayMicroseconds(2); // Wait for 2 microseconds
// Send a high pulse to trigger the ultrasonic sensor
digitalWrite(usTrig, HIGH);
delayMicroseconds(10); // Wait for 10 microseconds to ensure the pulse is sent
digitalWrite(usTrig, LOW); // Set the trigger pin back to low
// Measure the duration of the echo pulse
duration = pulseIn(usEcho, HIGH);
// Calculate the distance based on the direction
// 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() {
potValue = analogRead(potPin); // Read the value from the potentiometer (0-1023)
// Display the potentiometer value
Serial.print("Potentiometer Value: ");
Serial.println(potValue);
}
void potentiometermap() {
condition = map(potValue, 0, 1023, 2, 400);
Serial.print("condition Value: ");
Serial.println(condition);
}
void MotionSensor() {
readPot();
readUltrasonic();
potentiometermap();
if (distance < condition)
{
// 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 frequecy
// Tone (pin, freq, duration)
tone(BuzzerPin1, 100, 150);
tone(BuzzerPin2, 150, 150);
}
}