// ultrasonic sensor code
// declaring vairable for duration and distance
float distance;
float duration;
void setup() {
// begins serail communication with the baud rate of 9600 bits
Serial.begin(9600);
// trig pin(triggers the ultrasonic sensor to throw waves)
pinMode(18, OUTPUT);
//echo pin(a singal is sent to the arduino if any obstruction is found in the waves)
pinMode(17, INPUT);
// led
pinMode(4, OUTPUT);
}
void loop() {
digitalWrite(18, HIGH);
delay(10); // wait for 10 microseconds
digitalWrite(18, LOW);
// calculates the duration of the wave after obstruction
duration = pulseIn(17, HIGH);
// calculates the distance between the object that obstructed and the sensor
distance = duration * 0.017;
if(distance > 50)
{
digitalWrite(4, HIGH); // if distance is lower that 50, led is turned on
}
else
{
digitalWrite(4, LOW); // if distance is higher than 50, led is turned off
}
// prints the distance
Serial.print("distance: ");
Serial.print(distance);
Serial.print(" cm");
}