Hello everyone! Welcome to Arduino Geek. Today we will discuss about the Arduino code for line follower robot. So let's get started.
Line follower robot Arduino code -
Here's an example Arduino code for a simple line follower robot. This code assumes that you're using an Arduino Uno or similar board and a line sensor module with five sensors.
Arduino Code -
// define pins for the line sensor module#define LSensor1 A0#define LSensor2 A1#define LSensor3 A2#define LSensor4 A3#define LSensor5 A4// define pins for the motor driver module#define MotorA1 5#define MotorA2 6#define MotorB1 10#define MotorB2 9void setup() {// initialize the line sensor pins as inputspinMode(LSensor1, INPUT);pinMode(LSensor2, INPUT);pinMode(LSensor3, INPUT);pinMode(LSensor4, INPUT);pinMode(LSensor5, INPUT);// initialize the motor driver pins as outputspinMode(MotorA1, OUTPUT);pinMode(MotorA2, OUTPUT);pinMode(MotorB1, OUTPUT);pinMode(MotorB2, OUTPUT);}void loop() {// read the values from the line sensor pinsint sensor1 = analogRead(LSensor1);int sensor2 = analogRead(LSensor2);int sensor3 = analogRead(LSensor3);int sensor4 = analogRead(LSensor4);int sensor5 = analogRead(LSensor5);// determine the error valueint error = (sensor1 * -4) + (sensor2 * -2) + (sensor3 * 0) + (sensor4 * 2) + (sensor5 * 4);// adjust the motors based on the error valueif (error < 0) {// turn leftdigitalWrite(MotorA1, LOW);digitalWrite(MotorA2, HIGH);digitalWrite(MotorB1, HIGH);digitalWrite(MotorB2, LOW);} else if (error > 0) {// turn rightdigitalWrite(MotorA1, HIGH);digitalWrite(MotorA2, LOW);digitalWrite(MotorB1, LOW);digitalWrite(MotorB2, HIGH);} else {// go straightdigitalWrite(MotorA1, HIGH);digitalWrite(MotorA2, LOW);digitalWrite(MotorB1, HIGH);digitalWrite(MotorB2, LOW);}}
Arduino Code Description -
This code reads the values from the line sensor pins and determines the error value, which is the weighted sum of the sensor readings. The motor driver pins are then adjusted based on the error value to keep the robot on the line. The robot will turn left or right if the error value is negative or positive, respectively, and it will go straight if the error value is zero. You may need to adjust the weights for the sensor readings depending on your specific line sensor module and track.