0% found this document useful (0 votes)
4 views2 pages

Ultrasonic Arduino Code

The document contains Arduino code for an ultrasonic distance measuring system. It defines pins for triggering and receiving echo signals, calculates distance based on the duration of the echo, and uses an onboard LED to indicate if the measured distance is out of the specified range. The code continuously measures distance and outputs the result via the serial monitor.

Uploaded by

Marwa AlFaouri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Ultrasonic Arduino Code

The document contains Arduino code for an ultrasonic distance measuring system. It defines pins for triggering and receiving echo signals, calculates distance based on the duration of the echo, and uses an onboard LED to indicate if the measured distance is out of the specified range. The code continuously measures distance and outputs the result via the serial monitor.

Uploaded by

Marwa AlFaouri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Ultrasonic Arduino Code

#define echoPin 7 // Echo Pin


#define trigPin 6 // Trigger Pin
#define LEDPin 13 // Onboard LED
int maximumRange = 200; // Maximum range needed
int minimumRange = 5; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT); // declare trig pin as output
pinMode(echoPin, INPUT); // declare trig pin as output
pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); //calculate the period
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
if (distance >= maximumRange || distance <= minimumRange){
Serial.println("-1");
digitalWrite(LEDPin, HIGH);
}
else {
int d=distance;
Serial.print("Distance = ");
Serial.print(d);
Serial.println("cm");
digitalWrite(LEDPin, LOW);
}
delay(100);
}

You might also like