Skip to content

Create Jordan #393

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions Jordan
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#include <Servo.h>

const int trigPin = 9;
const int echoPin = 10;
const int motorLeft = 5;
const int motorRight = 6;
const int servoPin = 3;

const int angleCenter = 90;
const int angleLeft = 150;
const int angleRight = 30;

Servo servo;

void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motorLeft, OUTPUT);
pinMode(motorRight, OUTPUT);
Serial.begin(9600);

servo.attach(servoPin);
servo.write(angleCenter);
}

long getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
return pulseIn(echoPin, HIGH, 20000) * 0.034 / 2; // Timeout added
}

long getAverageDistance() {
long total = 0;
for (int i = 0; i < 5; i++) {
total += getDistance();
delay(10);
}
return total / 5;
}

int scanAngle(int angle) {
servo.write(angle);
delay(300); // انتظار حتى يثبت السرفو
return getAverageDistance();
}

void loop() {
long distance = getAverageDistance();
Serial.print("Center: "); Serial.println(distance);

if (distance == 0 || distance > 300) {
digitalWrite(motorLeft, LOW);
digitalWrite(motorRight, LOW);
return;
}

if (distance < 20) {
// توقف مؤقت وتراجع بسيط
digitalWrite(motorLeft, LOW);
digitalWrite(motorRight, LOW);
delay(200);

// مسح الاتجاهات
int left = scanAngle(angleLeft);
int right = scanAngle(angleRight);
servo.write(angleCenter);
delay(200); // العودة للمنتصف

Serial.print("Left: "); Serial.print(left);
Serial.print(" | Right: "); Serial.println(right);

// اتخاذ القرار
if (left > right) {
// انعطاف لليسار
digitalWrite(motorLeft, LOW);
digitalWrite(motorRight, HIGH);
delay(500);
} else {
// انعطاف لليمين
digitalWrite(motorLeft, HIGH);
digitalWrite(motorRight, LOW);
delay(500);
}
} else {
// السير للأمام
digitalWrite(motorLeft, HIGH);
digitalWrite(motorRight, HIGH);
}

delay(50);
}