Skip to content

Instantly share code, notes, and snippets.

@GreenMoonArt
Last active August 4, 2016 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GreenMoonArt/f21b1588dfbb469a25ec15bad249fa6f to your computer and use it in GitHub Desktop.
Save GreenMoonArt/f21b1588dfbb469a25ec15bad249fa6f to your computer and use it in GitHub Desktop.
// download library from: https://github.com/pololu/qtr-sensors-arduino
#include <QTRSensors.h>
#define NUM_SENSORS 6 // number of sensors used
#define TIMEOUT 2500
#define EMITTER_PIN QTR_NO_EMITTER_PIN // digital pin 2 is often used, but not necessary
// sensor connected through analog pins A0 - A5 i.e. digital pins 14-19
// note: the next two lines are really one line of code – it may be word-wrapped in your browser
QTRSensorsRC qtrrc((unsigned char[]) {14, 15, 16, 17, 18, 19}, NUM_SENSORS, TIMEOUT, EMITTER_PIN);
unsigned int sensorValues[NUM_SENSORS]; // square brackets indicate an array
void setup()
{
Serial.begin(9600);
delay(500);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH); // turn on Arduino's LED to indicate we are in calibration mode
for (int i = 0; i < 400; i++) // make the calibration take about 10 seconds
{
qtrrc.calibrate(); // reads all sensors 10 times at 2500 us per read (i.e. ~25 ms per call)
delay(20);
}
digitalWrite(13, LOW); // turn off Arduino's LED to indicate we are through with calibration
delay(2000); //allow time to position the robot
}
void loop()
{
unsigned int sensors[NUM_SENSORS];
int position = qtrrc.readLine(sensors);
int error = position - 2500; // you may need to adjust this factor
int errorMargin = 100; // you may need to adjust this factor
Serial.print("Error: ");
Serial.println(error);
if(error > errorMargin)
{
//code for turning to the left
Serial.println("Turn Left");
}
else if(error < -errorMargin)
{
//code for turning to the right
Serial.println("Turn Right");
}
else
{
//code to go straight
Serial.println("Go Straight");
}
delay(200);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment