/* File: lightAvoidance.ch the NXT robot will avoid facing light when a source of light is approaching */ #include #include CMindstorms robot; double lightValueMax = 100, // the largest possible light sensor reading lightValueMin = 0; // the smallest possible light sensor reading double powerFactor = 0.4; // an arbitrary constant for calibrating output power double turnLeft, // correction value of left motor power turnRight; // correction value of right motor power int lightValueLeft; // value of the left light sensor reading int lightValueRight; // value of the right light sensor reading int targetPower = 20; // power that outputs when the difference of lightValueLeft and lightValueRight is 0 int powerLeft, powerRight; robot.setSensorLight(PORT3, "Ambient"); robot.setSensorLight(PORT2, "Ambient"); /* an infinite while-loop which keeps the robot running */ while (powerFactor > 0) { robot.getSensorLight(PORT3, lightValueLeft); robot.getSensorLight(PORT2, lightValueRight); turnLeft = (lightValueLeft - lightValueRight)*powerFactor; turnRight = (lightValueRight - lightValueLeft)*powerFactor; powerLeft = round(targetPower + turnLeft); powerRight = round(targetPower + turnRight); robot.setJointPower(JOINT2, powerRight); robot.setJointPower(JOINT3, powerLeft); robot.moveForeverNB(); }