5.6 Code examples
Line tracking Arduino code
// Line Tracking with IR Sensor
// Define sensor pins
const int leftSensorPin = 2;
const int rightSensorPin = 3;
// Define motor pins
const int leftMotorPin = 4;
const int rightMotorPin = 5;
void setup() {
// Set sensor pins as inputs
pinMode(leftSensorPin, INPUT);
pinMode(rightSensorPin, INPUT);
// Set motor pins as outputs
pinMode(leftMotorPin, OUTPUT);
pinMode(rightMotorPin, OUTPUT);
}
void loop() {
// Read sensor values
int leftSensorValue = digitalRead(leftSensorPin);
int rightSensorValue = digitalRead(rightSensorPin);
// Line tracking logic
if (leftSensorValue == LOW && rightSensorValue == LOW) {
// Both sensors on the line
// Move forward
digitalWrite(leftMotorPin, HIGH);
digitalWrite(rightMotorPin, HIGH);
} else if (leftSensorValue == LOW && rightSensorValue == HIGH) {
// Left sensor off the line, right sensor on the line
// Turn left
digitalWrite(leftMotorPin, LOW);
digitalWrite(rightMotorPin, HIGH);
} else if (leftSensorValue == HIGH && rightSensorValue == LOW) {
// Left sensor on the line, right sensor off the line
// Turn right
digitalWrite(leftMotorPin, HIGH);
digitalWrite(rightMotorPin, LOW);
} else {
// Both sensors off the line or error condition
// Stop
digitalWrite(leftMotorPin, LOW);
digitalWrite(rightMotorPin, LOW);
}
}