// Pin definitions
const int leftSensorPin = 2;
const int rightSensorPin = 3;
const int leftMotorPin1 = 4;
const int leftMotorPin2 = 5;
const int rightMotorPin1 = 6;
const int rightMotorPin2 = 7;
// Constants
const int threshold = 500; // Adjust this threshold according to sensor readings
const int speed = 150; // Adjust motor speed as needed
void setup() {
// Configure motor pins as output
pinMode(leftMotorPin1, OUTPUT);
pinMode(leftMotorPin2, OUTPUT);
pinMode(rightMotorPin1, OUTPUT);
pinMode(rightMotorPin2, OUTPUT);
// Configure sensor pins as input
pinMode(leftSensorPin, INPUT);
pinMode(rightSensorPin, INPUT);
}
void loop() {
int leftSensorValue = analogRead(leftSensorPin);
int rightSensorValue = analogRead(rightSensorPin);
// Adjust motor speeds based on sensor readings
if (leftSensorValue < threshold && rightSensorValue < threshold) {
// Both sensors see the line, move forward
move forward();
} else if (leftSensorValue > threshold && rightSensorValue < threshold) {
// Only the right sensor sees the line, turn left
turnLeft();
} else if (leftSensorValue < threshold && rightSensorValue > threshold) {
// Only the left sensor sees the line, turn right
turnRight();
} else {
// Both sensors are off the line, stop
stop motors();
}
}
// Helper functions for motor control
void move forward() {
digitalWrite(leftMotorPin1, HIGH);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, HIGH);
digitalWrite(rightMotorPin2, LOW);
// Set motor speeds
analogWrite(leftMotorPin1, speed);
analogWrite(rightMotorPin1, speed);
}
void turnLeft() {
digitalWrite(leftMotorPin1, LOW);
digitalWrite(leftMotorPin2, HIGH);
digitalWrite(rightMotorPin1, HIGH);
digitalWrite(rightMotorPin2, LOW);
// Set motor speeds
analogWrite(leftMotorPin2, speed);
analogWrite(rightMotorPin1, speed);
}
void turnRight() {
digitalWrite(leftMotorPin1, HIGH);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, HIGH);
// Set motor speeds
analogWrite(leftMotorPin1, speed);
analogWrite(rightMotorPin2, speed);
}
void stopMotors() {
// Stop both motors
digitalWrite(leftMotorPin1, LOW);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, LOW);
}
Upload this code to your Arduino board, ensuring that the connections are correctly made. The robot will follow a black line on a light-colored surface. Adjust the threshold value to fit your specific setup, as it determines the sensitivity to the line.
This is a basic implementation, and you can further enhance the line follower robot with additional features and improvements based on your requirements and creativity.
It will take just few seconds to claim 7% Discount, After Submitting check Email for Coupon code.
Leave a Reply
You must be logged in to post a comment.