Hello everyone,
I am trying to write a code that would enable a robotic buggy to move straight from a specific starting point towards a wall, which could be up to 3.5 meters away, then rotate 180 degrees and return to the starting position as swiftly and accurately as possible.
Below is the circuit that I have created in tinkercad:
I have started to write the code which is shown below:
const int trigPin = 13; // Trigger pin of ultrasonic sensor
const int echoPin = 12; // Echo pin of ultrasonic sensor
const int motor1Pin1 = 9; // Motor 1 control pin 1
const int motor1Pin2 = 10; // Motor 1 control pin 2
const int motor2Pin1 = 6; // Motor 2 control pin 1
const int motor2Pin2 = 5; // Motor 2 control pin 2
const int enablePin1 = 11; // Motor 1 enable pin
const int enablePin2 = 3; // Motor 2 enable pin
const int TURN_DURATION = 2600; // quickness of turning (note this is in milliseconds)
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motor1Pin1, OUTPUT);
pinMode(motor1Pin2, OUTPUT);
pinMode(motor2Pin1, OUTPUT);
pinMode(motor2Pin2, OUTPUT);
pinMode(enablePin1, OUTPUT);
pinMode(enablePin2, OUTPUT);
digitalWrite(enablePin1, HIGH); // Enable Motor 1
digitalWrite(enablePin2, HIGH); // Enable Motor 2
}
void driveForward() {
analogWrite(enablePin1, 127);
analogWrite(enablePin2, 127);
digitalWrite(motor1Pin1, HIGH);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, HIGH);
digitalWrite(motor2Pin2, LOW);
}
void stopCar() {
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, LOW);
}
void turnAround() {
analogWrite(enablePin1, 127);
analogWrite(enablePin2, 0);
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, HIGH);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, LOW);
delay(TURN_DURATION);
}
//void recordDistance(){
//digitalWrite(trigPin, LOW);
//delayMicroseconds(2);
//digitalWrite(trigPin, HIGH);
//delayMicroseconds(10);
//digitalWrite(trigPin, LOW);
//pencil = pulseIn(echoPin, HIGH);
//}
void loop() {
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Receive ultrasonic echo
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration/2 * 0.034;
if (distance <= 32.5) { // If the car is very close to the wall (adjust threshold as needed)
// Stop the car
stopCar();
delay(1000);
// Turn 180 degrees
turnAround();
// Drive back to start position
driveForward();
delay(1000); //this is the problem section I believe
stopCar();
return;
}else
// Drive forward
driveForward();
return;
}
Currently, the above code allows the buggy to come within 32.5cm to a wall, turns around 180 degrees without a problem. However, it then drives forward and does not seem to stop. What am I missing.
I have also tried the above code using a switch case but again I cant get it working.
Any help with be greatly appreciated.