8.Ultrasonic with servo
Ultrasonic with servo
Materials Needed:
- Arduino board
- Ultrasonic sensor (e.g., HC-SR04)
- Servo motor
- Jumper wires
- Breadboard (optional)
Connections:
Ultrasonic Sensor to Arduino:
- TRIG pin → Pin 9
- ECHO pin → Pin 10
- VCC pin → 5V
- GND pin → GND
Servo Motor to Arduino:
- Signal pin → Pin 11
- VCC → 5V
- GND → GND
Procedure:
Connect the Components:
- Use jumper wires to connect the ultrasonic sensor and the servo motor as described above.
Write the Arduino Code:
- Copy and paste the following code into the Arduino IDE:
C++ Code
#include <Servo.h>
const int trigPin = 9;
const int echoPin = 10;
const int servoPin = 11;
int thresholdDistance = 20; // Set the distance threshold in centimeters
Servo myServo;
void setup() {
Serial.begin(9600); // Start the serial communication at 9600 baud rate
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.attach(servoPin);
myServo.write(0); // Set servo to initial position (0 degrees)
}
void loop() {
long duration;
int distance;
// Send a 10us pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Move the servo if the object is closer than the threshold distance
if (distance <= thresholdDistance) {
myServo.write(90); // Move servo to 90 degrees
} else {
myServo.write(0); // Move servo back to 0 degrees
}
delay(500); // Wait for a short while before the next measurement
}
Upload the Code:
- Connect your Arduino to the computer and upload the code using the Arduino IDE.
Open the Serial Monitor:
- Open the Serial Monitor to see the distance readings. Ensure the baud rate is set to 9600.
Observe Servo Motor Behavior:
- The servo will move to 90 degrees when an object is closer than 20 cm (you can adjust the
thresholdDistance
value to change the threshold). - When the object is farther away, the servo will move back to 0 degrees.
Explanation:
- The TRIG pin sends a pulse to start measuring distance.
- The ECHO pin receives the reflected pulse, and the duration is used to calculate the distance in centimeters.
- If the distance is below the thresholdDistance (20 cm by default), the servo motor moves to 90 degrees.
- If the distance is greater than the threshold, the servo returns to 0 degrees.
Comments
Post a Comment