Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
2.2 kB
1
Indexable
Never
// Define pin numbers
const int trigPin = 7;          // Ultrasonic sensor Trig pin connected to digital pin 7
const int echoPin = 6;          // Ultrasonic sensor Echo pin connected to digital pin 6

// Motor pins (adjust these according to your setup)
const int in1 = 8;  // IN1 pin connected to digital pin 8
const int in2 = 9;  // IN2 pin connected to digital pin 9
const int in3 = 12; // IN3 pin connected to digital pin 10
const int in4 = 13; // IN4 pin connected to digital pin 11

void setup() {
  Serial.begin(9600);           // Initialize serial communication for debugging
  pinMode(trigPin, OUTPUT);     // Ultrasonic sensor trig pin as output
  pinMode(echoPin, INPUT);      // Ultrasonic sensor echo pin as input

  pinMode(in1, OUTPUT);  // Motor pins as output
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;  // Convert the time into distance (cm)

  // Print Ultrasonic sensor distance to serial monitor
  Serial.print("Ultrasonic Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  if (distance > 10 && distance < 50) {
    moveForward();
  } else if (distance <= 10) {
    turnRight(); // You can change this to turnLeft() for a left turn
    delay(1000); // Adjust the delay based on your robot's speed and turning radius
  } else {
    stopRobot();
  }
}

void moveForward() {
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
}

void turnLeft() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
}

void turnRight() {
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
}

void stopRobot() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
Leave a Comment