Using Sensors
Listing 4.5 shows a program that will display the value of the light sensor. In order towrite the program in Listing 4.5, the programmer must \declare" a light sensor variable.
Fortunately, RobotC makes it easy to do this. Just select the menu item Robot! Motors
and Sensors Setup. In the resulting window, select the Sensors tab. There are 4 lines labeled
S1, S2, S3, and S4. Each line corresponds to the ports on the NXT brick labeled 1, 2, 3, and
4 respectively. With the light sensor plugged into Port 1, we ll in the S1 line. In the rst
eld, we give a variable name to the sensor, e.g. LightSensor. Any name may be used as
long as it follows the variable naming rules of Section 4.1. Next we choose the sensor type:
Light Inactive. (Light Active uses the same sensor, but in a mode where a small light
is turned on to aid in low-light situations.) When completed, RobotC will insert the sensor
declaration line as seen at the top of Listing 4.5.
# pragma config ( Sensor , S1 , LightSensor , sensorLightInactive )
task main () {
int LightLevel = 0;
LightLevel = SensorValue [ LightSensor ];
nxtDisplayString (3," Light level : %d", LightLevel );
wait10Msec (300);
}
Listing 4.5: This example will take a single reading from the light sensor and display the
value in a formatted string. Notice the instruction at the top of the program inserted by
RobotC to declare the light sensor.
A light sensor reading is of integer-type. The current value of the light sensor is always
available in SensorValue[LightSensor] (this is actually one element of a special array of
values that we will discuss later). In the square brackets, we nd the variable name that
we have declared for the light sensor. For simplicity and readability, we store the light
sensor reading in the integer-type variable LightLevel (an indeterminate value). We use
this variable to display the light level in a formatted string.
No comments:
Post a Comment