Figure 4-4 shows the completed catapult robot, programmed using the NXC code in this excerpt.
Figure 4.4 The completed catapult
For the NXC program, start with declaring the two touch sensors:
// enable NXC
#include "NXCDefs.h"
// main
task main() {
// define sensors at port 1 and 2 to be touch sensors
SetSensorType(IN_1,IN_TYPE_SWITCH);
SetSensorType(IN_2,IN_TYPE_SWITCH);
}
The infinite loop looks very similar to the one in RobotC, so proceed to the lifting of the crank mechanism:
…
task main() {
…
SetSensorType(IN_2,IN_TYPE_SWITCH);
// endless loop
while(1) {
// lift crank mechanism
RotateMotor(OUT_A, 75, 30);
}
}
Running the gear wheel until the first touch sensor triggers a "pressed" event loads the catapult:
…
task main() {
…
while(1) {
…
RotateMotor(OUT_A, 75, 30);
// load catapult
// run motor until the first
// touch sensor gets pressed
OnFwd (OUT_C, 100);
while(Sensor(IN_1) == 0) {
// do nothing
}
Off(OUT_C);
}
}
Waiting for the user to press the second touch sensor is done as follows:
…
task main() {
…
while(1) {
…
Off(OUT_C);
// wait for the user to press the second touch sensor
while(Sensor(IN_2) == 0) {
// do nothing
}
}
}
Now drop the crank:
…
task main() {
…
while(1) {
…
while(Sensor(IN_2) == 0) {
// do nothing
}
// drop crank mechanism
RotateMotor(OUT_A, -75, 30);
}
}
And wait:
…
task main() {
…
while(1) {
…
// drop crank mechanism
RotateMotor(OUT_A, -75, 30);
// wait for two seconds
Wait(2000);
}
}
Here's the complete NXC program for the catapult:
// enable NXC
#include "NXCDefs.h"
// main
task main() {
// define sensors at ports 1 and 2 to be touch sensors
SetSensorType(IN_1,IN_TYPE_SWITCH);
SetSensorType(IN_2,IN_TYPE_SWITCH);
// endless loop
while(1) {
// lift crank mechanism
RotateMotor(OUT_A, 75, 30);
// load catapult
// run motor until the first
// touch sensor gets pressed
OnFwd (OUT_C, 100);
while(Sensor(IN_1) == 0) {
// do nothing
}
Off(OUT_C);
// wait for the user to press the second touch sensor
while(Sensor(IN_2) == 0) {
// do nothing
}
// drop crank mechanism
RotateMotor(OUT_A, -75, 30);
// wait two seconds
Wait(2000);
}
}