[go: up one dir, main page]

0% found this document useful (0 votes)
20 views2 pages

#Include Servo.h

This code controls an ultrasonic sensor, servo motor, and two DC motors to allow a robot car to detect obstacles and turn to avoid them or move forward if clear.

Uploaded by

xevav11987
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

#Include Servo.h

This code controls an ultrasonic sensor, servo motor, and two DC motors to allow a robot car to detect obstacles and turn to avoid them or move forward if clear.

Uploaded by

xevav11987
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

new code

#include <Servo.h>
#include <NewPing.h>
#include <AFMotor.h>

#define TRIG_PIN A0 // Ultrasonic sensor trigger pin


#define ECHO_PIN A1 // Ultrasonic sensor echo pin
#define SERVO_PIN 4 // Servo motor control pin

#define MOTOR1_PIN1 5 // Motor 1 input 1 pin


#define MOTOR1_PIN2 6 // Motor 1 input 2 pin
#define MOTOR2_PIN1 7 // Motor 2 input 1 pin
#define MOTOR2_PIN2 8 // Motor 2 input 2 pin
#define MOTOR_DIR_PIN 9 // Motor direction pin

#define MAX_DISTANCE 20 // Maximum distance for obstacle detection (in cm)


#define TURN_DELAY 1000 // Delay for turning (in milliseconds)

Servo servoMotor;

void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(MOTOR1_PIN1, OUTPUT);
pinMode(MOTOR1_PIN2, OUTPUT);
pinMode(MOTOR2_PIN1, OUTPUT);
pinMode(MOTOR2_PIN2, OUTPUT);
pinMode(MOTOR_DIR_PIN, OUTPUT);

servoMotor.attach(SERVO_PIN);
servoMotor.write(90); // Set servo motor to the center position
delay(1000);
}

void loop() {
long duration, distance;

// Ultrasonic sensor measurement


digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration / 2) / 29.1;

if (distance <= MAX_DISTANCE) {


// Obstacle detected, turn the car
digitalWrite(MOTOR_DIR_PIN, HIGH); // Set motor direction pin
servoMotor.write(0); // Turn the servo motor to the left
delay(TURN_DELAY);

// Stop turning and go forward


digitalWrite(MOTOR1_PIN1, HIGH);
digitalWrite(MOTOR1_PIN2, LOW);
digitalWrite(MOTOR2_PIN1, HIGH);
digitalWrite(MOTOR2_PIN2, LOW);
servoMotor.write(90); // Set the servo motor back to the center position
} else {
// No obstacle detected, move forward
digitalWrite(MOTOR_DIR_PIN, LOW); // Set motor direction pin
digitalWrite(MOTOR1_PIN1, HIGH);
digitalWrite(MOTOR1_PIN2, LOW);
digitalWrite(MOTOR2_PIN1, HIGH);
digitalWrite(MOTOR2_PIN2, LOW);
}
}

You might also like