Introduction To Robotc Programming
Introduction To Robotc Programming
1) First, download the firmware onto the NXT brick: connect the brick, select "Download
Firmware" from RobotC "Robot" menu, and click on F/W Download button. Select the
newest firmware version (highest number) from list.
2) Try out this simple test program with your robot: note the comments, the task main()
statement, the semi-colons, square brackets and curly brackets, and use of white space and
indentation. This one makes the motors run for specified time intervals.
/* timed motor.c
* example of timed motor movement
* Mr. Judkis - 2/25/09
*/
task main()
{
// set motors B and C to 100% power, then wait 3 sec
motor[motorB] = 100;
motor[motorC] = 100;
wait1Msec(3000);
// turn them off, and wait 1 sec
motor[motorB] = 0;
motor[motorC] = 0;
wait1Msec(1000);
Then try out this one, that makes the motors run for specified numbers of rotations:
/* count rotation.c
* example of specifying how many rotations to make
* Mr. Judkis - 2/25/09
*/
task main()
{
// reset rotation sensor, set power to 70%
nMotorEncoder[motorA] = 0;
motor[motorA] = 70;
// while loop -- wait for 5 rotations
while(nMotorEncoder[motorA] < 1800)
{
; // nothing to do -- just waiting. . .
}
The code above uses the rotation sensor, something we haven't used before. It simply counts
the total rotations of the motor. We set its value to zero, turn on the motor, and wait until the
sensor indicates that the motor has turned the specified number of degrees.
Finally, this code allows a robot with a light sensor to follow the edge of a taped line:
//*!!Sensor, S1, lightSensor, sensorLightActive,
,
!!*//
//*!!
!!*//
//*!!Start automatically generated configuration code.
!!*//
const tSensors lightSensor
= (tSensors) S1;
//sensorLightActive
//*!!!!*//
//*!!CLICK to edit 'wizard' created sensor & motor configuration. !!*//
task main()
{
// loop forever
while(true)
{
// if the lightsensor reads a value less than 45, then the "if"
// code will be run
if(SensorValue(lightSensor) < 45)
{
motor[motorA] = 75;
// motor A is run at 75% power
motor[motorB] = 25;
// motor B is at 25% power
}
else
// if the lightsensor reads a value greater than or equal to 45,
// then the "else" code will be run
{
motor[motorA] = 25;
// motor A is at 25% power
motor[motorB] = 75;
// motor B is run at a 75% power
}
}
}
The code at the top, in italics, bracketed with the //*!! and !!*//, is automatically
generated by the Motors and Sensors Setup menu item under Robot. You don't need to type it
in, let RobotC create it for you:
W
Experiment with the power values for motorA and motorB, and see how fast you can make
your robot follow the edge of the tape on the floor.
267926127.doc - 4/26/2015 page 2 of 2