Step 4: The Code
If you want to test out the circuit, upload the following sketch to your Arduino.
/* Line Following RobotOnce you've uploaded the sketch to your Arduino open up the serial monitor and you should notice a series of values been printed in the window e.g. “Left = 21 – Minor Correction”.
Demonstrates the use of IR LED's for a simple line
following robot, if it leaves the black line it will
attempt to locate it.
The circuit:
* Follow the instructable on how to construct it.
created 2011
by Dominion-Network
This example code is in the public domain.
*/
// Motor Outputs
// Left Motor
int M1B = 11; // Reverse
int M1F = 10; // Forward
// Right Motor
int M2B = 6; // Reverse
int M2F = 5; // Forward
// Motor Speed
int mSpeed = 115;
// 2 IR Sensor Analog Input Pins
int LIRPin = A0; // Left Sensor
int RIRPin = A1; // Right Sensor
// 2 IR Analog Reading variables
int LIRReading; // Left Reading
int RIRReading; // Right Reading
void setup(void) {
Serial.begin(9600); // For debugging purposes
pinMode(M1F, OUTPUT); // Motor 1 Forward
pinMode(M1B, OUTPUT); // Motor 1 Reverse
pinMode(M2F, OUTPUT); // Motor 2 Forward
pinMode(M2B, OUTPUT); // Motor 2 Reverse
}
void loop(void) {
leftirscan();
rightirscan();
delay(1000);
}
void rightirscan() {
RIRReading = analogRead(RIRPin);
Serial.print("Right = ");
Serial.print(RIRReading);
// We'll have a few threshholds, qualitatively determined
if (RIRReading < 20) {
Serial.println(" - No Correction");
analogWrite(M2F, 0);
} else if (RIRReading < 200) {
Serial.println(" - Minor Correction");
analogWrite(M2F, mSpeed + 10);
} else if (RIRReading < 500) {
Serial.println(" - Moderate Correction");
analogWrite(M2F, mSpeed + 50);
} else if (RIRReading < 800) {
Serial.println(" - Severe Correction");
analogWrite(M2F, mSpeed + 100);
} else {
Serial.println(" - Extreme Correction");
analogWrite(M2F, 255);
}
}
void leftirscan() {
LIRReading = analogRead(LIRPin);
Serial.print("Left = ");
Serial.print(LIRReading);
// We'll have a few threshholds, qualitatively determined
if (LIRReading < 20) {
Serial.println(" - No Correction");
analogWrite(M1F, 0);
} else if (LIRReading < 200) {
Serial.println(" - Minor Correction");
analogWrite(M1F, mSpeed + 10);
} else if (LIRReading < 500) {
Serial.println(" - Moderate Correction");
analogWrite(M1F, mSpeed + 50);
} else if (LIRReading < 800) {
Serial.println(" - Severe Correction");
analogWrite(M1F, mSpeed + 100);
} else {
Serial.println(" - Extreme Correction");
analogWrite(M1F, 255);
}
}
That means the left sensor is getting more light reflected into the photo transistor and will correct it's course to reduce the light been reflected by turning either left or right until the value has been decreased below the threshold.
Here's a simple concept demo.
Remove these ads by
Signing Up


























Not Nice
















Visit Our Store »
Go Pro Today »



