//PROGRAM # 3
/* BUMP A LOT
(revised)---- Tankbot with one touch sensor: it backs up and turns either left
or right (random) when it runs into something. 2 tasks and 1 inline function. I
use the inline function instead of subroutines because the subroutines are
extremely limited. They cannot use any arguments! They cannot call another
subroutine, and they cannot have a local variable if the subroutine is being
called from multiple tasks. Subroutines do save space, as only a single copy of
the subroutine code is used and shared by different callers. When using inline
functions, another copy of the code is included in the program every time it is
called, which takes up more of your limited space. The big advantage of inline
functions is that it allows the use of 4 different argument types (see NQC
Programmer’s Guide) which provide a great deal of versatility, even allowing a
return value using the pass by reference argument "int &". */
// sensors- same
as original Bump A Lot program
#define BUMP SENSOR_2
// motors- same
as original Bump A Lot program
#define LEFT OUT_A
#define RIGHT OUT_C
// other
constants
#define
TURN_TIME 150 //1 1/2 second
#define REV_TIME 50 //1/2 second
#define
NOTE 440 //frequency of sound
#define
NOTE2 660 //frequency of
sound
task main()
{
// configure sensor- tells the RCX that
the sensor at port 2 (BUMP) is a
//touch sensor
SetSensor(BUMP, SENSOR_TOUCH);
// Robot moves foward
On(LEFT+RIGHT); //turns LEFT & RIGHT motor on
//begin task called “bump”
start bump;
}//main
//this task has
the robot back up, turn (random right or left) and move forward
//if the touch
sensor is pressed. It also plays a sound before turning
task bump()
{
while(true) //necessary or RCX will only perform task once
{
until(BUMP==1); //touch sensor pressed
int
x = Random(2); //x is random variable (either 0 or 1)
if (x<1) //if x is 0, play
“right” sound and turn right
{
playsoundR(); //Calls inline function “playsounR”
// back up
Rev(LEFT+RIGHT);
Wait(REV_TIME);
// spin around
Fwd(LEFT);
Wait(TURN_TIME);
// resume
Fwd(RIGHT);
}
else //if x is 1, play “left” sound and turn
left
{
playsoundL(); //calls inline function “playsoundL”
// back up
Rev(LEFT+RIGHT);
Wait(REV_TIME);
// spin around
Fwd(RIGHT);
Wait(TURN_TIME);
// resume
Fwd(LEFT);
}//else
}//while
}//task
//inline function
plays note at frequency 440 for 1/2 second
void
playsoundR()
{
PlayTone(NOTE, 50);
}//return
//inline function
plays note at frequency 660 for 1/2 second
void playsoundL()
{
PlayTone(NOTE2, 50);
}//return