Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Create a code in C for arduino uno. The arduino will be a car with 4 wheels and an…

  1. User

    Create a code in C for arduino uno. The arduino will be a car with 4 wheels and an ultrasonic sensor. Make it lateral park

  2. Assistant

    Certainly! Below is a sample Arduino code written in C that will control a car with four wheels and an ultrasonic sensor to perform a lateral (parallel) parking maneuver. This code assumes that the car has two DC motors for movement (left and right wheels) controlled via a motor driver (like the L298N), and one ultrasonic sensor (like the HC-SR04) mounted on a servo to sweep and detect distances on the sides.

    Important Note: This code is a basic framework and may need adjustments based on your specific hardware setup (motor connections, sensor positions, etc.). Please make sure to wire your components correctly and safely.

    // Define motor control pins
    #define ENA 9    // Enable/speed motors Right
    #define ENB 10   // Enable/speed motors Left
    #define IN1 7    // Motor Right forward
    #define IN2 6    // Motor Right reverse
    #define IN3 5    // Motor Left forward
    #define IN4 4    // Motor Left reverse
    
    // Ultrasonic sensor pins
    #define TRIG_PIN 12
    #define ECHO_PIN 11
    
    // Servo motor pin (for ultrasonic sensor rotation)
    #include <Servo.h>
    Servo servo;
    #define SERVO_PIN 3
    
    // Variables
    long duration;
    int distance;
    int servoAngle = 90; // Start at 90 degrees
    
    void setup() {
      // Initialize serial communication
      Serial.begin(9600);
    
      // Initialize motor control pins
      pinMode(ENA, OUTPUT);
      pinMode(ENB, OUTPUT);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(IN3, OUTPUT);
      pinMode(IN4, OUTPUT);
    
      // Initialize ultrasonic sensor pins
      pinMode(TRIG_PIN, OUTPUT);
      pinMode(ECHO_PIN, INPUT);
    
      // Attach servo
      servo.attach(SERVO_PIN);
      servo.write(servoAngle); // Face forward
    }
    
    void loop() {
      // Step 1: Move forward looking for a parking space
      moveForward();
      int spaceSize = detectParkingSpace();
    
      if (spaceSize > 30) { // Assume 30 cm is enough for parking
        // Step 2: Stop and prepare to park
        stopMoving();
        delay(1000);
    
        // Step 3: Move forward a bit to align car
        moveForward();
        delay(1000); // Adjust as needed
        stopMoving();
        delay(500);
    
        // Step 4: Begin parallel parking maneuver
        parallelPark();
        // Parking complete
        while (true) {
          stopMoving();
        }
      }
    }
    
    // Function to move forward
    void moveForward() {
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);
      analogWrite(ENA, 200); // Speed can be adjusted
      analogWrite(ENB, 200);
    }
    
    // Function to move backward
    void moveBackward() {
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, HIGH);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      analogWrite(ENA, 200);
      analogWrite(ENB, 200);
    }
    
    // Function to turn right while moving backward
    void reverseRight() {
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, HIGH);
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);
      analogWrite(ENA, 200);
      analogWrite(ENB, 200);
    }
    
    // Function to turn left while moving backward
    void reverseLeft() {
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      analogWrite(ENA, 200);
      analogWrite(ENB, 200);
    }
    
    // Function to stop movement
    void stopMoving() {
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, LOW);
    }
    
    // Function to detect a parking space
    int detectParkingSpace() {
      int space = 0;
      // Rotate servo to the right to check for space
      servo.write(120); // Adjust angle as per your setup
      delay(500);
      int distance1 = getDistance();
    
      // Rotate servo to the left to check for space depth
      servo.write(60); // Adjust angle as per your setup
      delay(500);
      int distance2 = getDistance();
    
      // Calculate space size
      space = distance1 + distance2;
    
      // Reset servo to forward position
      servo.write(90);
    
      // Return the detected space size
      return space;
    }
    
    // Function to perform parallel parking maneuver
    void parallelPark() {
      // Step 1: Reverse while turning right
      reverseRight();
      delay(2000); // Adjust timing as needed based on testing
      // Step 2: Reverse while turning left to straighten
      reverseLeft();
      delay(2000); // Adjust timing as needed
      // Step 3: Stop the car
      stopMoving();
    }
    
    // Function to get distance from ultrasonic sensor
    int getDistance() {
      // Clear the trigger
      digitalWrite(TRIG_PIN, LOW);
      delayMicroseconds(2);
    
      // Send a 10us pulse to trigger
      digitalWrite(TRIG_PIN, HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIG_PIN, LOW);
    
      // Read the echo pin
      duration = pulseIn(ECHO_PIN, HIGH);
    
      // Calculate distance in cm
      distance = duration * 0.034 / 2;
    
      // Return the distance
      return distance;
    }
    

    Explanation of the Code:

    • Motor Control Pins: Set up the motor driver pins connected to the Arduino. Adjust these based on how your motors are wired.
    • Ultrasonic Sensor Pins: Define the trig and echo pins connected to the ultrasonic sensor.
    • Servo Motor Setup: Attach the servo motor used to rotate the ultrasonic sensor to scan for parking space.
    • Movement Functions: Functions like moveForward(), moveBackward(), reverseRight(), and reverseLeft() control the car's movement by setting the motor driver pins accordingly.
    • Parking Detection: The detectParkingSpace() function rotates the ultrasonic sensor to measure distances on the sides to detect a possible parking space.
    • Parallel Parking Maneuver: The parallelPark() function controls the sequence of movements required to park the car. Timing delays (delay()) need to be adjusted based on actual testing and the car's speed.

    Safety and Adjustments:

    • Adjust Timing: The delay() durations in the parking maneuver steps are placeholders. You'll need to adjust them according to your car's speed and response.
    • Sensor Angles: Modify the servo angles in detectParkingSpace() to match how your sensor is mounted.
    • Motor Speeds: You can adjust the speed of the motors by changing the values in analogWrite(ENA, speed) and analogWrite(ENB, speed).
    • Testing: Before running the full program, test each function individually to ensure motors and sensors are working as expected.

    Additional Tips:

    • Power Supply: Ensure that your power supply can handle the current drawn by the motors and the servo.
    • Obstacle Detection: Consider adding conditions to stop the car if an obstacle is detected during movement for safety.
    • Debugging: Use Serial.println() statements to print out distance measurements and other variables for debugging purposes.

    Disclaimer: This is a simplified example to illustrate how you might program an Arduino to perform a lateral parking maneuver with basic components. Real-world implementation may require more sophisticated sensors and control algorithms to handle dynamics accurately.


    Feel free to ask if you need further customization or explanation of any part of the code!