why not start with just trying to read the distance sensor and printing the value on the Serial monitor?
then add some code the prints something (e.g. "stop") when the distance is close?
then add code to run the motor if not close and stop the motor if close?
looks like you're trying to turn the robot by running each motor in opposite directions, but i don't see any code to stop turning or even stop both motors
I added mor pin definitions and now I'm getting exit status 1
expected constructor, destructor, or type conversion before 'int' on the const int trigPin = 9;
// defines pins numbers
setup()
const int trigPin = 9;
const int echoPin = 10;
const int(motor1pin2)
const int(motor1pin1)
const int(motor2pin1)
const int(motor2pin2)
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
safetyDistance = distance;
if (safetyDistance <= 5){
digitalWrite(motor1pin2, LOW);
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor2pin1, LOW);
digitalWrite(motor2pin2, HIGH);
delay(1000);
digitalWrite(motor1pin1, LOW);
digitalWrite(motor1pin2, HIGH);
digitalWrite(motor2pin2, LOW);
digitalWrite(motor2pin1, HIGH);
}
else{
digitalWrite(motor1pin2, HIGH);
digitalWrite(motor1pin1, LOW);
digitalWrite(motor2pin2, LOW);
digitalWrite(motor2pin1, HIGH);
delay(1000);
}
It looks like you have wrtten your code as one big proceedure.
Can I suggest you forget your code for the moment AND write some code that JUST makes the motors run back and forth at 5 second intervals.
You need to get your motor control done first BEFORE adding ultrasonics etc.
A schematic would help as we do not even know ;
What Arduino controller your are using.
What type of motor controller you are using.
What the motor specs are.
What you are using for a power supply.