You are on page 1of 2

// Pin definitions

const int LEFT_MOTOR_PIN = 5;


const int RIGHT_MOTOR_PIN = 6;
const int SENSOR_1_PIN = A0;
const int SENSOR_2_PIN = A1;
const int SENSOR_3_PIN = A2;
const int SENSOR_4_PIN = A3;
const int SENSOR_5_PIN = A4;
const int SENSOR_6_PIN = A5;
const int SENSOR_7_PIN = A6;
const int SENSOR_8_PIN = A7;

// Threshold value for sensor readings


const int THRESHOLD = 500;

void setup() {
  // Initialize motor pins
  pinMode(LEFT_MOTOR_PIN, OUTPUT);
  pinMode(RIGHT_MOTOR_PIN, OUTPUT);

  // Initialize sensor pins


  pinMode(SENSOR_1_PIN, INPUT);
  pinMode(SENSOR_2_PIN, INPUT);
  pinMode(SENSOR_3_PIN, INPUT);
  pinMode(SENSOR_4_PIN, INPUT);
  pinMode(SENSOR_5_PIN, INPUT);
  pinMode(SENSOR_6_PIN, INPUT);
  pinMode(SENSOR_7_PIN, INPUT);
  pinMode(SENSOR_8_PIN, INPUT);
}

void loop() {
  // Read sensor values
  int sensor1 = analogRead(SENSOR_1_PIN);
  int sensor2 = analogRead(SENSOR_2_PIN);
  int sensor3 = analogRead(SENSOR_3_PIN);
  int sensor4 = analogRead(SENSOR_4_PIN);
  int sensor5 = analogRead(SENSOR_5_PIN);
  int sensor6 = analogRead(SENSOR_6_PIN);
  int sensor7 = analogRead(SENSOR_7_PIN);
  int sensor8 = analogRead(SENSOR_8_PIN);

  // Determine line position


  int linePosition = 0;
  if (sensor1 < THRESHOLD) {
    linePosition = -4;
  }
  else if (sensor2 < THRESHOLD) {
    linePosition = -3;
  }
  else if (sensor3 < THRESHOLD) {
    linePosition = -2;
  }
  else if (sensor4 < THRESHOLD) {
    linePosition = -1;
  }
  else if (sensor5 < THRESHOLD) {
    linePosition = 0;
  }
  else if (sensor6 < THRESHOLD) {
    linePosition = 1;
  }
  else if (sensor7 < THRESHOLD) {
    linePosition = 2;
  }
  else if (sensor8 < THRESHOLD) {
    linePosition = 3;
  }

  // Adjust motor speeds based on line position


  int leftSpeed = 0;
  int rightSpeed = 0;
 
  if (linePosition == -4) {
    leftSpeed = -100;
    rightSpeed = 100;
  }
  else if (linePosition == -3) {
    leftSpeed = -80;
    rightSpeed = 100;
  }
  else if (linePosition == -2) {
    leftSpeed = -60;
    rightSpeed = 100;
  }
  else if (linePosition == -1) {
    leftSpeed = -40;
    rightSpeed = 100;
  }
  else if (linePosition == 0) {
    leftSpeed = 100;
    rightSpeed = 100;
  }
  else if (linePosition == 1) {
    leftSpeed = 100;
    rightSpeed = 80;
  }
}

You might also like