You are on page 1of 1

const int trigPin = 9; // Trig pin of ultrasonic sensor connected to digital pin 9

const int echoPin = 10; // Echo pin of ultrasonic sensor connected to digital pin
10
const int motorPin = 5; // Pin for motor control

void setup() {
pinMode(trigPin, OUTPUT); // Set trigPin as output
pinMode(echoPin, INPUT); // Set echoPin as input
pinMode(motorPin, OUTPUT); // Set motorPin as output
Serial.begin(9600); // Initialize serial communication
}

void loop() {
long duration, distance;
digitalWrite(trigPin, LOW); // Set trigPin low for 2 microseconds
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Set trigPin high for 10 microseconds
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Measure the duration of the echo signal
distance = duration * 0.034 / 2; // Calculate distance in cm
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

if (distance < 20) { // If distance is less than 20cm, stop the motor
digitalWrite(motorPin, LOW);
} else { // Otherwise, start the motor
digitalWrite(motorPin, HIGH);
}
delay(100); // Delay for 100 milliseconds before taking another measurement
}

You might also like