2 Linefollowing code by Gabriel Fornaeus
4 More information at http://hax0r.se
7 // For the Pololu Qik motor controller
8 #include <CompactQik2s9v1.h>
9 #include <NewSoftSerial.h>
10 // Setup pins for the motor controller
15 NewSoftSerial mySerial = NewSoftSerial(rxPin,txPin);
16 CompactQik2s9v1 motor = CompactQik2s9v1(&mySerial,rstPin);
19 #include <PololuQTRSensors.h>
20 #define NUM_SENSORS 3 // Number of sensors used(actually five, but we'll skip the outer two)
21 #define TIMEOUT 2500 // Waits for 2500 us for sensor outputs to go low
23 // Sensors 0 through 5 are connected to digital pins 4 through 6, respectively
24 PololuQTRSensorsRC qtrrc((unsigned char[]) { 8, 9, 10, },
25 NUM_SENSORS, TIMEOUT);
26 unsigned int sensorValues[NUM_SENSORS];
28 // Variables for PD control
30 // Proportional constant
32 // Derivative constant
58 motor.stopBothMotors();
60 digitalWrite(13, HIGH);
64 for (i = 0; i < 80; i++)
66 if (i < 20 || i >= 60)
68 motor.motor0Forward(70);
69 motor.motor1Reverse(75);
73 motor.motor0Reverse(70);
74 motor.motor1Forward(75);
76 qtrrc.calibrate(); // Reads all sensors 10 times at 2500 us per read (i.e. ~25 ms per call)
78 // Stop when the calibration is done
79 motor.stopBothMotors();
80 // End of calibration period
81 digitalWrite(13, LOW);
83 motor.stopBothMotors();
89 // Get the position of the line
90 int position = qtrrc.readLine(sensorValues,QTR_EMITTERS_ON);
92 /* Compute the "error" from the line position.
93 Error will be 0 when we're dead center over the line, -1000 when we're to the left and 1000
94 if it's to the right */
95 int error = position - 1000;
97 // Set motor speed based on proportional and derivative PD terms
98 int motorSpeed = KP * error + KD * (error - lastError);
101 int m0Speed = constrain((M0 + motorSpeed),0,127);
102 int m1Speed = constrain((M1 - motorSpeed),0,127);
104 motor.motor0Forward(m0Speed);
105 analogWrite(11, m0Speed);
106 motor.motor1Forward(m1Speed);
107 analogWrite(12, m1Speed);