/*
Spybot Line Follower written in NQC
Steve Hassenplug

http://www.geocities.com/stevehassenplug/


The Spybot should have the light sensor and the red light 
  pointed towards the line (directly or using the fiber optic cables)

To use:
1) Build Spybot Line follower
2) Download this program to Spybot using BricxCC
  ( http://hometown.aol.com/johnbinder/bricxcc.htm )
3) Place Spybot on line & press run
4) Move Spybot over line & background
5) Press Touch sensor on Spybot to start it running

The red & green LEDs will show the value read from the light sensor.  
The red = 1,2,4 (outside to inside) and the green = 8,16,32 (outside to inside)

This program has 3 ranges.
1) Below min = black = turn right
2) Between min & max = grey = go forward
3) Above max = white = turn left


GreyPercent is the Percent of area defined as between min + max
Increasing this number will speed-up spybot.  However it may not follow the line as well.

*/

#define GreyPercent 10


task main()
{

  int Min;    // low range for moving
  int Max;    // high range for moving
  int tMin;   // min light reading
  int tMax;   // max light reading

  SetSensorMode(SENSOR_2,SENSOR_MODE_PERCENT);
  SetLight(LIGHT_ON);

  tMin = 100;
  tMax = 0;
  
  SetDirection(OUT_A+OUT_B,OUT_REV); // change this based on gearing
//  SetDirection(OUT_A+OUT_B,OUT_FWD);
  
  // calibrate light sensor
  while(SENSOR_1==0) // wait until button is pressed
  {
    SetLED(LED_MODE_ON,SENSOR_2); // show sensor value on display
    if(SENSOR_2tMax) tMax = SENSOR_2;
  }
  
  // set min/max movement values
  Min = (tMax-tMin) * (50 - GreyPercent / 2) / 100 + tMin;
  Max = (tMax - Min + tMin) ;

  while(SENSOR_1==1);  // wait until button is released

  while(true)
  {
    SetLED(LED_MODE_ON,SENSOR_2); // show sensor value on display
     if (SENSOR_2>=Min)
      On(OUT_A);
     else
      Off(OUT_A);
     if (SENSOR_2<=Max)
      On(OUT_B);
     else
      Off(OUT_B);
  }
}