Programing the robot to use the light sensor to avoid light

Jump to: navigation, search
ArduinoArduino Tutorials and Guided ProjectsVEX + Arduino, Mobile Robotics Platform → Programing the robot to use the light sensor to avoid light

Say you wanted your robot to avoid light - perhaps your robot's photosensory is photosensitive, or you want to hunt vampires. We can do this by a small modification of the previous program, and get drastically different results. This is one of the powers of programming - once you have a solid code base, you can easily manipulate it to get a variety of interesting results.

All we need to do is change the code so that shadeDiff is subtracted from the rightServo, and added to the leftServo.

#pragma config(CircuitBoardType, typeCktBoardUNO)
#pragma config(UART_Usage, UART0, uartSystemCommPort, baudRate200000, IOPins, dgtl1, dgtl0)
#pragma config(Sensor, anlg0,  rightLight,     sensorReflection)
#pragma config(Sensor, anlg1,  leftLight,      sensorReflection)
#pragma config(Sensor, dgtl2,  button,         sensorTouch)
#pragma config(Motor,  servo_10,        rightServo,    tmotorServoContinuousRotation, openLoop, reversed, IOPins, dgtl10, None)
#pragma config(Motor,  motor_11,        leftServo,     tmotorServoContinuousRotation, openLoop, IOPins, dgtl11, None)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//
task main()
  int leftValue = 0;
  int rightValue = 0;
  int leftLow = 1000; //Arbitrary high numberso the < comparison will work (we don't want the low value to always be 0!)
  int rightLow = 1000; //Same deal here.
  int leftHigh = 0;
  int rightHigh = 0;
  // Auto-calibration ended by button press. The button will begin the light following.
  while(!SensorValue[button]) {
    leftValue = SensorValue[leftLight];
    rightValue = SensorValue[rightLight];
    //Get low and high values for the left sensor
    if(leftValue > leftHigh) {
      leftHigh = leftValue;
    } else if(leftValue < leftLow) {
      leftLow = leftValue;
    //Get low and high values for the right sensor
    if(rightValue > rightHigh) {
      rightHigh = rightValue;
    } else if(rightValue < rightLow) {
      rightLow = rightValue;
  int factor = 8; //This value worked for us however you might want to change it for your robot/flashlight intensity.
  // Light following loop
    //Maps both sensors to a scale of 0-20. 20 was chosen so the calculation doesn't overflow (use a number larger than 16 bits)
    leftValue = (SensorValue[leftLight] - leftLow) * 20 / (leftHigh - leftLow);
    rightValue = (SensorValue[rightLight] - rightLow) * 20 / (rightHigh - rightLow);
    //Find the difference in light values
    int shadeDiff = (leftValue - rightValue);
    //Run the motors
    motor[leftServo] = 40 + (shadeDiff * factor);
    motor[rightServo] = 40 - (shadeDiff * factor);
    //If the loop cycles too quickly, we get calculation errors. Therefore we regulate the speed by waiting a bit.