Vous êtes sur la page 1sur 73


472 Fire-Fighting Robot

Industrial Systems Design & Integration

Team 4

Matthew Playne 03070905

Courtney de Lautour 02381036
Ben Langley 01090194
Daniel Mills 02214806

Submitted to: Peter Xu

Date: 02/06/06

The aim of this assessment was to design and construct a Fire-Fighting Robot which would extinguish
m ultiple candles w hilst avoiding any obstacles in the robot’s path.This project w as a group project and
was to be completed before the end date of 29 May 2006.

Our robot was primarily design using the CAD software, with extensive detailed drawings enclosed in
this report. The main structure of the robot was made of light 3mm aluminium plate. The drive line
was provided by two low speed motors with connected gearboxes and two RC wheels. We decided on
digital UV sensors to provide the distance we were from objects and we used an UVTron for flame
detection. The brains of our robot were provided by a M16 microcontroller which was purchased from

Each member of the group was allocated a different section of the project to complete. We had
allocated times to work on the project in the lab. The sections we split the robot up into were, CAD and
Design, Mechanical, Electrical and final the Software. These areas are discussed in greater detail in the
report. We believe the factors influencing the success of the robot were good teamwork and starting
the project as soon as practically possible.

On completion of the initial programming of the robot we had a testing process to undertake. The
initial testing was conducted in stages. Firstly we needed to get the obstacle avoidance working as
required then we incorporated the flame detection circuit at a later date. We conducted a fine tuning
session w here w e adjusted our code to ensure the robot’s sensors w ere operating as efficiently as

We encountered numerous problems with the construction of our robot. We had wheels slipping on
the shaft under load, the sensor wires moving during operation (thus not giving a correct reading) and
stability problems as we only used two wheels to drive the robot. All problems were overcome in the
later stages of then project.

To complete this project we needed to use all the different engineering knowledge areas we had been
previously taught whilst studying at Massey University. The project proved a success with our robot
efficiently extinguishing the candles and avoiding the obstacles we placed randomly around the table.

Table of Contents

Summary Page 2

1 - Introduction Page 5
1.1 - Project Introduction Page 5
1.2 - Project Specifications Page 5
1.3 - Acknowledgements Page 5

2 - Design Page 7
2.1 - Design Overview Page 7
2.2 - Mechanical Page 7
2.2.1 - Chassis Page 7 - Specifications Page 7 - Initial Concepts Page 7 - Construction Page 7 - Additions to the Design Page 8
2.2.2 - Drive Train Page 8 - Specifications Page 8 - Initial Concepts Page 8 - Construction Page 8 - Additions to the Design Page 8
2.3 - Sensors Page 9
2.3.1 - crossSense Technology Page 9 - Initial Design Page 9 - Implementation Page 9
2.3.2 - UVTron Page 9
2.4 - Controller Page 10
2.5 - Electrical Page 10
2.5.1 - Specifications Page 10
2.5.2 - Initial Concepts Page 11
2.5.3 - Construction Page 11
2.5.4 - Additions to the Design Page 11
2.6 - Computer Aided Design Page 12
2.6.1 - Design / CAD Page 12
2.6.2 - UVTron Page 12
2.6.3 - Renesas M16C Microcontroller Page 12
2.6.4 - Support Board Page 13
2.6.5 - crossSense Technology Page 13
2.6.6 - Skids Page 14
2.6.7 - Aluminium Hubs Page 15
2.6.8 - Full Model Page 15

3 - Software Design Page 17

3.1 - Hardware Drivers Page 17
3.1.1 - Specifications Page 17
3.1.2 - GetDistance Page 17
3.1.3 - SetMotors Page 17
3.2 - Control Systems Page 19
3.2.1 - Specifications Page 19

3.2.2 - Initial Concepts Page 19
3.2.3 - Final Layout Page 19 - Search for Flame Page 20 - Extinguish Flame Page 21 - Escape Page 22 - Avoid Page 23 - Follow Flame Page 24 - Coding Page 25

4 - Testing Page 26
4.1 - Initial Testing Page 26
4.2 - Fine Tuning Page 26
4.3 - Improvements Page 26

5 - Problems Encountered Page 27

5.1 - Drive Motors Page 27
5.2 - Orientation of Development Board and Bracket Page 27
5.3 - Sensor Connections Page 27
5.4 - Fan and Motor Bush Page 27
5.5 - Last Minute Hiccup Page 27

6 - Conclusions Page 28
6.1 - Conclusions Page 28
6.2 - Personal Conclusions Page 28
6.2.1 - Ben Langley Page 28
6.2.2 - Matthew Playne Page 29
6.2.3 - Courtney de Lautour Page 30
6.2.4 - Daniel Mills Page 31

7 - References Page 32

8 - Appendices Page 33
8.1 - Appendix A - Bill of Materials Page 33
8.2 - Appendix B - Sharp GP2D02 Data Sheet Page 35
8.3 - Appendix C - Renesas M16C 62P Data Sheet Page 39
8.4 - Appendix D - UVTRON Flame Detector Bulb Data Sheet Page 40
8.5 - Appendix E - UVTRON Flame Detector Driver Data Sheet Page 42
8.6 - Appendix F - ST Microelectronics L293D Motor Driver Data Sheet Page 44
8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet Page 51
8.8 - Appendix H - 70 RPM Drive Motor Data Sheet Page 59
8.9 - Appendix I - Fire Fighting Robot Source Code Page 60

1 - Introduction

1.1 - Project Introduction

Throughout the past 3 years of our Mechatronics degree at Massey University we have gained knowledge in areas such as:
mechanical, electrical, software and electronic engineering. We have in particular focused on: motion actuation, sensing,
signal processing and microprocessor control. For the paper Industrial Systems Design and Integration we were required to
combine and demonstrate these skills by means of a group project.

This year the project was to design and build a Fire-Fighting Robot. The robot was required to move around obstacles and
detect and extinguish small fires, which were simulated by candles. The robots were required to be built by the end of
semester one with a competition against the other groups as a final assessment.

As to building the robot itself we were also required to complete a report and web page for our robot. These were to give
greater explanation of the design and construction phases of the robot as well as to visually show diagrams and
photographs of the robot we constructed.

1.2 - Project Specifications

Initially there were a number of specifications that needed to be met in order to successfully complete the project. The fire
fighting robot we produced was designed, built and operated with these project specifications in mind. These specifications
are listed below:

● The Fire-Fighting Robot is a group project - groups are to be chosen by the students with a maximum of
five in each group.

● Students are to schedule their own time slots to work on the project, utilising the laboratories provided.
Any manufacture of materials is to be organised with workshop staff.

● The Fire-Fighting Robot must be completed before the date of 28 May 2006. Testing of its operation is to
be conducted on this date.

● The robot is to be autonomous when in run mode, and no human intervention is to take place throughout
the entire assessment time.

● The robot is required to find and extinguish two candles randomly placed on the table.

● The robot is to implement obstacle avoidance at all times whilst tracking and extinguishing the candles.

● The robot is not to use any destructive methods to extinguish the candle. The candle is not to be touched
by the robot at any time during the assessment.

● The size and the dimensions of both the robot and candles is determined by the students, also noting the
physical dimensions of the test table in the engineering laboratory.

 Each group has a budget of $400, supplied by Massey University, to design and build the Fire-Fighting Robot.
Additionalfunding can be used from the students’personalfunds.

1.3 - Acknowledgements

There are num erous persons w e w ould like to thank for their contribution to our team ’s success in the Fire Fighting robot
competition. Firstly we would like to thank the NZDF for the material (aluminium plate) which they kindly donated to the
project. We would like to thank the workshop staff, Raymond and Eddy, for being of assistance whilst manufacturing the
structural aspects of the robot. We would like to thank Jenny for her assistance in the ordering of our equipment from
overseas locations. A special mention also needs to be given to Peter who assisted in the equipment selection process
when designing our robot and also being the overseer of the Fire-Fighting robot. Johan and Olaf offered constructive
criticism (sometimes) for the methods we were using in the construction of our robot. Last but not least I would like to
thank our classmates who provided exciting competition in the final assessment for the Fire-Fighting robot.

2 - Design

2.1 - Design Overview

As with most projects the design stage of the project is very important. We were aware that decisions that we made early
on in the project could have big implications later on regarding the overall success of the project. For that reason we made
the decision to spend several weeks on the design stage of the project in order to ensure that we had covered all aspects of
the project and come up with the most suitable design possible.

We decided to work first on the mechanical design aspects of the project. We adopted an open approach to design ideas
from the team. From these initial discussions we were able to quickly zero in on the best solution. We then moved on to
the other mechanical aspects of the project. We were initially less concerned with the electrical and control aspects of the
project as what controller we decided to use would have no impact on the mechanical portion of the project. We had been
made aware that often the teams left the mechanical aspects to the last minute which had resulted in a back-log of work
for the workshop staff. We therefore ensured that we got as much of the mechanical construction done as quickly as possi-
ble so as to avoid delays.

While we were working on the mechanical design and construction of the robot we were also researching the best options
for the control and sensing aspects of the project. We took quite a lot of time to make final decisions on these aspects of
the project. As it turned out it was worth waiting to ensure that we got the right components. We had initially decided to
use a Microchip PIC-based microcontroller but after further consideration we decided to go with the cheaper and more
powerful Renesas M16C-based controller. This was a controller that Matthew had worked with during his summer job and
so he was familiar with its use.

Having spent a lot of time designing the mechanical components we had very little difficulty with things not working prop-
erly. There were several minor components which we designed as the need for them arose. We all imposed high standards
on our own work; this resulted in a well-built and reliable robot. This hard work in the construction of the unit would result
in significant time savings during the testing stages, as we did not have the long down-times that some of the other teams
experienced due to reliability issues.

The following sections describe in detail the different hardware design aspects of the project.

2.2 - Mechanical

2.2.1 - Chassis - Specifications

Firstly we needed to analyse what the robot needed to achieve and how we were to design and build a chassis to meet
those requirements. We decided to keep the robot chassis as simple as possible to achieve the tasks it needed to. We
discussed the specifications of the robot and came to a number of conclusions. The robot needed to be: light in weight,
small and an easy shape to move around the table and avoid obstacles and cheap to manufacture. - Initial concepts

We had two initial ideas for the shape of the chassis. The first was a rectangular platform with two drive wheels and a pivot
bearing at the rear. This was thought of as it was of similar shape to the robot we constructed in Year 1 of our course. The
other concept was a circular shape with two drive wheels. - Construction

We decided to go with the circular design for the chassis as we predicted it would be more manoeuvrable around the table
as it would be able to turn on the spot. The chassis was constructed from 3mm aluminium plate which we were gifted by
the Royal New Zealand Navy. We decided to make the chassis 200mm in diameter which was large enough to mount the
wheels and motors but also as small as possible to navigate around the table. The workshop at Massey University was used
for all construction with the fasteners also being supplied by the University. We decided to have the wheels mounted on
the inner of the circle as opposed to outside the circle. We then thought with the wheels mounted on the inner of the circle
and the chassis kept low to the ground we would not need any further roller wheels for stability. - Additions to the Design

There were a number of changes made to our original design which was of circular shape with a diameter of 200mm. We
mounted a second level as we required more room to place our circuit boards and our extinguishing device. This second
level was again 200mm in diameter and the distance between the two was 50mm. By adding a second level we needed
supports to hold the second levelin position.W e used a “C” design for these brackets.W e then thought that w e could
mount the 3 distance sensors on these brackets, which would save making additional mounting brackets from the top level.

We also found we needed to increase the stability of the now two-level chassis. We thought of using ball bearings which
could be locally purchased but in order to keep cost down we designed and made skids for the front and back from material
in the workshop. The skids were constructed from nylon and followed the shape of the chassis. If these skids did not work
satisfactorily we would have purchased the ball bearing wheels.

From the top level we designed a holder for our fan (used to extinguish the flame). It was designed to be higher than the
top level and be angled downwards on a slight angle to help with the extinguishing of the flame.

2.2.2 - Drive Train - Specifications

We decided we needed to use motors which were of relatively low speed with higher torque. From the start the plan was
to find motors with excess power for the application; this would then provide a safety margin if we needed to add more
weight to the robot. The low speed motors needed a gearbox and also two drive wheels. - Initial Concepts

There were several methods of producing a drive train that we investigated. We could have the motors connected to a gear
box and then to the wheels of the robot. The second design was to find motors with built in gearboxes which could be
directly coupled to the wheels themselves. Lastly we were considering using stepper motors to move the robot. This would
have had the advantage that exact positioning would have been possible. We thought about this option for some time
before deciding that it would be unnecessarily complicated. - Construction

We decided to use two 70 RPM motors, with the connected gearboxes, for our robot. These were purchased from Jaycar
Electronics for approximately $15 each. We assumed by using the motors with the connected gearboxes they would be
superior in reliability compared with an added on plastic gearbox. The wheels were supplied from a team member, which
had been used in a previous project. The motors were mounted to the chassis by brackets which were purchased from
Hammer Hardware. - Additions to the Design

It was found that simply gluing our motors onto the plastic wheels was very ineffective. We had slipping of the wheels
about the motor shafts. We then consulted Raymond, the workshop technician, and some adapter plates were made to
attach our motors to our wheels. These were made of aluminium and had a grub screw to prevent the wheel slipping off
the shaft.

2.3 - Sensors

2.3.1 - crossSense Technology - Initial Design

One of the given parameters for our design was to have sensors which would give us a range rather than just a proximity
reading. We also wanted to minimize the amount of sensors used; this saves cost and makes, making a control system sim-

Our initial plan was to use some form of sensor rotating about the centre of our robot; from this we would have a 360 o field
of view. This would enable us to perform path finding and mapping operations. In turn this would enable us to know exactly
were we had been and where the next likely place for a candle was. However given the size of the world in which the robot
was placed this was an unnecessary step and we decided that the extra effort required would be wasted (in terms of func-
tionally usefulness).

Our original sensor choice was to use ultrasonic, however after consultation we found that these may have problems in
that they could interfere w ith each other and the sound w aves could reflect unpredictably and a single “pulse” could be
received more than once, which may or may not have been read as the return from a separate measurement.

W e decided to use infrared laser sensors as these don’t interfere w ith each other and don’t have the sam e problem s w ith
unpredictable reflections. The ones we chose were Sharp GP2D02 Infrared Laser Distance Finders, and returned a result as
an 8 bit serial value. - Implementation

We decided that it was important that we were able to get a full field of view in front of the robot. In order to get this we
worked out that if we crossed our sensors over we would effectively have a screen; the areas where one sensor was unable
to see would be covered by the other.

This layout also allowed us to see objects which were approaching from the front, along with those on the side. Since we
wanted to take the same actions for both (turn away if possible) this was not a problem.

As mentioned the robot would turn away from upcoming walls as with equal importance to those on the side. We could
effectively affect the priority it gave to each of these by altering the angle we had the sensors set on; pointing more for-
wards would mean that turning from an upcoming wall was more important than keeping a distance from a wall on the
side. In the end we came up with an angle for the sensors which was able to meet both expectations along while still being
able to detect smaller objects directly in front of the robot quickly enough to take evasive action.

With the sensors crossing over we were able to accurately detect objects which were within 200mm from the side of the
robot and 250mm in front. Any object needed to be within 70mm of a sensor for the reading to become unreliable. This
translated into being approximately 20mm away from the chassis of the robot, by which stage evasive action should hope-
fully have been taken.

One issue of the sensors themselves was that occasionally they would return a false reading, which was was often valued at
zero. To fix this we included a method (in software) which would average out the last five readings from the sensors. While
this reduced response times we found that it remained quick enough to avoid all but the smallest objects. This averaging
prevented the behavior “Escape” to trigger unpredictably,as it had before w e im plem ented the system .In an attem pt to
increase response times we added a linear weighting to each reading, the newest being five times more important than the

2.3.2 - UVTron

For sensing the flame we decided to use a pre-built flame sensor package. The device which we chose to use was called the
UVTron by HAMAMATSU; this can detect flames in a lit room from five meters. This works by UV light hitting a filament in a
bulb attached to the board; as this occurs electrons are discharged into a thin plate, which is then converted by the on
board electronics to a useable value.

The output from the board is modulated as a low pulse signal (a voltage drops from high to low at a frequency depending
on the strength of the flame). When a flame was directly in front of the UVTron this was at a frequency of ten hertz; as the
flame was moved away / covered this frequency would drop off to zero.

Again, as with the distance sensors, we needed to average the readings to prevent rogue readings from triggering
behaviours unnecessarily.

2.4 - Controller

Perhaps one of the most important decisions that we had to make was which microcontroller we were going to utilize for
the project. There were several important considerations that we had to take into account when selecting suitable candi-

 Performance - The unit needed to have a high clock rate and accurate timers in order to enable fast processing of
sensor data and to ensure a high rate of control processing

 Ports - The unit needed to have enough ports to allow us to do all of the things that we needed to. In addition to
this the unit needed to have 2 PWM outputs and enough timers and external interrupt lines

 Cost - The unit needed to be as inexpensive as possible, as not only did we need to purchase the unit itself, but
also the programmer; this cost needed to be taken into account.

 Ease of use - The controller needed to be easy to use and program.

Based on these criteria we selected two candidates from which to make our final choice: The Microchip PIC 18 Series and
the Renesas M16C. We initially favoured the PIC due to its simplicity and inexpensive nature. Also we had all used this chip
in one of our third-year papers Embedded Systems Design (140.320). After further investigation however we had some con-
cerns as to the performance capabilities of this controller. In addition to this it was going to be considerably more expen-
sive to go with the PIC option rather than the M16C.

In the end we decided to go with the M16C. Matthew, who would be doing a lot of the low-level coding, had worked exten-
sively with this controller during the summer work period. In addition to this the controller could be programmed in ANSI C.
This meant that Courtney, who would be doing most of the high level programming, would be able to program the chip
without any past experience with the M16C. This unit was subsequently purchased and the programming process could

Please note that the specifications for this unit are listed in Appendix C.

2.5 - Electrical

2.5.1 - Specifications

By the time that we started work on the electrical section of the project the team had made a decision as to the type of
sensors and microcontroller that would be used. As mentioned in the above sections we had decided to use infra-red laser
range finders, the UVTRON flame detector and the Renesas M16C microcontroller. One of the reasons that we chose the
sensors that we did was to make interfacing between sensors and the microcontroller as easy as possible. Secondly the
digital nature of the sensors that we used meant that we would not need to perform time-consuming analogue to digital
conversions. In addition to this, after much discussion regarding the type of motors we would use to move the robot, we
decided on a PWM based DC motor design. The use of PWM to control the motors meant that we were able to keep the
outputs from the microcontroller digital as well. This meant that we did not have to use the onboard DAC.

Because of our careful selection of sensors and control methodology the additional electronics required was minimal. Mat-

thew, who due to past experience was in charge of the electrical and control engineering aspect of the project, decided to
construct all additional necessary electronics on a single support board. This board would contain all of the power supply
and logic control circuitry required for interfacing between the sensors, motors and microcontroller.

2.5.2 - Initial Concepts

An initial investigation was performed in order to select the most suitable components required for the task at had. The
decision was made to use prototyping board and link wire to construct the circuit. This meant that the circuit could be eas-
ily modified while being neat and tidy. Based on what we had learned in lectures the decision was made to utilize the
L293D Half H Bridge motor controller. When configured correctly this chip could be used to power the motors via PWM in
both the forward and reverse directions. The decision was made to use two of these driver chips, one for each drive motor.
The reason this approach was chosen was to reduce the current load on each of the chips as at that stage we were unsure
as to how much current the drive motors would use under load.

In addition to this it was necessary to provide several regulated voltage levels from the on-board power supply. We had
initially decided to use a 12V supply for the robot. As the CMOS circuitry and the M16C use a 5V supply we used a 7805 5V
regulator with 470uF and 100nF capacitors for smoothing. We left the 12V supply to the drive motors unregulated, but
placed smoothing capacitors (470uF + 100nF) over the supply.

Finally the board was to also provide an interface between the sensors and the microcontroller. The microcontroller and
the support board are connected by a 50 pin IDC connector; this gave us access to enough of the ports and functions that
we required. Connectors for the sensors, motors, and supply were also to be added to the board.

2.5.3 - Construction

The support board was assembled over a couple of days. Matthew did this as he had the most experience with this sort of
construction having worked on several design projects over the summer work period. The main features of the board were
tested as they were implemented and when complete the board was working and required no modifications. No official
circuit diagrams were drawn before-hand as this board was a very simple circuit and as such required no major design
thought beforehand. The circuit, once complete, was implemented on the robot. As other areas of the project progressed
additions and changes were made to the circuit as necessary.

2.5.4 - Additions to the Design

After the initial design and construction of the board was complete we were able to progress in other areas of the project.
As advances in these areas were made and further design decisions were made it was necessary to make changes and addi-
tions to the support board and the related electronics.

The first major change that was made was to convert the entire electrical subsystem from a 12V DC supply to an 18V DC
supply. This change was made as the team considered it an advantage to run the drive motors at their maximum of 18V in
order to give a greater range of control over the speed of the robot. As our extinguishing unit was to run on 12V it was nec-
essary to add a 12V regulator to the circuit. In addition to this we added additional filtering and smoothing capacitors to
ensure that the inductance from the motors did not affect the lower level voltage supplies.

The second major change that we made was swapping the orientation of the IDC connector around. This change was made
to enable the Microcontroller board to sit above the support board and be connected directly by a cable. This change was
easy to make, however a mistake was made in the rerouting of the wires which took about an hour to resolve. Although
this was a minor issue a better approach would have been to draw out all of the changes to be made to ensure that nothing
was left to chance.

The final changes made to the board were to add connectors for the extinguishing unit and to reroute the motor drivers to
enable one driver to power both of the drive motors off 18V leaving the other one available to power the extinguishing unit
at 12V. We had determined by that stage that the current the drive motors were drawing was small enough to enable run-
ning both of them from one chip.

Once all of these changes were made heat sinks were added to both of the motor drivers and the 12V regulator. This was to
ensure low-temperature, reliable operation during long testing stints.

2.6 - Computer Aided Design

2.6.1 - Design / CAD

We used CAD at the very start of our project to help portray ideas and concepts for chassis design. From the beginning the
team decided on a round chassis, with centrally located internal wheels, to allow for the best turning ability.

This provided clarity on the design for the team and from here we focused on constructing the chassis of our robot.
Modelling the robot in CAD came back into effect later on in the project timeline, as further design revisions were discussed
between the team and portrayed on paper (due to the nature of the components involved).

2.6.2 - UVTron

The UVTron is located at the front of the upper tier to enable the best flame detection. Due to the bulb not being
directional, a shield was made up to effectively give the sensor direction. The shield is shown in the below image; it is
constructed out of sheet aluminium, and spray painted in matt-black.

2.6.3 - Renesas M16C Microcontroller

We made use of a M16 developer board for the control of our robot. This unit is described in previous sections, but was
added to the CAD model to provide completeness of the drawing.

Though this model of our M16 controller is obviously incomplete, missing many electronic components, it should be noted
that it was tailor drawn, is to scale and shows the dominant components.

2.6.4 - Support Board

This board contains all of the additional hardware circuitry required by the robot.

Again, this model is obviously missing components, but the model is to scale.

2.6.5 - crossSense Technology

This CAD model should help to further explain the object detection sensor setup on our robot. We also used this CAD
model to help obtain desired sensor angles.

The sensors were also mounted on brackets made up of folded sheet metal. This served two purposes: to separate the
upper and lower tiers of the robot; and to allow the sensors to be mounted and pivoted in the desired direction.

2.6.6 - Skids

Another early decision was to use skids instead of a stabilizing wheel, as the surface the robot was to operate on was of
negligible friction and with the drive wheel motor choice, skids would provide the best stability for our application.

2.6.7 - Aluminium Hubs

After problems arose with the hubs provided with the wheels, we had some new, more durable hubs fabricated for us out
of aluminium.

2.6.8 - Full Model

Finally, the complete robot model.

3 - Software Design

3.1 - Hardware Drivers Initialize

3.1.1 - Specifications

Wait for 2ms

The hardware drivers are the low-levelportions ofthe robot’s code.
The purpose of these drivers is to provide a hardware to software
interface that enables access to such hardware as the sensor and mo-
tors from within the behavioural code. The specifications for these
functions were determined by the software development team be- Set Control Lines
fore the coding process started. This was to ensure that the code
would be compatible between the upper and lower layers of soft-
ware. Only two main hardware drivers were necessary for this pro-
ject. In addition to these drivers several internal routines were writ-
If Aquire time >
ten to handle such things as timer interrupts and MCU initialization. 70ms

3.1.2 - GetDistance
If Sensors are
This function is the low-level driver that communicates with the dis-
tance sensors and loads global variables with the returned results. Y
This driver is responsible for initializing the sensors for each reading,
taking the readings, processing them, and then loading them for use Set control lines
by the higher level software. The flow chart for this function is shown high
to the right.

While testing this code at home Matthew discovered a major issue

regarding this portion of the project. It had been our understanding Load new data bit
that the IR Laser Sensors returned a binary value that represented a
distance. We also expected that this relationship would be linear. In
actualfact it w asn’t.After m any hours ofw ork M atthew discovered
that the relationship was actually a third-order polynomial. In order
to linearize this relationship the following steps had to be completed Shift raw value left

for each of the three sensors:

1. Tabulate the relationship for a range of measured distances
2. Graph this relationship Set control lines
3. Use mathematical software to model the graph as an equation
4. Put this equation and its parameters into the code and perform
the conversion for each of the three sensors

This was a very time-consuming process especially as the sensors Wait for 0.2ms
gave different results once mounted on the robot. Once it was com-
pleted however this system worked very well and gave accurate re-
sults between 10cm and 55cm and was reliable in different condi-
If loop < 8

3.1.3 - SetMotor
Calculate Maths
The SetMotor functions are the low-level drivers that, based on a Conversion
value and direction flag, calculate the PWM value and set the corre-
sponding ports and timers to run the motors at the desired speed.
While quite simple functions they are fairly involved as they contain a
lot of error checking to ensure that the values being passed to it are Put formatted data
into global Return
valid PWM values. If it receives any unexpected values it will return variables

error codes corresponding to the error that has occurred. The flow chart for these functions is shown below.

These functions are designed to be simple and easy to modify if necessary. Once when replacing a failed drive motor we
soldered the two wires the opposite way round
to what they had been on the old motor. Rather
than having to unsolder and redo the connec- Initialize
tions we were able to quickly change one line of
code. This sort of example shows how beneficial
well thought-out code is to the testing process.
If PWMValue > Return error code
254 0xFFFE

If direction = If direction = Return error code

forward reverse 0xFFFF


Set direction port Set direction port

to forward to reverse

Set timer value to

PWMValue << 8

Return PWMValue

3.2 - Control Systems

3.2.1 - Specifications:

The system had to be able to respond to three inputs and decide on the outputs for three individual components, this had
to be done in a real time situation and as such the faster the system preformed operations the better the overall result.

It was required that the system be able to detect flames and activate an extinguishing operation while navigating a object
littered field without making contact with any part of the world expect for the ground plane.

3.2.2 - Initial concepts:

From the beginning we planned on using a

behaviour based system. This is essentially providing
cases in which we know what the outputs should be, Get sensor
each case has a priority and if it is triggered it will infomation

overrule the actions by all lower priority behaviours.

One good example of this is if you are tracking
towards a flame but approach a wall. The behaviour
w hich says “turn aw ay from w alls” w illoverride the
Too long since Turn for 360
“go tow ards a flam e” behaviour,since you can find we last saw or looked Y degrees or until
the flame again however touching a wall is against for a flame? we see a flame
the rules.

3.2.3 - Final Layout:

Perform extinguishing
Is fan on? Y procedure, turn fan off
The final layout we used differed from the when finished
conventional behaviour based structure. As we
discovered new behaviours we wanted to add a lot
of the implementation was a lot quicker and easier if
w e didn’t im plem ent them as individualfunction
calls but rather three or four lines of code which Follow Flame
were placed above the existing function based
behaviours. These were cases where we wanted to
over ride all other behaviours which, we
im plem ented using an “if … else … ” m ethodology
improving the response times for these actions, Close enough to
Y Turn fan on
which was imperative to their functionality. extinguish?

We ended up using five separate behaviours

however there were cases where a higher level
behaviour “escape” w ould disable a low er levelone
“search for flam e.” This w as because the “search for Avoid obstacles
flam e” behaviour w as tim er-based rather than event
-based; this meant that it was possible for escape to
be interrupted, which would have produced un-
desirable results.
Escape dead ends

Set Motor Speeds

19 - Search for flame

Timer based triggering ever 10 seconds.

This behaviour would perform a turn of 360 degrees looking for an input from the flame detector saying that a flame was in
front of the vehicle. Once found the behaviour would exit allowing for a controlled approach to the flame.


Last seen
Behaviour active? N flame over 10 N
seconds ago?


Behaviour timed out?

(360 degrees turned)

Look for flame

Found flame? Y Turn fan on

Set motor speeds Deactivate

to incite an behaviour
on-the-spot turn


20 - Extinguish flame

Triggered from turning on the fan, which occurs in the follow flame behaviour.

This would turn the robot to the left for a set amount of time; it would then turn right for twice as long before turning back
left, meaning that over all, the robot would end up pointing where it started from.

Once completed the fan was turned off and the behaviour exited.


Behaviour active?
(is fan on?)

Sequence complete? Turn fan off

(Timer > 4t) / end behaviour

Set motor speeds

to incite a
Phase 1?
Y on-the-spot
(Timer < t)

Set motor speeds

Phase 2? to incite a
(Timer < 3t) on-the-spot
clockwise turn

N (Timer < 4t)

Set motor speeds

to incite a


21 - Escape

The aim of the escape behaviour is to prevent the robot from colliding with obstacles when avoid fails.

Escape works by taking the distances from both sensors; if one is under a safety threshold, the behaviour takes over. First it
reverses the robot for a short period of time; it then turns slightly less than 90 degrees away from the sensor which was
closest (an object on the right gets too close, the robot will turn left)

Ifthis behaviour becom es active it w illprevent the “Search for flam e” behaviour from activating for another 5 seconds.


Set escape
Behaviour active? N Left sensor too close? Y
direction = right


Search for flame

Set escape
cannot activate Right sensor too close? Y
direction = left
within 5 seconds

Y Activate behaviour
(Timer < tr)

Set motors to Behaviour timed out? Deactivate

reverse (Timer > te) behaviour

Turn on-the-spot
in escape direction


22 - Avoid

This behaviour is the most active of all five. Its job is to steer the robot away from obstacles before they become an issue.

By taking the difference between the sensor readings a value for how much the robot should turn can be discovered. This is
then used to set one of the motors (left or right depending on turn direction) to a velocity between 100% and –100%. As
the difference between sensors becomes greater the turning radius of the robot decreases to a stage where it could turn in
its own space (however escape generally triggers before this occurs). By using the difference in sensor ranges it means that
if there are two walls to the sides of the robot it will remain central, however due to the physical layout of our sensors it
has the downside of guiding the robot into corners remarkably well.


turn = difference
between left and
right sensors

Is turn big enough to

warrant turning?

Given turn, find

the relative
speeds for the

Soft set the motor

speeds (might be
over ridden by
other behavours)


23 - Follow Flame

This behaviour will guide the robot to a flame so it can be extinguished.

Due to the fact that our flame detector could only give a single output as to whether there was a flame in front of it or not
this task became more difficult.

To track the flame we needed to know where it was in front of the robot, so to do this we made a scan like motion,
whereby the robot would see a flame, turn away from it for a given time after it last saw the flame, then reverse the scan,
seeing the flame again and continue to turn for a given amount of time after the flame dropped out of view, then turned
back, and so on.

The sensor did perform (although very inaccurately) the function of reporting the distance to the flame. From this we were
able to say we are close enough to the flame and put it out, which we did by turning on the fan (which then triggered the
“Extinguish flam e” behaviour.)


Flame stronger
Store this value as
Flame visible Y than strongest recently Y
strongest seen
seen flame?


Reset turn timeout


Behaviour Reset turn timeout

active? (flame seen Y Turn timed out? Y timer and reverse
within timer) turn direction.


Soft set motors to

turn while
continuing to
move forward

24 - Coding

The coding of the control system turned out to be much easier than deciding on how behaviours would interact with each
other and react to input stimuli. Once we had decided on how each would work, coding the behaviours was relatively
simple in terms of programming techniques required.

Keeping the code in a logical, modular form made it easy for us to revise the interaction between behaviours while not
having to play around with the interfacing between the control software and hardware.

Toward the end of the programming stage we discovered that there were some behaviours which did not warrant having
their own functions. For these we simply implemented above the lower priority behaviours, which we prevented from
triggering using if… else… statem ents.

4 - Testing
4.1 - Initial testing

The programming of the control system was a continuous process; this involved implementing a new component, as few
w ere introduced at a tim e as possible.O ften w e w ould find that the new com ponent w ouldn’t act as expected.This w ould
lead to the need to comment out the new control code and go though it line by line, making sure that it was not causing
the problem.

Along with the testing of new components we needed to test individual behaviours. Due to the nature of a behaviour based
system it was relatively easy to comment out existing and fully functional behaviours, leaving only the one which was in
development. This made it possible for us to identify issues that we would probably have missed if trying to complete the
entire project at once.

One of the major things we found was that if a candle was too far from the robot to be extinguished yet the UVTron could
still see it the robot would continue to attempt to put it out. To solve this we added a maximum number of times the fan
could be turned on without having a break of some time in between. This meant that if the robot attempted to put out the
same flame more than four times the fan behaviour would be disabled; this in turn would allow follow flame to take over
and bring the robot closer, until the time when the extinguishing behaviour was re-enabled.

4.2 - Fine Tuning

O nce w e had each ofthe behaviours ‘w orking’it w as clear that im provem ents could be m ade.Things that w e changed in
the fine tuning stage were along the lines of, escape triggering too early, how far the find flame behaviour would turn
before coming back, what is a reasonable time to expect a candle to be blown out.

Fine tuning was one of the longest processes we went though on the robot and we would probably still be doing it if we
had not had a deadline placed upon us. We tested our robot so extensively that we destroyed the gear box on one of the
drive motors though overuse.

4.3 - Improvements

We discovered that our robot had problems navigating past the end of an object while there was still an object on the
other side.This w as caused by the sensor ofone side no longer being able to see the object and the other side’s sensor
having a short distance;given our avoid function’s m ethodology this w ould cause the robot to turn.W e did find a quick fix
to this,by saying just because you can’t see it now doesn’t m ean it isn’t stillthere - in other words unless the sensor on one
side became closer than the last seen on the other side no turn would occur. While this worked in most cases there were
some where it was unsatisfactory.

Given more time we would have liked to come up with a new method of navigating the ends of obstacles, and once we had
achieved this another problem, which to this stage has gone unnoticed would become apparent.

5 - Problems Encountered

5.1 - Drive Motors

There were numerous problems with the motor and gearbox packages we used for the Fire-Fighting Robot. The motors
provided sufficient driving torque and speed but where our problems started was attaching the motors to the wheels. The
motor shaft was of 5mm diameter and needed to be attached to a plastic wheels. We could not drill the shaft and insert a
grub screw so we opted to glue the motor shafts to the wheels. This did not work as we were getting an amount of slipping,
at the wheels, as the robot was in operation. We consulted the workshop staff and produced some aluminium adapters to
connect the wheels to the motors. This eliminated the problem of the motors slipping on the shaft.

We also found that two of our motor gearboxes wore out after a long period of testing. These motor and gearbox packages
were replaced and seemed to work as required. The method we used of connecting our motors to our chassis allowed us to
easily interchange motors should a problem occur. We have not identified any reasons for the gearbox failure to date.

5.2 - Orientation of Development Board and Bracket

Initially we planned to have our two circuit boards (Development and Vero) side by side on the top level. We then decided
to have one on top of the other. We made a bracket to rest the development board on but when assembling the two
realised that our ribbing cable was oriented the wrong way. To overcome this we needed to swap some of the pins
underneath and solder different connection wires. We arranged the two boards in this manner to give an aesthetically
pleasing look to the robot.

5.3 - Sensor Connections

Due to the extensive testing of our sensors we found the four wires to each sensor were touching and subsequently the
sensor was not working as required. In order to overcome this we needed to separate each wire by electrical tape. To hold
the wires in position it was identified that we need to hot glue the four wires into each sensor to prevent them moving
whilst the robot is in operating mode. This worked very well and no further problems were encountered with the sensor

5.4 - Fan and Motor Bush

We purchased a fan and a high speed motor (9000RPM) from a local model shop. We found that the diameter of the fan
hole was too large for the motor shaft. Initially we glued the fan to the shaft but this seemed not to work and the fan was
slipping on the motor. We then asked the workshop to make an adapter shaft with a press fit which was slotted in between
the motor shaft and the fan hole. This worked very well and upon Johan breaking one fan we had a replacement fan which
we could use.

5.5 - Last Minute Hiccup

On the day of the assessment our robot was fully functional but we continued to make minor adjustments to our code to
fine tune motor speeds and the like to suit new batteries etc. A quarter of an hour out from the official start time of the
assessment we accidentally plugged in one of our connectors incorrectly, resulting in a ground line to the UVTron to be
supplied with 18V, and its corresponding supply line hanging. After thorough of testing and probing with the DMM and
oscilloscope and after sw apping the U VTron w ith another group’s,w e confirm ed that our U VTron w as stillfully operational.
Further testing showed one of the external interrupt ports on the M16 was drawing around 150mA, which was clearly too
much current. We concluded that the 18V that was supplied to the ground line had affected the M16, through the UVTron.
We could have modified our code to use a different port, but another group that was using the same M16 controller
allowed us to borrow their controller and re-program it with our code (thanks Warren and group Shortcircuit).

6 - Conclusions

6.1 - Conclusions

The rounded chassis combined with the centrally located wheels worked extremely well for the robot and its ability to
navigate the world in which it was placed. We encountered no problems using skids to provide support for the front and
back of the robot.

After deciding to use a fan to extinguish the flame and testing its performance we were extremely happy with our choice, in
fact our successes prompted other teams to abandon their original preconceptions to adopt our method.

After seeing the trouble other teams had with circuit design we were most pleased that from the start we chose to use
keyed connecters as opposed to hard wiring external devices.

Our use of crossSense® worked extremely well for large oncoming objects yet had caused problems when objects were to
the side, and had just been navigated past. It was able to detect the sharp or continuous upcoming obstacles so long as
they had a reasonable depth.

The UVTron created some difficulty in that it was not originally direction sensitive, and thus required the addition of a
custom designed shell. It was extremely reliable once we had completed this physical modification.

Using an M16 developer board to control our fire fighting robot made debugging a lot easier due to an on board LCD unit.
Although programming the M16 using the supplied programming solution was slow and tedious, the micro itself was
reliable and presented no problems until a port was overloaded due to human error.

The control system we used was by far the most complicated part of our project; the behaviour control was a good choice
to make, as it managed to simplify the process substantially. A major part of our control was using pulse width modulation
to control the speeds of our drive motors; this was successful however it caused problems with the stalling point of the
motors as the battery voltage dropped off.

6.2 - Personal Conclusions

6.2.1 - Ben Langley

I felt that the Fire-Fighting robot project was a very appropriate project to complete as it
combined our knowledge of the past 3 1/2 years into one project. We had covered all the
areas needed to build this robot, and completing this project put these knowledge areas
into practice. This project could not have been completed individually in the time frame
given and working as a group, which worked very well, simulated the group environment in
which a project like this would be completed in industry.

We have completed the task as required, building a Fire-Fighting robot, but for the amount
oftim e and effort put into the project Ifeelit should have a higher w eighting in the paper’s
assessment. There was a huge effort put into this project from myself and my team
members, which sometimes compromised other assessments and was only worth 40% of
one paper. To complete this project it required planning and designs for the robot to be
started immediately after receiving the project. I feel part of the success of our robot was
put down to an early starting date and the large amount of time we scheduled to work on
the robot in the lab. Another key to our success was allocating different tasks to each group
member so we could be working on many aspects of the project at one time.

My involvement in the Fire-Fighting robot was of a substantial amount. My duties included, but not limited to, designing
and constructing a chassis for our robot, which also included adding a second level and adding skids to the front and back
for support when in operation. I also was in charge of fitting and assembling the drive train, constructing brackets for the
sensors and circuit boards, and providing a mounting bracket for the fan to extinguish the flame. I was in charge of liaising

with the workshop to have various parts manufactured for the Fire-Fighting robot. I was also required for assembly and
disassem bly ofthe robot and any alterations m ade to im prove the robot’s structure.Additionalto the construction Iw as
required to source and supply the material (aluminium sheet) and purchase many of the items used in the robot from local

Lastly I found this project very challenging and at the same time enjoyable and rewarding as our robot operated as required
on completion of the project. This project has given me experience in working with a team and having to complete a
project within a given timeframe. From this project I have learnt how we can bring all the different areas of engineering
together (such as mechanical, electrical, electronic and software) and apply them to a real life project.

6.2.2 - Matthew Playne

When we were first given the outline for this project I remember being very excited about
being able to work on a more substantial project than we had previously done (this project
being more of a design project than our other less substantial projects in the past which
had tended to focus on only one aspect of our learning).

Having worked on several major projects during my summer work period this year I was
well aware of the time that would be involved in developing the project to completion. I
was also aware, as were the rest of the team, that the design and prototyping stage of the
project would be just as important, if not more, than the actual construction phase. For this
reason we spent a number of weeks evaluating the different options that we could pursue.

As all the members in our team have different skills and abilities we were able to effectively
distribute different responsibilities that took advantage of the skills of each person. As I had
done a lot of electronics design and programming work as a Development Engineer at Elec-
tronic Partners Limited I was chosen to work on the electronics and hardware drivers for
the robot. In addition to this I was responsible for working with Courtney to ensure that the high and low level software
worked well together. I also provided input regarding the other aspects of the robot design.

It was fun to be able to put some of my work experience to use in a university environment. I spent a few hours over the
holidays at home putting the circuit together. Once I had got the board working I was able to start work on the hardware
drivers. I came across several issues during this process (which are outlined in previous sections). I was pleased that I was
able to resolve these issues relatively quickly. I feel that all of the practice I have had in this sort of work has been greatly

I had fun working with the other members in my team on this project. We are all good friends and have worked on a lot of
projects together.This m akes for an enjoyable and relaxed w ork environm ent,and as w e are already aw are ofeach others’
working style and our strengths and weaknesses we are able to support and help each other more effectively.

I think that this project has taught all of us a lot about working on a project such as this which combines many different
technological and design aspects of our learning. Overall I think that we implemented the project well; we had a lot less
issues during the project development than I was expecting. I feel that this was mostly due to the large amount of time that
we spent in the design phase of the project.

I am quite proud of the fact that we were able to successfully implement the crossSense design in the final product. This
concept was designed by Courtney and although I was initially unsure of how well the system would work I was soon con-
vinced as to its benefits and I enjoyed implementing this system and seeing it develop to completion. Although not perfect
this system works well, and I feel that it has been a valuable research aspect to this project.

I am also pleased that many of the designs that we implemented on our robot were later adopted by some of the other
teams after seeing our success. Several of the other teams switched to a fan-based extinguishing method after seeing how
successful our implementation was. I consider this to mean that we were at the top of the field with regards to research
and design, and as is the case with any project, being at the top of the field is the ultimate goal.

I have very much enjoyed every aspect of this project (even putting together this report) and have greatly appreciated the
opportunity to work on this project and work with all of the people that I have. I would like to thank everyone involved in

this project, both my team mates and all of the Massey University staff involved.

6.2.3 - Courtney de Lautour

The firefighting robot was the first major, open ended, project we have had to complete
while at university. While we had to make a line follower in first year the complexity of that
task was minor, however what we had seen helped in the decision making on how the ro-
bot should move around its world.

To begin with I had envisioned many complicated and impractical design approaches.
These included a range sensor rotating on a platform on the robot which would build a
precise model of the environment and thus path finding algorithms could have been imple-
mented. However throughout the process it became obvious that this was extremely diffi-
cult to achieve in our time frame, along with being un-required.

The robot was designed to be able to turn within its own radius from the beginning; this
m ade the system m uch sim pler,as w e could turn the robot know ing that it w ouldn’t hit
anything in the process.W e also knew that the sm aller the robot’s footprint the easier con-
trol would be. To achieve this we envisioned using a number of tiers. In the end we used
three; one for the motors, batteries and obstacle sensors, the second tier for the flame
sensor, mounting for the extinguishing fan, and the electronic interface board. The last tier was constructed differently
from the other two, given that it was only required to hold the microcontroller developer board.

One of the design ideas we had from the start was to use two sensors physically placed to create crossing fields of view.
This meant that if the robot approached a sharp point directly, one of the sensors would be able to see it and an appropri-
ate action could be taken, whereas if we had the sensors pointing outwards neither would have seen the approaching ob-
ject. This allowed us to use fewer sensors and have a much safer system.

Before we could make the robot do anything intelligent we needed to interface the external components to the micro con-
troller. This was made easier by using a pre-built developer board. However it was still required that we build a circuit
board containing H-bridges, voltage regulators, smoothing capacitors, and a transistor to drive the fan. The interfacing of
the microcontroller to this board was mainly a software task; it required deciding on which ports to use for what functions
and what to do with each bit of the chosen ports.

Once we had interfaced the hardware we needed to construct the control system. This is essentially where the robot be-
came unique from the others. Designing and building this was the longest part of the project. From the design brief we
were coming up with basic ideas on how to implement the functionality we would require. However by the time the robot
was ready to have any form implementation we were already halfway though allocated time; we were working on creating
and fine tuning the control system right up until the time where the robot was finally displayed.

Deciding on behavior based control was one of the most important decisions we made. This meant that the system would
be reactive, rather than requiring a model of the world to make decisions, which made the system far simpler. There were
certain tasks we wanted the robot to perform which did not require any input from the sensors; to perform these we trig-
gered the behavior from a timer, rather than something like a range sensor getting too low.

Overall I found the project to be enjoyable and I learnt a lot about a variety of Mechatronics principles. I felt that the robot
performed well in the final demonstration, however if given more time there are things I would have liked to improve
upon, as is the case with any project.

6.2.4 - Daniel Mills

My primary role in the team was to work along side Ben to design and produce the chassis and other mechanical aspects of
our fire fighting robot. The over-all physical design was produced mainly by Ben and myself, however, as was the case with
other aspects of the robot, there were certainly contributions from the rest of the team. I feel that on the whole we worked
effectively as a team, each member playing to their strengths and everyone contributing to all aspects of the project at one
point or another.

Points of Mention:

 From the start we decided on making the chassis circular with fully enclosed internal wheels, to provide the best
turning circle with the least external interference.

 I proposed using plastic skids as opposed to using a jockey-wheel of types to stabilize the robot from front to back rock.
We ended up going with this idea and it worked very successfully. The skids were produced with a combined effort
between Raymond, Ben and myself.

 It became apparent once we had all the circuitry available to us that the motors, batteries, circuit boards, switches, fan
etc were not all going to fit on the single lower base plate/chassis. An upper tier was produced to hold all three circuit
boards and the fan assembly. Originally Ben and I decided to separate the upper and
lower tiers with aluminium round bar and mount the IR Laser sensors on separate
brackets, mounted to either the upper or lower tier. On revision we decided to
incorporate both the tier spacer and the IR Laser sensor mounting bracket into one

 I spent some time thinking about how to mount the fan and motor assembly and in the
end, two concepts were produced both of similar design, with slight differences. We
used a strip ofalum inium sheet m etalfor this bracket,Iused a ham m er’s head as a
Dolly to shape the bracket, as it has almost identical diameter as the fan motor.

 I was responsible for modelling the robot through SolidWorks. All of the components
are drawn accurately and to a 1:1 scale. The full model assembly contains around 40
part files.

7 - References

Acroname Easier Robotics. (2004). The Hamamatsu UVTron Flame Detector Package. [Brochure]. Richards, S: Author.

Acroname Easier Robotics. (2004). The Sharp GP2D02 and GP2D05 infrared Object Detectors. [Brochure]. Richards, S:

Paper 143.472 Industrial Systems Design and Integration (2006). Fire-Fighting Robot. [Brochure]. Xu, W.L: Author.

Renasas (2006). M16C62P Group Single Chip 16-Bit Microcomputer. Retrieved March 12, 2006 from the World Wide Web:

8 - Appendices

8.1 - Appendix A - Multi-Level Costed Bill of Materials

Level Part Number Description Type Count Part Cost Unit Cost
0 FFR Fire Fighting Robot Manufactured 1 $338.76 $338.76
1 R67-UVTRON Hamamatsu UVTRON Flame Detector Purchased 1 $116 116
1 FFR-DB FFR Support Board Manufactured 1 $41.17 41.165
2 HM3412 2 Pin 0.1 Straight Locking Header Purchased 6 $0.12 0.72
2 HM3414 4 Pin 0.1 Straight Locking Header Purchased 3 $0.22 0.66
2 HP9552 Universal Pre-Punched Experimenters Board Purchased 1 $6.70 6.7
2 WW4346 Blue Wire Wrap Wire on Spool Purchased 0.3 $16.75 5.025
2 HH8514 TO-220 Heatsink Purchased 2 $1.45 2.9
2 RE6326 Capacitor Electrolytic 470uF 25V Purchased 3 $0.75 2.25
2 RM7125 100nF 100V MKT Capacitor Purchased 5 $0.36 1.8
2 FFR-HS FFR Heatsink Manufactured 1 $0.00 0
3 FFR-AL 3mm Plate Aluminum Purchased 1 $0.00 0
2 PI6456 16Pin Gold Insert Machined Pin IC Socket Purchased 3 $2.20 6.6
2 ZC4093 4093 Quad 2-Input NAND CMOS IC Purchased 1 $1.10 1.1
2 Z6845 SN754410 Quad Half H Driver Purchased 2 $4.98 9.96
2 ZV1512 7812 +12V 1A Voltage Regulator Purchased 1 $1.95 1.95
2 ZV1505 7805 +5V 1A Voltage Regulator Purchased 1 $1.50 1.5
1 FFR-MB FFR Main Controller Board Manufactured 1 $3.65 3.65
2 PP1116 50 Pin IDC Vertical Header Purchased 1 $3.65 3.65
2 SKP16C62P Renesas M16C 62P Developer Board Purchased 1 $0.00 0
1 FFR-CH FFR Chassis Manufactured 1 $15.52 15.52
2 HM3412 2 Pin 0.1 Straight Locking header 2.54 Pitch Purchased 1 $0.12 0.12
2 ST0572 DPDT Standard Toggle Switch Purchased 1 $2.70 2.7
2 ST0578 Missile Switch Protective Cover Purchased 1 $7.50 7.5
2 HM3402 2 Pin Header With Crimp Pins Purchased 2 $0.60 1.2
2 FFR-CHMC FFR Main Chassis Component Manufactured 2 $0.00 0
3 FFR-AL 3mm Plate Aluminum Purchased 1 $0.00 0
2 FFR-CHB FFR Chassis Bracket Manufactured 3 $0.00 0
3 FFR-AL 3mm Plate Aluminum Purchased 1 $0.00 0
2 FFR-FS1 FFR M3 Fastner Purchased 18 $0.00 0
2 FFR-FS2 FFR M4 Fastner Purchased 10 $0.00 0
2 FFR-MBR FFR Motor Bracket 20mm Purchased 4 $1.00 4
2 FFR-SKD FFR Ground Skid Manufactured 2 $0.00 0
2 FFR-NYL FFR CNC Nylon Purchased 1 $0.00 0
2 FFR-PB FFR PCB Bracket Manufactured 1 $0.00 0
3 FFR-AL 3mm Plate Aluminum Purchased 1 $0.00 0
1 R19-IR02 Sharp GP2D02 IR Laser Range Finder Purchased 3 $27.00 81
1 FFR-EXT FFR Extinguishing Unit Manufactured 1 $13.95 13.95
2 YM2716 12V 8100 RPM DC Electric Motor Purchased 1 $11.95 11.95

8.1 - Appendix A - Multi-Level Costed Bill of Materials - Continued

2 PROP1 130mm Propellor Blade Purchased 1 $2 2

2 FFR-BUSH1 FFR Aluminum Bush Purchased 1 $0 0
2 FFR-EXB FFR Extingushing Unit Bracket Manufactured 1 $0.00 0
3 FFR-AL 3mm Plate Aluminum Purchased 1 $0.00 0
3 FFR-FS1 FFR M3 Fastner Purchased 1 $0.00 0
1 YG2732 12V DC Reversible Gearhead Motor 70 RPM Purchased 2 $15.95 31.9
1 TAM 53089 Tamiya White Wheels Dish Type Purchased 2 $0.00 0
1 FFR-HUB FFR Drive Wheel Hub Purchased 2 $0.00 0
1 FFR-BAT FFR Battery Pack Manufactured 1 $3.74 3.74
2 PH9209 8 X AA 2 Rows of 4 Square Battery Holder Purchased 1 $2.25 2.25
2 WM4516 Rainbow Cable 16 Core Purcahsed 0.01 $4.00 0.04
2 PH9200 4 X AA Square Battery Holder Purchased 1 $1.45 1.45
1 FFR-SH FFR UVTRON Directional Shield Manufactured 1 $0.01 0.01
2 FFR-AL 3mm Plate Aluminum Purchased 1 $0.00 0
2 MISC-HS Misc. Heatshrink Purchased 1 $0.01 0.01
1 FFR-BAT FFR AA Battery Purchased 12 $0.32 3.84
1 H1861 Insulated Spacer 10mm 5pk Purchased 2 $6.88 13.76
1 FFR-CB1 FFR 2 Pin Cable Connector Manufactured 2 $1.25 2.5
2 WM4516 Rainbow Cable 16 Core Purchased 0.01 $4.00 0.04
2 MISC-HS Misc. Heatshrink Purchased 1 $0.01 0.01
2 HM3402 2 Pin Header With Crimp Pins Purchased 2 $0.60 1.2
1 FFR-CB2 FFR 4 Pin Cable Connector Manufactured 2 $0.81 1.62
2 FFR-WR1 FFR Thin Wire Purchased 4 $0.00 0
2 HM3404 4 Pin Header With Crimp Pins Purchased 1 $0.80 0.8
2 MISC-HS Misc. Heatshrink Purchased 1 $0.01 0.01
1 FFR-CB3 FFR 2 Pin Cable Connector 1 Ended Manufactured 4 $0.65 2.6
2 WM4516 Rainbow Cable 16 Core Purchased 0.01 $4.00 0.04
2 HM3402 2 Pin Header With Crimp Pins Purchased 1 $0.60 0.6
2 MISC-HS Misc. Heatshrink Purchased 1 $0.01 0.01
1 FFR-CB4 FFR 50 Pin IDC Cable Manufactured 1 $7.50 7.5
2 WM4508 50 Way IDC Ribbon Cable Purchased 0.2 $6.50 1.3
2 PS0990 50 Way IDC Line Socket Purchased 2 $3.10 6.2

Please note that datasheets for the main components of the robot are included in the following appendices.

8.2 - Appendix B - Sharp GP2D02 Data Sheet

8.2 - Appendix B - Sharp GP2D02 Data Sheet - Continued

8.2 - Appendix B - Sharp GP2D02 Data Sheet - Continued

8.2 - Appendix B - Sharp GP2D02 Data Sheet - Continued

8.3 - Appendix C - Renesas M16C 62P Data Sheet

For a full datasheet for the Renesas SKP16C62P Please go to: http://america.renesas.com/products/tools/

8.4 - Appendix D - UVTRON Flame Detector Bulb Data Sheet

8.4 - Appendix D - UVTRON Flame Detector Bulb Data Sheet - Continued

8.5 - Appendix E - UVTRON Flame Detector Driver Data Sheet

8.5 - Appendix E - UVTRON Flame Detector Driver Data Sheet - Continued

8.6 - Appendix F - ST Microelectronics L293D Motor Driver Data Sheet

8.6 - Appendix F - ST Microelectronics L293D Motor Driver Data Sheet - Continued

8.6 - Appendix F - ST Microelectronics L293D Motor Driver Data Sheet - Continued

8.6 - Appendix F - ST Microelectronics L293D Motor Driver Data Sheet - Continued

8.6 - Appendix F - ST Microelectronics L293D Motor Driver Data Sheet - Continued

8.6 - Appendix F - ST Microelectronics L293D Motor Driver Data Sheet - Continued

8.6 - Appendix F - ST Microelectronics L293D Motor Driver Data Sheet - Continued

8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet

8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet - Continued

8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet - Continued

8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet - Continued

8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet - Continued

8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet - Continued

8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet - Continued

8.7 - Appendix G - Fairchild 4093 NAND CMOS Chip Data Sheet - Continued

8.8 - Appendix H - 70 RPM Drive Motor Data Sheet

8.9 - Appendix I - Fire Fighting Robot Source Code


Date: 29/05/06

Filename: FireFightingRobot.c
File Version: 2.0
Code Size: 12718 Bytes

Authors: Matthew Playne (to 26/04/06 + further modifications)

Courtney de Lautour (26/04/06 to 29/05/06)

Company: Massey University Team 4

Uses: sfr62p.h

Notes: This program contains all FireFightingRobot code


#include "skp_bsp.h"
#include "skp_lcd.h"
#include "math.h"

//---------------------------Compiler Definitions---------------------------//
//Interupt vector definitions//
#pragma INTERRUPT ta0_irq
#pragma INTERRUPT int2_irq

//Defines for the distance sensors//

#define SensorLeftControl p7_4
#define SensorLeftData p7_1
#define SensorRightControl p7_0
#define SensorRightData p7_3
#define SensorRearControl p7_7
#define SensorRearData p7_5

//---------------------------Function Declarations---------------------------//

void ta0_irq(void);
void int2_irq(void);
void mcu_init(void);
char * IntToAsciiDec(char * dest_string,int min_digits,unsigned int value);

//Control Function Declarations//

void FollowFlame (void);
void Escape (void);
void Avoid(void);
void SetMotors (void);

//Range Sensor Function Declarations//

void GetDistance(void);
void ShuffleDistance (void);
void CleanDistance (void);
void AverageDistance (void);
int AverageHelper (int n);
void ModifyMinDistance (void);
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

//Flame Sensor Functions//

void GetFlame (void);
void AverageFlame (void);

//Motor Drivers Function Declarations//

void InitializeMotors(void);
unsigned int SetMotorLeft(unsigned int PWMValue, char Direction);
unsigned int SetMotorRight(unsigned int PWMValue, char Direction);

//Fan Drivers Funtion Declarations//

void FanOn(void);
void FanOff(void);
//---------------------------Variable Declarations---------------------------//

//Control Variables//
const U8 MaxDistance = 30;
const U8 Threshold = 14;
const U8 TurnTimeout = 300;
const U8 Samples = 3;
const U16 FanOnTime = 6000;
unsigned long WithoutFlameTimer = 0;
U8 FanOnCount = 0;
U16 FanOffTime = 0;
unsigned long FlameTicks = 0;
U16 MaxFlame = 0; // Lower = stronger flame (eh? :P)
U8 FoundFlame = 0;
U8 FlameDirection = 1; // 1 = left : 2 = right
U16 FlameStr[6]; // Average the flame Str
const U8 FlameSamples = 5;
U16 flameTurnTimeout;
U8 flameSearch = 0;
U16 flameSearchTimer = 0;
U8 Escaping = 0;
U8 EscapeDirection = 1;
U16 EscapeTicks = 0;
float mScale;
float LeftSpeed;
float RightSpeed;

//ta0_irq Global Variables//

U16 timer_02ms = 0; //incremented every 0.2 ms (reset every 100ms)
U16 timer_100ms = 0; //This value will be incremented every 100 ms

//LCD Global Variables//

char lcd_text[8];

//GetDistance Global Variables//

U8 DistanceLeft[4]; //'cm' value last returned from the left IR range sensor
U8 DistanceRight[4]; //'cm' value last returned from the right IR range sensor
U8 DistanceRear[4]; //'cm' value last returned from the rear IR range sensor
U8 MinLeft;
U16 MinLeftTimer;
U8 MinRight;
U16 MinRightTimer;
U8 MinRear;
U16 MinRearTimer;
unsigned long FanActive;
U8 flame = 0;
U16 noflame = 0;
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

U16 wombat = 0;
U16 lastpulse = 9999;
U16 flameTimer = 0;
U16 oldtimer = 0;

//---------------------------Function Definitions---------------------------//

void main(void){
U16 old = 0;
U16 power = 0;
U8 i;

while(1) { // Main Loop
LeftSpeed = 254;
RightSpeed = 254;
if ((WithoutFlameTimer > 50000) && (FanActive == 0)){
LeftSpeed = -200;
RightSpeed = 200;
if (WithoutFlameTimer > 72000){
WithoutFlameTimer = 0;
GetFlame ();
}else {
if (FanOffTime > 12000){
FanOnCount = 0;
if (FanActive){
if (FanActive > FanOnTime){
FanOff ();
FanOnCount ++;
if (FanActive < (.25 * FanOnTime)){
LeftSpeed = 200;
RightSpeed = -200;
}else if (FanActive < (.75 * FanOnTime)){
LeftSpeed = -200;
RightSpeed = 200;
}else if (FanActive < FanOnTime){
LeftSpeed = 200;
RightSpeed = -200;
ModifyMinDistance ();
GetFlame ();
mScale = ((((DistanceLeft[0] - 8) / (MaxDistance - 8)) +
((DistanceRight[0] - 8) / (MaxDistance - 8))) * 32) + 127 + 64;
if ((DistanceLeft[0] > 40) || (DistanceRight[0] > 40))
mScale = 254;
FollowFlame ();
Avoid (); // Keep away from walls etc.
Escape ();
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

SetMotors ();

//***********END OF MAIN*************//

void int2_irq(void){
lastpulse = flameTimer;
flameTimer = 0;

void FollowFlame (void){

int flameStr = FlameStr[0];

if ((flameStr < 4000)&&(flameStr > 100)){

WithoutFlameTimer = 0;
if (flameStr <= (MaxFlame - 30)){
MaxFlame = flameStr;
FlameTicks = 0;
flameSearch = 0;
FanOn ();
FoundFlame = 1;
if ((FlameTicks > 1000) && (FoundFlame == 1)) { // Been turning long enough?
flameSearch = 1;
FoundFlame = 0;
FlameTicks = 0;
if (FlameDirection == 1) FlameDirection = 2;// Change Turning Direction
else FlameDirection = 1;
if ((FlameTicks < 1000)||(FoundFlame == 1)){
if (FlameDirection == 1){
LeftSpeed = 254;
RightSpeed = 200;
LeftSpeed = 200;
RightSpeed = 254;
LeftSpeed = 254;
RightSpeed = 254;
if (flameSearch == 1){
if ((flameSearchTimer < 20000)&&(flameStr >= 4000)){
LeftSpeed = 150;
RightSpeed = -150;
}else if (flameStr >= 4000){
flameSearchTimer = 0;
flameSearch = 0;
}else if (flameStr <= 3000){
LeftSpeed = 0;
RightSpeed = 0;
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

void Escape (void) {

if (Escaping != 1) {
if ((DistanceLeft[0] < Threshold) || (DistanceRight[0] < Threshold)){
Escaping = 1;
EscapeTicks = 0;
if (DistanceLeft[0] < DistanceRight[0]) EscapeDirection = 1;
else EscapeDirection = 2;
if (WithoutFlameTimer > 25000) WithoutFlameTimer = 25000;
if (EscapeTicks < 2500){
LeftSpeed = -254;
RightSpeed = -254;
}else if (EscapeTicks < 4000 + 2500){
if (EscapeDirection == 1){
LeftSpeed = -254;
RightSpeed = 254;
LeftSpeed = 254;
RightSpeed = -254;

}else if (EscapeTicks > 4000 + 2500){
Escaping = 0;
EscapeTicks = 0;

// Avoid//
// This uses infomation from the left and right sensors to calculate left and right
// motor speeds.
void Avoid (void){
float Turn;

Turn = DistanceRight[0] - DistanceLeft[0]; // positive if turning left

if ((Turn < 0) && DistanceRight[0] > MinLeft) Turn = 0;
else if ((Turn > 0) && DistanceLeft[0] > MinRight) Turn = 0;
if ((Turn < 5) && (Turn > -5)) return;
else if (Turn < -2){
LeftSpeed = 1;
RightSpeed = 1 + (Turn/15);
}else if (Turn > 2){
LeftSpeed = 1 - (Turn/15);
RightSpeed = 1;
LeftSpeed *= mScale;
RightSpeed *= mScale;

//This fuction is the interrupt request handler for TimerA0. TimerA0 is set up
//in mcu_init to trigger an interrupt every 0.2ms. The main purpose for this is
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

//to enable accurate 0.2ms measurement for communicating with the IR range
//sensors. If it is neccessary to reduce this minimum value below 0.2ms this
//is permissible, however the timer_02ms value should be maintained accurately.
//Do not add too much addtional code to this function as it will begin to impact
//on timing accuracy.
void ta0_irq(void) {

timer_02ms++; //Increment timer_0.2ms

if (FanActive){
FanActive ++;
FanOffTime = 0;
}else FanOffTime ++;
flameTimer ++;
flameTurnTimeout ++;
flameSearchTimer ++;
WithoutFlameTimer ++;
if (flameTimer > 5000){
lastpulse = 5000;
flameTimer = 5000;
if (FlameTicks < 99999) FlameTicks ++;
if(timer_02ms > 1000) { //Increment timer_100ms every 100ms
timer_02ms = 0; //Reset our 0.2ms counter every 100ms
timer_100ms++; //We actually increment the 100ms counter here
MinLeftTimer ++;
MinRightTimer ++;
MinRearTimer ++;
}else if (timer_02ms > 500){
MinLeftTimer ++;
MinRightTimer ++;
MinRearTimer ++;
if (Escaping == 1) EscapeTicks ++;

//This fuction contains the main initialization code for this program. I'm not sure
//exactly what some things do, so if you don't know it is best to leave it alone.
//There are some port setups at the end of this function, however these do not
//affect the low-level drivers. The low-level drivers initialization functions
//(and the main function in the case of the IR range sensors) ensure that the
//needed ports are correctly set up. Feel free to modify this function and add
//to it as necessary - I wouldn't advise messing with the clocks and interrupt
//stuff to much though :-)
void mcu_init(void) {
unsigned int count = 20000;

prc1 = 1; // enable access to processor mode registers

pm20 = 0; // 2 wait states for sfr access...this is
//the reset value necessary for >16Mhz
//operation, can be set to 1 wait for <=16Mhz
prc1 = 0; // disable access to processor mode registers
// configure and switch main clock to PLL at 20MHz
// and start the 32Khz crystal sub clock
prc0 = 1; // enable access to clock registers
prc2 = 1; // enable write to pacr
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

prc2 = 0; // write disable

cm1 = 0x20; // set to hi-drive Xin, divide by 1
cm0 = 0x18; // set to main clock using divide by 1, Xc
//function. Turn on 32kHz sub clock and Xc HD
cm21 = 0; // switch to Xin
plc0 = 0x11; // configure PLL to x2
plc0 = 0x91; // enable PLL
while(count > 0) count--; // wait for PLL and 32kHz clocks to stabilize
//(20mS maximum, 200,000 cycles @10Mhz) this decre
//ment with no optimization is 12 cycles each
//(20,000*12 cycles=240,000=24mS)
cm11 = 1; // switch to PLL
prc0 = 0; // disable access to clock registers

/* Switch initialization - macro defined in skp_bsp.h */


/* LED initialization - macro defined in skp_bsp.h */


/* Timer initialization */
/* Configure Timer A0 - 100ms (millisecond) counter */
ta0mr = 0x80; //Timer mode, f32, no pulse output
ta0 = 125; //0.2ms

/* Change interrupt priority levels to enable maskable interrupts */

DISABLE_IRQ // disable irqs before setting irq registers - macro de
// fined in skp_bsp.h
ta0ic = 2; // Set the timer's interrupt priority to level 2
int2ic = 1; // Set the UVTRON interrupt priority to level 1
ifsr2 = 0;
ENABLE_IRQ // enable interrupts macro defined in skp_bsp.h

/* Port Configuration */
pd7 = 0b01010101;
pd8 = 0b11100001;

/* Start timers */
ta0s = 1; // Start timer A0

//This fuction when called takes readings from the three IR range finders, converts
//the raw data obtained into a 'cm' value and loads these measurements into three
//global variables: DistanceLeft, DistanceRight, DistanceRear. This routine takes
//approximately 100ms to run, and it gathers data from all three sensors
//This fuction utilizes the TimerA0 interrupt for accurate 0.2ms timing. This timer
//should not be used for any other purpose if this function is to be used. It
//is permissible to add a small amount of additional code to the TimerA0
//interrupt handler, however this code should not take a long time to run as
//it will impact on the accuracy of this function.
void GetDistance(void) {
U16 timertemp=0;
int i;
U8 x[3];
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

float y[3];
float ctemp = 0;
float powertemp = 0;
float mtemp = 0;
const float reara = 370.3297;
const float rearb = -0.0048757;
const float rearc = 8.35316;
const float lefta = 1.567149;
const float leftb = 68.8646;
const float righta = 1.58421;
const float rightb = 71.419;

SensorLeftData = 0;
pd7_4 = 1;
SensorRightData = 0;
pd7_0 = 1;
SensorRearData = 0;
pd7_7 = 1;
x[0] = 0;
x[1] = 0;
x[2] = 0;
timer_02ms = 0;
timertemp = timer_02ms;
while (timer_02ms != timertemp+(10));
SensorLeftControl = 0;
SensorRightControl = 0;
SensorRearControl = 0;
timertemp = timer_02ms;
while(1) {
if(SensorLeftData == 1) {
if(SensorRightData == 1) {
//if(SensorRearData == 1) { //Not using rear sensor
if (timer_02ms > timertemp+(70*5)) break;
SensorLeftControl = 1;
SensorRightControl = 1;
SensorRearControl = 1;
timertemp = timer_02ms;
while (i < 7) {
while (timer_02ms != timertemp+(1));
x[0] = x[0] | (SensorLeftData & 0x01);
x[1] = x[1] | (SensorRightData & 0x01);
x[2] = x[2] | (SensorRearData & 0x01);
x[0] = x[0] << 1;
x[1] = x[1] << 1;
x[2] = x[2] << 1;
SensorLeftControl = 0;
SensorRightControl = 0;
SensorRearControl = 0;
timertemp = timer_02ms;
while (timer_02ms != timertemp+(1));
SensorLeftControl = 1;
SensorRightControl = 1;
SensorRearControl = 1;
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

timertemp = timer_02ms;
while (timer_02ms != timertemp+(1));
x[0] = x[0] | (SensorLeftData & 0x01);
x[1] = x[1] | (SensorRightData & 0x01);
x[2] = x[2] | (SensorRearData & 0x01);
x[0] = x[0] << 1;
x[1] = x[1] << 1;
x[2] = x[2] << 1;
powertemp = (rearb*x[2]);
mtemp = reara * powf(x[2],powertemp);
y[2] = mtemp + rearc;
powertemp = (leftb/x[0]);
y[0] = lefta * (powf(x[0],powertemp));
powertemp = (rightb/x[1]);
y[1] = lefta * (powf(x[1],powertemp));
ShuffleDistance ();
DistanceLeft[Samples] = y[0];
DistanceRight[Samples] = y[1];
DistanceRear[Samples] = y[2];
CleanDistance ();
AverageDistance ();

// CleanDistance
// This sets any distance readings which are greater than the max distance to use
// the set max distance.
void CleanDistance (void){

DistanceRight[Samples] -= 7;
if ((DistanceLeft[Samples] > MaxDistance)||(DistanceLeft[Samples] < 8)) Dis-
tanceLeft[Samples] = MaxDistance;
else DistanceLeft[Samples] -= 7;
if ((DistanceRight[Samples] > MaxDistance)||(DistanceRight[Samples] < 8))
DistanceRight[Samples] = MaxDistance;
else DistanceRight[Samples] -= 7;
if((DistanceRear[Samples] > MaxDistance)||(DistanceRear[Samples] < 8)) Dis-
tanceRear[Samples] = MaxDistance;

void AverageDistance (void){

int Max, Min, MaxPos, MinPos, Total, i, weight;

Max = 0;
Min = 50;
Total = 0;
for (i = 1, weight=1; i <= Samples; i ++,weight++){
if (DistanceLeft[i] > Max){
Max = DistanceLeft[i];
MaxPos = i;
if (DistanceLeft[i] < Min){
Min = DistanceLeft[i];
MinPos = i;
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

Total += DistanceLeft[i]*weight;
DistanceLeft[0] = Total / AverageHelper(Samples);
Max = 0;
Min = 50;
Total = 0;
for (i = 1, weight=1; i <= Samples; i ++,weight++){
if (DistanceRight[i] > Max){
Max = DistanceRight[i];
MaxPos = i;
if (DistanceLeft[i] < Min){
Min = DistanceRight[i];
MinPos = i;
Total += DistanceRight[i]*weight;
DistanceRight[0] = Total / AverageHelper(Samples);
Max = 0;
Min = 50;
Total = 0;
for (i = 1; i <= Samples; i ++){
if (DistanceRear[i] > Max)
Max = DistanceRear[i];
if (DistanceRear[i] < Min)
Min = DistanceRear[i];
Total += DistanceRear[i];
Total -= (Min + Max);
DistanceRear[0] = Total / AverageHelper(Samples);

int AverageHelper (int n){

int i;
int rtn = 0;

for (i = 1; i <= n;i++){

rtn += i;
return rtn;

void ShuffleDistance (void){

int i;

for (i = 1; i < Samples; i ++){

DistanceLeft[i] = DistanceLeft[i + 1];
DistanceRight[i] = DistanceRight[i + 1];
DistanceRear[i] = DistanceRear[i + 1];

void ModifyMinDistance (void){

if (MinLeft > DistanceLeft[0]){

MinLeft = DistanceLeft[0];
MinLeftTimer = 0;
}else if (MinLeftTimer > TurnTimeout){
MinLeft = DistanceLeft[0];
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

if (MinRight > DistanceRight[0]){
MinRight = DistanceRight[0];
MinRightTimer = 0;
}else if (MinRightTimer > TurnTimeout){
MinRight = DistanceRight[0];

void GetFlame (void){

int i;

for (i = 1; i < FlameSamples; i ++) FlameStr[i] = FlameStr[i + 1];

FlameStr[0] = lastpulse;
if ((FlameStr[0] > 100) && (FlameStr[0] < 4000)){
WithoutFlameTimer = 0;
FollowFlame ();
FanOn ();

void AverageFlame (void){

int Max = 0, Min = 5000;

int MaxPos, MinPos;
long int Total;
int i , weight;

Max = 0;
Min = 5000;
Total = 0;

for (i = 1, weight=1; i <= FlameSamples; i ++,weight++){

if (FlameStr[i] > Max){
Max = FlameStr[i];
MaxPos = i;
if (FlameStr[i] < Min){
Min = FlameStr[i];
MinPos = i;
Total += FlameStr[i]*weight;
FlameStr[0] = Total / AverageHelper(FlameSamples);

//This fuction initializes the MCU for PWM control of the drive motors.
//Timers A1 and A3 are used for PWM control of the right and left motors
//respectively. In addition to this the control ports: p7_6, p7_2, p6_3 and
//p6_2 are configured.
//This fuction utilizes TimerA3 and TimerA1, these should not be used by any other
//portions of any program this function is included in.
void InitializeMotors(void) {
ta3mr = 0b10100111; //Configure Timers A3 and A1 for 8bit PWM
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

ta1mr = 0b10100111; //
ta3 = 0x00; //Set the initial PWM values to 0
ta1 = 0x00; //
DISABLE_IRQ //Disable interrupts
ta3ic |= 0x00; //Set Timers A3 and A1 interupt settings
ta1ic |= 0x00; //
ENABLE_IRQ //Enable interrupts

ta3s = 1; //Start Timers A3 and A1

ta1s = 1; //
pd7 = pd7 | 0x44; //Set PWM output ports to output (p7_6 and
pd8 = pd8 | 0x0C; //Set motor direction control ports to
//output (p8_3 and p8_2)
p7 = p7 & 0xBB; //Set p7_6 and p7_2 to 0 (everything else as
p8 = p8 | 0x0C; //Set p8_3 and p8_2 to 1 (everything else as

//This fuction sets the direction and power percentage to the left
//motor. The power percentage is specified as a U16 with value ranging
//from 0 (completely off) to 254 (max power). The function will return
//an error (0xFFFE) if a value is passed to it outside of this range.
//The direction of motor rotation is specified by a char Direction. This
//value can be either ('f' or 'F' - forward) or ('r' or 'R' - reverse). If
//any other value is passed to the function it will return an error (0xFFFF).
//If the function is successful it will return the original power percentage
//value passed to it.
//This fuction utilizes TimerA3, TimerA3 should not be used by any other
//portions of any program this function is included in.
unsigned int SetMotorLeft(unsigned int PWMValue, char Direction) {
if(PWMValue > 254) return 0xFFFE;
if((Direction == 'f') || (Direction == 'F')) p8_2 = 0;
else if((Direction == 'r') || (Direction == 'R')) p8_2 = 1;
else return 0xFFFF;
ta3 = (PWMValue) << 8;
return PWMValue;

//This fuction sets the direction and power percentage to the left
//motor. The power percentage is specified as a U16 with value ranging
//from 0 (completely off) to 254 (max power). The function will return
//an error (0xFFFE) if a value is passed to it outside of this range.
//The direction of motor rotation is specified by a char Direction. This
//value can be either ('f' or 'F' - forward) or ('r' or 'R' - reverse). If
//any other value is passed to the function it will return an error (0xFFFF).
//If the function is successful it will return the original power percentage
//value passed to it.
//This fuction utilizes TimerA1, TimerA1 should not be used by any other
//portions of any program this function is included in.
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

unsigned int SetMotorRight(unsigned int PWMValue, char Direction) {
if(PWMValue > 254) return 0xFFFE;
if((Direction == 'f') || (Direction == 'F')) p8_3 = 0;
else if((Direction == 'r') || (Direction == 'R')) p8_3 = 1;
else return 0xFFFF;
ta1 = (PWMValue) << 8;
return (PWMValue);

void SetMotors (void){

char LeftChar;
char RightChar;
U8 intLeftSpeed;
U8 intRightSpeed;

LeftSpeed = LeftSpeed * .9;

RightSpeed = RightSpeed *.9;
if (LeftSpeed > 0) LeftChar = 'f';
LeftChar = 'r';
LeftSpeed *= -1;
if (RightSpeed > 0) RightChar = 'f';
RightChar = 'r';
RightSpeed *= -1;
intLeftSpeed = LeftSpeed;
intRightSpeed = RightSpeed;
SetMotorLeft (intLeftSpeed, LeftChar);
SetMotorRight (intRightSpeed, RightChar);

void FanOn(void){
if (FanOnCount > 4) return;
p8_5 = 1;
p8_0 = 1;
FanActive = 1;

void FanOff(void){
p8_0 = 0;
FanActive = 0;

//This fuction converts an unsigned integer value to an ASCII string. This
//function does not behave as you would think, looking at the function
//declaration. In order to use this function correctly it is necessary to declare
//a string (char array) of the intended string length or longer, which is
//then passed to this function at dest_string. Upon completion of the function
//the string (null terminated) will be available in the character array
//specified in dest_string. min_digits specifies the minimum number of visible
//characters that should make up the string (e.g. leading zeros), value is the
//integer value to be converted to a string.
char * IntToAsciiDec(char * dest_string,int min_digits,unsigned int value) {
8.9 - Appendix I - Fire Fighting Robot Source Code - Continued

const unsigned long base10[] = {1,10,100,1000,10000,100000};

unsigned int tmp;
unsigned int i, total_digits = 0;
char buff[5];

for(i=0;i<5;i++) {
tmp = (int)( value % base10[i+1] );
value -= tmp;
buff[i] = (char)( tmp / base10[i] );
buff[i] += '0';
if(buff[i] != '0') total_digits = i+1;
if( total_digits < min_digits) total_digits = min_digits;
i = total_digits;
while(i) {
*dest_string++ = buff[i-1];
*dest_string = 0;
return dest_string;