0% found this document useful (0 votes)
3 views

Ultrasonic Code Slide Layout

This document contains an Arduino sketch that controls a servo motor and provides distance feedback using ultrasonic sensors. It includes setup for LED indicators and a buzzer to signal different distance ranges. The loop continuously sweeps the servo from 0 to 180 degrees and back, measuring distance and providing visual and auditory feedback based on the measured distance.

Uploaded by

nikksji22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Ultrasonic Code Slide Layout

This document contains an Arduino sketch that controls a servo motor and provides distance feedback using ultrasonic sensors. It includes setup for LED indicators and a buzzer to signal different distance ranges. The loop continuously sweeps the servo from 0 to 180 degrees and back, measuring distance and providing visual and auditory feedback based on the measured distance.

Uploaded by

nikksji22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <Servo.

h>
const int trigPin = 9, echoPin = 10, servoPin = 6, redLED = 2, blueLED = 3, yellowLED = 4, buzzerPin = 13;
Servo myServo; long duration; int distance, angle;

void setup() {
pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);
pinMode(redLED, OUTPUT); pinMode(blueLED, OUTPUT); pinMode(yellowLED, OUTPUT);
pinMode(buzzerPin, OUTPUT); myServo.attach(servoPin); Serial.begin(9600);
}

void loop() {
for (angle = 0; angle <= 180; angle += 2) {
myServo.write(angle); Serial.print("Angle: "); Serial.println(angle);
delay(15); distance = getDistance(); feedback(distance);
}
for (angle = 180; angle >= 0; angle -= 2) {
myServo.write(angle); Serial.print("Angle: "); Serial.println(angle);
delay(15); distance = getDistance(); feedback(distance);
}
}

int getDistance() {
digitalWrite(trigPin, LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH); delayMicroseconds(10);
digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2;
}

void feedback(int d) {
Serial.print("Distance: "); Serial.println(d);
digitalWrite(redLED, LOW); digitalWrite(blueLED, LOW); digitalWrite(yellowLED, LOW);
noTone(buzzerPin);
if (d <= 15) {
digitalWrite(redLED, HIGH);
for (int freq = 1000; freq < 3000; freq += 200) { tone(buzzerPin, freq); delay(2); }
for (int freq = 3000; freq > 1000; freq -= 200) { tone(buzzerPin, freq); delay(2); }
digitalWrite(redLED, LOW); delay(50);
} else if (d > 15 && d <= 30) {
digitalWrite(blueLED, HIGH); tone(buzzerPin, 1500); delay(50); noTone(buzzerPin); delay(50);
} else {
digitalWrite(yellowLED, HIGH);
}
}

You might also like