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

code with ultrasonic

Uploaded by

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

code with ultrasonic

Uploaded by

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

// Motor pins

const int motor1Pin1 = 9;


const int motor1Pin2 = 11;
const int motor2Pin1 = 12;
const int motor2Pin2 = 13;

// Ultrasonic sensor pins


const int trigPin = 5;
const int echoPin = 6;

// Distance threshold for detection (in cm)


const int detectionThreshold = 30;

void setup() {
// Set motor pins as outputs
pinMode(motor1Pin1, OUTPUT);
pinMode(motor1Pin2, OUTPUT);
pinMode(motor2Pin1, OUTPUT);
pinMode(motor2Pin2, OUTPUT);

// Set ultrasonic sensor pins


pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

// Start serial communication (optional for debugging)


Serial.begin(9600);
}

void loop() {
// Measure distance
int distance = getDistance();

// Check if distance is within threshold


if (distance > 0 && distance <= detectionThreshold) {
// If oil is detected (object within threshold), run motors forward
moveForward();
} else {
// If no oil detected, stop motors
stopMotors();
}

delay(100); // Small delay for stability


}

// Function to measure distance using ultrasonic sensor


int getDistance() {
// Send a 10us pulse to trigger pin to initiate measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the time it takes for the echo to return


long duration = pulseIn(echoPin, HIGH);

// Calculate distance in cm (speed of sound is 343 m/s)


int distance = duration * 0.034 / 2;
// Print distance for debugging (optional)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

return distance;
}

// Function to move motors forward


void moveForward() {
digitalWrite(motor1Pin1, HIGH);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, HIGH);
digitalWrite(motor2Pin2, LOW);
}

// Function to stop motors


void stopMotors() {
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, LOW);
}

You might also like