// Pins for motor control
#define LEFT_MOTOR_PWM 3 // PWM pin for left motor speed control
#define LEFT_MOTOR_DIR 4 // Direction pin for left motor
#define RIGHT_MOTOR_PWM 5 // PWM pin for right motor speed control
#define RIGHT_MOTOR_DIR 6 // Direction pin for right motor
// Pins for IR sensors
#define LEFT_SENSOR A0
#define RIGHT_SENSOR A1
// Threshold for sensor reading
#define SENSOR_THRESHOLD 600 // Adjust this value based on your setup
void setup() {
// Motor pins setup
pinMode(LEFT_MOTOR_PWM, OUTPUT);
pinMode(LEFT_MOTOR_DIR, OUTPUT);
pinMode(RIGHT_MOTOR_PWM, OUTPUT);
pinMode(RIGHT_MOTOR_DIR, OUTPUT);
// IR sensor pins setup
pinMode(LEFT_SENSOR, INPUT);
pinMode(RIGHT_SENSOR, INPUT);
}
void loop() {
int leftSensorValue = analogRead(LEFT_SENSOR);
int rightSensorValue = analogRead(RIGHT_SENSOR);
// Adjust motor speeds based on sensor readings
if (leftSensorValue < SENSOR_THRESHOLD && rightSensorValue < SENSOR_THRESHOLD) {
// Move forward at full speed
moveForward(255, 255);
} else if (leftSensorValue < SENSOR_THRESHOLD) {
// Turn right
moveForward(255, 150);
} else if (rightSensorValue < SENSOR_THRESHOLD) {
// Turn left
moveForward(150, 255);
} else {
// Stop
stopMotors();
}
}
// Function to move the car forward with variable speeds for each motor
void moveForward(int leftSpeed, int rightSpeed) {
analogWrite(LEFT_MOTOR_PWM, leftSpeed);
analogWrite(RIGHT_MOTOR_PWM, rightSpeed);
digitalWrite(LEFT_MOTOR_DIR, HIGH);
digitalWrite(RIGHT_MOTOR_DIR, HIGH);
}
// Function to stop the car
void stopMotors() {
analogWrite(LEFT_MOTOR_PWM, 0);
analogWrite(RIGHT_MOTOR_PWM, 0);
}