I need to make a line follower that stops when it detects an obstacle with an IR

Posted this on Reddit, but was completely ignored.

Hi guys, I've been struggling the past few weeks with my school projects. Especially with line followers. The project I'm currently working on is a line follower with a Sharp 2Y0A21 IR sensor. The purpose of the project is to well, make a car that follows a black line and stops when it 'sees' an obstacle in front.

The first problem is that it doesn't actually follows the black line, it just turns around in the same place, to the same side (sometimes left, sometimes right).

The other is that the IR sensor seems to do nothing and now I doubt that it is properly connected.

To be honest, I have little to no idea about what I'm doing. For all projects our teacher just gives us the code and some instructions on how to assemble the circuits but lately they've been a bit, um, deficient.

Anyways, I made this crappy wiring diagram and I will include the code too to try to make easier to identify any flaws.

Code:

#include "AFMotor.h"

#define SensorOne 10

#define SensorTwo 9

AF_DCMotor MotorOne(3);

AF_DCMotor MotorTwo(1);

byte LsensorO;

byte LsensorT;

int ir_sensor = A0;

float read;

int cm;

void setup() {

Serial.begin(9600);

pinMode(SensorOne, INPUT);

pinMode(SensorTwo, INPUT);

}

void loop() {

LsensorO = digitalRead(SensorOne);

LsensorT = digitalRead(SensorTwo);

read=analogRead(ir_sensor);

cm=pow(3927.4/read,1.2134);

Serial.println(cm);

delay(2000);

if(cm>=7 && cm<=12){

Stop();

}

else{

if (LsensorO == 0 && LsensorT == 0) {

Advance();

}

if (LsensorO == 1 && LsensorT == 0) {

Right();

}

if (LsensorO == 0 && LsensorT == 1) {

Left();

}

}

}

void Stop() {

MotorOne.setSpeed(BRAKE);

MotorTwo.setSpeed(BRAKE);

MotorOne.run
(RELEASE);

MotorTwo.run
(RELEASE);

}

void Advance() {

MotorOne.setSpeed(200);

MotorTwo.setSpeed(200);

MotorOne.run
(FORWARD);

MotorTwo.run
(FORWARD);

}

void Left() {

MotorOne.setSpeed(100);

MotorTwo.setSpeed(100);

MotorOne.run
(BACKWARD);

MotorTwo.run
(FORWARD);

}

void Right() {

MotorOne.setSpeed(100);

MotorTwo.setSpeed(100);

MotorOne.run
(FORWARD);

MotorTwo.run
(BACKWARD);

}

Start here

Then scrap that code and write some simple testbed to check the sensors read what you want them to read.

Agreed, to above - are you able to link the sensor your using?

Also test you sensors first individually with a serial print to see if they're reading anything accurately.
Check out this project for some ideas: https://create.arduino.cc/projecthub/Raushancpr/arduino-with-ir-sensor-1579b6

Hi,
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".
OR
http://forum.arduino.cc/index.php/topic,148850.0.html.
Then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Thanks.. Tom.... :slight_smile: