#include <AFMotor.h>
#include <Servo.h>
#define TRIGGER_PIN 2 // Ultrasonic sensor trigger pin
#define ECHO_PIN 3 // Ultrasonic sensor echo pin
AF_DCMotor motor1(1); // Motor 1 initialization
AF_DCMotor motor2(2); // Motor 2 initialization
AF_DCMotor motor3(3); // Motor 3 initialization
AF_DCMotor motor4(4); // Motor 4 initialization
Servo servoMotor; // Servo motor initialization
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize ultrasonic sensor pins
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Set motor speed
motor1.setSpeed(200);
motor2.setSpeed(200);
motor3.setSpeed(200);
motor4.setSpeed(200);
// Attach servo motor to pin 9
servoMotor.attach(9);
}
void loop() {
// Read ultrasonic sensor distance
long duration, distance;
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration / 2) / 29.1;
// Print ultrasonic sensor distance
Serial.print("Distance: ");
Serial.println(distance);
// Check if an obstacle is detected within 20 cm
if (distance < 20) {
// Obstacle detected, stop and turn
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
delay(500);
// Rotate servo motor to 90 degrees
servoMotor.write(90);
delay(1000);
// Move backward for 1 second
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(BACKWARD);
motor4.run(BACKWARD);
delay(1000);
// Rotate servo motor to -90 degrees
servoMotor.write(-90);
delay(1000);
// Rotate servo motor to 90 degrees
servoMotor.write(90);
delay(1000);
} else {
// No obstacle detected, move forward
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
}
}
Have you got a question ?
Motor shield is in use... Defines these pins...
// Arduino pin names for interface to 74HCT595 latch
#define MOTORLATCH 12
#define MOTORCLK 4
#define MOTORENABLE 7
#define MOTORDATA 8
[quote="arduinouser20007, post:1, topic:1222531"]
AF_DCMotor motor1(1); // Motor 1 initialization
AF_DCMotor motor2(2); // Motor 2 initialization
AF_DCMotor motor3(3); // Motor 3 initialization
AF_DCMotor motor4(4); // Motor 4 initialization
[/quote]
ChatGPT does not know you are using Uno/Nano.
O didn't understand ![]()
Okay the thing is that i am still a beginner in this field ![]()
So thanks for letting me know that ![]()
Thanks please is there any adjustment that is still needed for the code
The AF motor shield is using pins 12, 4, 7, and 8... you should have received instructions and possibly example sketches with your motor shield... maybe on paper, maybe online.
Oh I forgot to tell you i am using an adafruit motor driver shield so that is why the motor pins were defined that way. If it was a "shift register" you were right defining the pin connections as you did
Do you have a question?
Not really
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.