Appendix E: Cricket 2 Code

 

global [leftir rightir fldist bldist fdist num1 num2 thold temp diff candlethold inroom]

to main
setthold 3 ;range used in mathematical procedures
setcandlethold 150 ;indicates that robot is too close to candle and should stop
set inroom 20 ;indicates if candle is in the room.
waituntil [newir?]
if (ir = 2) ;message from cricket 3 that robot has entered a room.
[ifelse (check-room)
[send 1 ;tells other crickets that candle is in the room, and
zigzag] ;begin moving towards it
[send 0] ;candle is not in room, so exit
]
end

 

to zigzag
send 6 ;go forward
loop[
get-sensors
if (leftir > rightir)
[send 4] ;turn left, aligning toward candle.
if (rightir > leftir)
[send 5] ;turn right, aligning toward candle.
if ((leftir > candlethold) and (rightir > candlethold)) ;too close to the candle
[send 7 ;turn wheels off
align-candle ;final alignment so that the robot faces candle directly
extinguish]
if (newir?)
[if (ir = 3) ;signal from Cricket 3: the robot is within 12" of the candle
[send 7 ;turn wheels off
align-candle ;final alignment so that the robot faces the candle directly
send 16 ;message to other crickets to stop running their programs
extinguish]
]
wait 2]
end

 

to check-room
ifelse (sensora > inroom and sensorb > inroom)
[output 1] ;ambient infrared light is greater than threshold; candle is present
[output 0] ;candle is not here
end

 

to align-candle
loop [
get-sensors
if (less-than rightir leftir)
[send 15] ;pivot left
if (less-than leftir rightir)
[send 14] ;pivot right
if (equals leftir rightir)
[send 7 stop] ;turn wheels off
]
end

 

to delay :n ;shorter than wait command
repeat :n [resett]
end

 

to extinguish
a, thisway on ;gear rack going down
wait 200
a, thatway on ;gear rack going up
wait 200
a, off
end


;mathematical procedures and procedures to check the environment


to less-than :num1 :num2 ;determines if num1 is significantly less than num2
;(by more than thold)
ifelse (:num1 < (:num2 - thold))
[output 1]
[output 0]
end

 

to equals :num1 :num2 ;determines if num1 and num2 are within the range of thold
ifelse (abs (:num1 - :num2) < thold)
[output 1]
[output 0]
end

 

to abs :n ;calculates the absolute value of n
ifelse :n < 0 [output ( -1 * :n)]
[output :n]
end

 

to get-sensors
setleftir sensorb
setrightir sensora
end