//For Ultrasonic Sensor
#define trig_Pin 9
#define echo_Pin 10
#define buzzer 11
#define ledPin 13
#define potPin A0
//Detection Distance in CM
unsigned int detectDistance; //For Storing the detection Distance
unsigned int baseDetection = 5; //Base Value for the DetectDistance in case the Potentiometer does not work
unsigned int potValue; //For Storing the mapped values for potentiometer
//For Timing: Reading Sensor every set time
unsigned long currentMillis; //For storing arduino built-in timer
unsigned long previousMillis; //For Storing the last/previous Millis recorded
unsigned long refreshRate = 1000; //1000 = 1 sec; Change this if you want faster readings the lower the number the faster
void setup() {
//For Ultrasonic Sensor Pin Mode
pinMode(trig_Pin, OUTPUT); //Trigger Pin at pin 9
pinMode(echo_Pin, INPUT); //Echo Pin at pin 10
//For Potentiometer Pin Mode
pinMode(potPin, INPUT); //Potentiometer center pin at pin A0
//For Output Pin Mode
pinMode(buzzer, OUTPUT); //Buzzer at Pin 11
pinMode(ledPin, OUTPUT); //Led at Pin 13
Serial.begin(9600); // Starts the serial communication
}
void loop() {
input(); //Input code run
output(); //Output code run
}
//for Checking Distance using Ultrasonic
float checkdistance() {
digitalWrite(trig_Pin, LOW);
delayMicroseconds(2);
digitalWrite(trig_Pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_Pin, LOW);
//Reads the emitted echo from the Trigger Pin and calculates
//it for how long the echo travels from the reflected surface
float distance = pulseIn(echo_Pin, HIGH) / 58.00;
delay(10);
//everytime the check distance will be called out
//it will give the value of distance
return distance;
}
//for all input program
void input()
{
//mapping the values for the potentiometer which will be added to the detectDistance's value
potValue = analogRead(potPin);
unsigned int adjustedValue = map(potValue, 0, 1023, 0, 95);
detectDistance = baseDetection + adjustedValue;
}
//for output program
void output()
{
//Time Starts now
currentMillis = millis();
//If refreshRate elapsed or If target time is achieved
if (currentMillis - previousMillis >= refreshRate)
{
//Checks the distance and send it to the Serial Monitor
Serial.print("Reading: ");
Serial.println(checkdistance());
Serial.print("Set Distance: ");
Serial.println(detectDistance);
//If read distance is less than or equals to the set detect distance
if (checkdistance() <= detectDistance)
{
//For LED Output
digitalWrite(ledPin, HIGH); //sets the led turned on
//For Buzzer Output
digitalWrite(buzzer, HIGH); //sets the buzzer turned on
}
//else the read distance is greater than the set detect distance
else
{
//For LED Output
digitalWrite(ledPin, LOW); //sets the led turned off
//For Buzzer Output
digitalWrite(buzzer, LOW); //sets the buzzer turned off
}
}
}