How to use multiple procedures

From GoGoWiki

Jump to: navigation, search

Sometimes it is a good to divide your program into sub procedures. It can often make your program more understandable to others. It can also save memory when a certain section of your program is used multiple times.

Here's an example. Let's assume that we have a robotic vehicle. It can move forward or backward by controlling a motor connected to the "A" port. It also has front and rear bumpers (sensor1 and sensro2 respectively). The following program moves the car forward until the front bumper hits something. It then moves backwards until the rear bumper is triggered.

to moveForwardAndBack
  ; move forward until the front bumper is triggered (value < 500)
  a, thisway on
  waituntil [ sensor1 < 500 ]
  off

  wait 10 
  
  ; reverse directoin and move until the rear bumper is triggered
  a, thatway on
  waituntil [ sensor2 < 500 ]
  off
  
end

The same program can be created with multiple procedures as follows.

to moveForwardAndBack

  moveForward
  wait 10
  moveBackward

end

to moveForward
  ; move forward until the front bumper is triggered (value < 500)
  a, thisway on
  waituntil [ sensor1 < 500 ]
  off
end

to moveBackward

  ; reverse directoin and move until the rear bumper is triggered
  a, thatway on
  waituntil [ sensor2 < 500 ]
  off
  
end

This second approach allows the main program to be a bit more readable to others. The procedure contents are simply moved into the procedures "moveForward" and "moveBackward"

Note the the top-most procedure will always be the one called first.

Here's a second example

to doControl
  forever [
    if sensor1 < 500 [ a, onfor 10 ]
  ]
end

Assuming that sensor 1 is attached to a touch sensor, the program will turn on motor A for 1 second every time the sensor is pressed. Now take a look at the next program, which does the same thing but with two procedures.

to doControl
  forever [
    if pressed [ a, onfor 10 ]
  ]
end

to pressed
   output sensor1 < 500
end

This time "if sensor1 < 500" is replaced with "if pressed" It makes the program more human readable. The expression "sensor1 < 500" is moved into the "pressed" procedure, which outputs its value to the main procedure.