[go: up one dir, main page]

0% found this document useful (0 votes)
39 views254 pages

Implementation of A Fuzzy Logic Based Se

Uploaded by

gtorretta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views254 pages

Implementation of A Fuzzy Logic Based Se

Uploaded by

gtorretta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 254

IMPLEMENTATION OF A FUZZY LOGIC BASED

SEEDING DEPTH CONTROL SYSTEM

A Thesis
Submitted to the Faculty of Graduate Saidies
in Partial Fulfilment of the Requirements
for the D e p of

MASTER OF SCIENCE

Department of Electrical and Cornputer Engineering


University of Manitoba
Whpeg, Manitoba, Canada

63 T.Tessier. January 20,1997


The author has granted a non- L'auteur a accordé une licence non
exclusive licence allowing the exclusive permettant à la
National LX* of Canada to Bibliothecpe nationale du Canada de
reproduce, loan, distn'bute or se1 reproduire, prêter, distriiuer ou
copies of this thesis in microform, vendre des copies de cette thèse sous
paper or electronic formats. la forme de microfiche/nlm, de
reproduction sur papier ou sur format
électronique.

The author retains ownership of the L'auteur conserve la propriété du


copyright in this thesis. Neither the droit d'auteur qui protège cette thèse.
thesis nor substantial extracts h m it Ni la thèse ni des extraits substantiels
may be printed or otherwise de celle-ci ne doivent être imprimés
reproduced without the author's ou autrement reproduits sans son
permission. autorisation.
THE OF MANITOBA

COPYRIGEï PERMISION PAGE

A Thesu/Practictim submittcd to the Facuky of Gmduatt Studies of The University

of Manitoba in partiril fidiUnent of tâe reqainmenb of the degree

Permission bas been granted to the U b a r y of The University of Manitoba to knd or sell
copies of thb thesidpmcticum, to the National Library of Canada to microfilm this thesis
and to kad or sell copies of the fdm, aod «,Dtscrtatioas Abshnco Internatioaai to piblish
an absîract of this thesWpracticum.

The aothor reserva other publication iigbts, and neitbet this tbesidpracticum nor
esteosive extracts fmm it may be printed or otherivise reprodueed without the author's
w-ritten permission.
Imprecise seeding depth can lead to lower crop yields and increased power requirements.
For example, a variation of 2.56 cm (1 inch) b m optimum depth resdts in 45%, 2546, and 15%
reduction in the emergence of soybeans, sorghum, and wheat, respectively. Problems encountered
with traditionai linear seediag depth control systems inciude oscillation, instability, and
inaccurate depth control in undulating terrain. Variations of 1.27 cm to 4.45 cm (0.5 to 1.75
inches) are not uncornmon.
The control system in this ~searchutilws a rnicmprocessor-based fPzzy logic control
process in combination with a novel seeding depth gauge system. This system combines the
human coatrol reasoning of fùzzy logic with an electro-hydraulic seeding depth controiler. The
fuzzy algorithm is modelled upon expert human control by means of linguistic variables that
describe the error between the measured seeding depth and the desired depth set point. The inputs
of the fuzzy conml rules are the e m r between the measured seeding depth and the desired
seeding depth, and the rate of change in e r r a (the dinerence between the present and a past
sarnpliag instance). These variables descrik the direction of the e m r (positive, P or negative, N)
as weli as the magnitude (smali, S, medium, M or big B). The change in e m r is rnonitored in
order to provide dinerential control. Stability of the control system is ensured by monitoring these
proportional and differeatial input signals. The microprocessor unit used in the controller is the
Motorola MC68HC16Zl.
Three scenarios were examined: a 3-membership function, a 5-mernbership function, and
a 7-membership function fuzzy control algorithm. In each idgorithm simulation, the variation in
output gain, complexity, and number of MPU cycles to execute was observed. The 5-membership
function aigorithm ushg trianguiar memkrship functions was found to provide the best
combination of control and complexity for this application.
Two controller units were consmicted, for testing in laboratory simulations and under field
Data was
conditions. The 5-membership fuaction algorithm was tested under field conditio~~~.
logged fiom the field trials, with error mean fiom the set point king 2 mm, with variation and
standard deviation king 17.1 cm and 2.8 cm, respectively, based on converted A/D nadhgs.
I wish to acknowledge the guiding efforts of my advisor, Dr. W~toldKinsner, for providing
the topic of this research and for takllig the photos of the contmUer modules. His encouragement
and faith in what bis students can achieve serves as testament to bis dedication to the
advancement of knowledge.
I also wish to express my heardelt th& to George Oamby, President of hofile Resource
Management. George and 1 spent many days and eveaings at the workshop and in the fields of
Gamby Farms Ltd. during both static tests throughout 1994, 1995 and 1996, and field testing in
fall'96.1 also wish to acknowledge the support of Gamby Fanns Ltd. for the use of the workshop,
tractor and discer throughout tbis research, as weil as Joseph Gamby for his assistance with the
sensors.
In pursuhg a cross-disciplinary approach to research, I had the help and support of many
graduate students in the Department that were always willing to take the time to explain a new
concept or approach to a problem, and always to share their enthusiasm for leaming. Special
thanks goes to Dr. Ken Ferens, Dr. Armein Langi, Geoff Stacey, Warren Greider, Eric Jang, and
Aiex McIlraith.
1 wish to express thanks to my colleagues at ALjuit Aerospace Incorporated. Their
encouragement and support are very much appreciated Th- also goes to Vlad Kowalyk of
New Hoiland Canada, who supplied the sensors and the proportional valve, as well as advice on
suppression of noise in electricd devices on agricultural tractors.
This work was financially supported in part by Profile Resource Management, Iac. of
Winnipeg and the Natural Sciences and Engineering Research Council of Canada Technical and
software support was also received h m the Department of Electrical and Computer Engineering
of the University of Manitoba
This thesis is dedicated to my supportive parents, Gaii and ClBord Tessier, and my loving
wife Angela, who worked with me every step of the way to the conclusion of this work. It is also
dedicated to our daughter Adrienne, who always keeps life in perspective for her parents!
A b ~ t r o e t ~ ~ ~ ~ m a ~ . m ~ ~ . ~ ~ ~ ~ . ~ . m . ~ ~ ~ ~ ~ m . ~ . ~ ~ ~ ~ ~ ~ ~ m ~ ~ ~
0 . 0 ~ ~ ~ ~ ~ ~ ~ a ~ ~ a m m ~ ~ a

Acknowledgements ......................................................iv
Table of Contents ........................................................ v
ListofFigures ...........................................................ix
ListofEquatioas ............................xi
ListofAbbreviations ..................................................... xü
Chapter 1:
Introduction .........................................................m.gl
1.1 Background and Motivation .......................................... 1
1.2 Thesis Objectives ................................................... 2
1.3 Overview of Thesis Chapter Contributions ............................... 3

Chapter 2:
Control of Seeding Depth .................................................7
2.1 Effects of Seeding Depth on Crop Emergence ............................ 7
2.2 Types and Accuracy of Seeding hplements .............................. 9
2.3 Advantages to using discer seedea in the Red River Valley .................. 13
2.4 MethodsofDepthControl ............................................ 14
2.5 Chapter Overview .................................................. 16

Chapter 3:

3.1 Fuzzy vs .Conventional Control ....................................... 19


3.2 Formulating a Fuzzy Logic Control Aigorithm ........................... -22
Fuzzy Control Rules ......................................... - 2 2
Membership Functions ......................................... 23
F d i c a t i o n ................................................ 24
Fuzzy Inference ............................................. - 2 6
Defiizzification ............................................... 31
Summary of the Decision Process ................................ 34
Representation and Andysis of a Fuuy Logic Controller ...................34
Design of the Fuuy Logic Controller ...................................36
Chapter Overview .................................................. 39
Chapter 4:
Systern Dcfmition of the Fuzzy ! k à b g Depth ControUer .......................41
4.1 Resdts of Seeding Depth Snidies ...................................... 41
4.2 System Definition Criteria ........................................... - 4 4
4.3 Seeding Depth Conaoi System Hardware ............................... - 1 6
4.4 Seeding Depth Control System Software ............................... - 5 0
4.5 Chapter M e w ..................................................51

Chapter 5:
.
Detailed Hardware Design of the Fuzzy WCB a d Depth Controlkr ..........53
5.1 The Controuer Module .............................................. 55
5.2 TheDepthSensorModule ............................................ 61
5.3 The Hydraulic Control Module ....................................... - 6 3
5.4 Electrical Noise and EMI Suppression .................................. 65
5.5 Power Supply Module ............................................... 65
5.6 Chapter O v e ~ e w................................................. - 6 7

Chapter 6:
Software Design of the Fuuy logic-Based Seediiig Depth Contn,Uer .............69
6.1 Initiakation and Data Preparation Routines ............................. -70
Initiaikation .................................................70
CHECK-KEYSRoutine ....................................... 72
SAMPLERoutine ............................................77
ERROR-CONVERT Routine .................................. - 7 8
ERROR-BUFFERRoutine .....................................78
6.2 The F u z y Control Subroutine: ....................................... - 7 8
FUZZYTEST Routine ........................................ - 8 0
6.3 Hydraulic, LCD Display and Data Logging Routines ....................... 84
HYD-CONTRoutine ......................................... 84
Display-Depth Routine ........................................85
Send-DataRoutine ........................................... 86
6.4 Chapter Overview .................................................. 88

Chapter 7:
System Implementation ...................................................89
7.1 Field Test and Data Logging Mode ..................................... 89
Operational Issues ........................................... -90
Field Operation .............................................. 91
7.2 CalibrationMode ................................................... 96
KeypadFmctions ............................................ 97
7.3 Chapter Overview ................................................. -101

Chapter 8:
Discussion and AnalysSs of F o a y Logk B d Seeding Depth ContmUer .........103
8.1 F u u y C o n ~......................................................
l 103
8.2 SimuIation ........................................................107
8.3 Lab Testing .......................................................114
8.4 Field Testing ...................................................... 115
8.5 Chapter Summary .................................................. 123

Chapter 9:
Conclusions And Recommendations ........................................125
9.1 Performance of the Sensors ........................................... 125
9.2 Hardware Observations and Recommendations ........................... 126
9.3 Aigorithm Development Recommended Impmvements .....................127
9.4 Production of a Fuuy CASE Tool ..................................... 129
9.5 FutureWork ....................................................... 129
9.6 Chapter Overview .................................................. 131

References.............................................................. 133
Appendur A: Fwzy Depth Controiier Schemtic Diagrams ..................... A-1
Appendix B: !hftware Flowchart .F u a y ControUer ..........................B-1
B .1 Controuer Initiaiization........................................................................................ ...B 4
8.2 Main Program Execution 2
CHECK-KEYS Flowchart ............................. ....J3-8
RATSED-POSKION-SET ............................................................................B-10
Setting Disk Raised Position............................................................ B-1
Sening Disk Raised Position............................................................ .B -12
Choosing Imperia1 or Metric Units ..................... . . ................*.......B-13
MOVETO-UP ............................................................................................. B. 14
SET-OPERATING-DEPTH ................................ d l 5
FIELD-0-POSlTION-SET ....................................................................... J-16
CALIBRATE ... .........................B.17
.............e.*.r.........*.....*.....*.e..o.*.............*.....

90 Deg.Sensor Am Position Set ........................ B 18


Disc Sensor Calibration ........................ .- ...,. ................... ...B -19
Calibrate Front Sensor ......................................................................B-20
MOVETO-DOWN ......................... ......................... B 2 1
Sample Depth Sensoa ...................................................................................B-22
ERROR-CONVERT ............. ................ .. ........... ......................B-23
ERROR-BUFFER .................................................................................... .B -24
FUZZYTEST .................................................................................................B-25
.
Appendix C: S o l h w e Source Code Fuzzy ContmUer -...........................................C 4
A p p e d i ~D: PC o
m
.m
.,w
*.. .w.~w.~.w.m.w.~.~.m.o.mm.o.~.e. Dm1
Appendix E: Mathrod Simulation ...,,..m.........mw........-w,,.........,.... ,. ..........E-1
Fig. 1.1.

Fig.2.1. Crop emergence as a function of seeding depth..................................................8


Fig.2.2. Double disc seed drill opener detail.................................................................... 10
Fig.2.3. Airseeder system with highcapacity seed hopper, air blower and cultivator......11
Fig.2.4. One way discet seeder detail................................................................................ 12
Fig.2.5. Discer seeàer used in this research................................................................... 14
Fig.2.6. Iliustration of the distance from the cab to the disk gangs..................... .... 15

Fig.3.1. Membenhip functions. uich a reference fuzzy set of the term set for error........24
Fig.3.2. Fuzzification of the crisp input XO into the memkrship fiinctions of error.......25
Fig.3.3. Fuzzi£ication of the cnsp input X1 into the membership fcns of chg in error.....25
Fig.3.4. Fuzzy conmil d e summary ........................
............ .d
Fig. 3.5. Alpha cuts for the output Du@) when N = 0.0. Z = 0.3. P = 0.25. ................... -32
Fig.3.6. The rwultiag mean of maxima (MOM) output for change in output..................33
Fig.3.7. Geometric representation of fuzzy sets A aod B............................................... ..35
Fig.3.8. A fuuy contrd output s d a c e............................................................................. 36
Fig.3.9. The Fuzzy Logic Controiler (FLC)in the framework of a control system.........38

Fig.4.1. View of tandem discers fiom the tractor cab........................................ ...........43


Fig.4.2. System block diagram-seeding depth controiler......................... .
............. 4 8
Fig.5.1. ...
Lab test unit................ .............................................................................3 3
Fig.5.2. Field test and data logging unit..................... . ..................................................54
Fig.5.3. ..... - .
ControUer main modules.............................
Fig.5.4. M a i . control box connectors...................... .. .....................
. . . . . ......55
Fig.5.5. Block Diagram of the MC68HC16Z1 showing main modules and poris............56
Fig.5.6. Controller module main components................................................................. 57
Fig. 5.7. Keypad connections to Port F of MC68HC1621........................ . . ..................60
Fig.5.8. Front sensor gauge wheel assembly................................................................... 61
Fig.5.9. Hydraulic control subsystem componeats......................................................... 63
Fig.5.10. Hydrauiic proportional valve..................... . ....... ... ...............................64
Fig.5.1 1. Power Supply Module......... . . . . . . ......... +
Fig.6.1. Keypad scanning directions....................... . . .................................................-73
Fig.6.2. Acnial and ided signals from a switch. for key debouna routine...................... 73
Fig.6.3. Fuzzy d e s output table................................................................................... 79
Fig.6.4. Hydraulic valve detail........................................................................................ 85

Fig.7.1. LCD interface display in operation...................................................................... 92


Fig.7.2. Keypad functions...................................... .........................................................93
Fig.7.3. Calibration functions 90 degree setting and theta correction........................... 96
O
Fig.8.1. Fupy control d e s for 7 membership fruiction algorithm. .................................104
Fig.8.2. Manifold Editor input wmbersbip huiction example......................**................- 109
Fig.8.3. Manifold Editor output membersbip fûnctioa for 7 memb fcn algoritbm.........109
O

Fig.8.4. F D E simulation screen example: input and output memb.fcns.........................110


Fig.8.5. Input mmbership ~ c t i o nfor s change in enor h m prev.depth reading.........1 11
Fig.8.6. Output wmbersbip hctiom for depth adjustrnent. .............. .............. 1 1
Fig.8.7. Fuuy con001 surface ( h mFIDE simulation)............................................... 1 12
.
Fig 8.8. Field data logger status display screen................................................................. 1 16
Fig.8.9. Portion of data output [ile showing data format for PC Iogger............................ 1 18
Fig.8.10. T h e domain plot of the seiisor positions.................... .
... ........................... 1 19
Fig. 8.1 1 . Error plot h m PC logger, 5 membership h c t i o a aigorithm............................ 120
Fig.8.12. FFI' plot fiom PC logger, fiont sensor, for field test 5...................... ..... 121
Fig.8.13. FFI' plot fiom PC logger, disc sensor, for field test 5......................................... 121
Fig. 8.14. .
.
Enor plot fiom the 5 membership hction algorithm.................. .................122
Fig. 8.15. Field aial 5 error Born set point, over 1400 samples......................................... 122
General fom of the conml law.....................................................................20
Fuay logic controIler (FLC)representation..... .
... ... 2
.
.
Error change.................... ......................................................................... 21
Error sum....................................................................................................... 21
Control change...............................................................................................21
Min operator. .................................................................................................. 29
Max operator.................................................................................................. 29
Alpha cut output fwiction.............................................................................. 31
MOM method defiiuification........................................................................ 32

Min of inputs.................
........... ........................................................ 106
Mernbership of the min of the input variables (x. y) ........................ .
.
......107
Max of ail fuuy phrases............................................................................... 107
A ampetes
AC altemathg current
A/D analog to digital converter
CAL caiiirate
CNT control
COA center of area defindication method
CONT control
COP microprocessorunit w atchdog mer
cm centimetre
CPU central processing unit
DC direct current
DEG degrees
DOS disk operathg system
DSP digital signal processing, digital signal processor
EPROM erasable, programmable read-oniy memory
ERR errot
FCN fiinction
FFI' fast Fourier transfonn
FLC fuuy Iogic controllet
GPT general purpose tirnet of the MC68HC16
HYD hydraulic
Hz hertz, cycles per second
IBM International Business Machines
in inch
UO inlout Iiaes andlor referrhg to a microcoatroller UO subsystem
Wiz kilohertz, 1,000 cycles pet second
KHz kilohertz, binary designation, 1,024 cycles per second
km kilometre
LCD liquid crystal display
LED light emitting diode
ma milliamperes, 111,000 of an amp
MAX maximum function
MC68HCI 1 Motorola &bit micmprocessor unit29
MC68HC16 Motorola 16-bit micmprocessor unit
MEMB membership
MHz megahertz, million cycles per second
MIN minimum function
mm millimetre
MOM mean of maxima defimification method
MOV metal oxide varistor
MPU microprocessorunit
MS Microsoft
OM organic matter
PC IBM-compatible personal computer
PD proportional-differentialcontroller
PI proportional-integral controuer
PID propoaional-integrai-differentialcontroller
PWM pulse-width modulation
QSM queued serial module of the MC68HC16
RAM random access memory
ROM read-only memory
RS232 serial interface port, adhering to RS232 standard
S M system integration modde of the MC68HC16 MPU
SRAM standby, battezy-backed RAM in the MC68HC16 MPU
STD DEV standard deviation
SYS system
v volts
VAR variance
VLSI very large scale integntion
1.1 Background and Motivation
The depth of seeding of field crops is a cntical crop production factor. Of al crop

management parameters that must be coatrolled, this is one of the few that requires ao

additional cash outlay, yet can have a profound effect on the final yield and grade of a cmp

if not properly controlled.

Each type of seeding implement has unique characteristics that affect how weli it

maintains accurate depth while seeding. Among the types which pose the greatest control

accuracy challenge is the one-way discer seeder. This type of implement has been replaced

by other types on many Western Canadian farms for various reasons, not the lest of

which is the difnculty in maintainhg consistent seeding rate and depth under conditions of

varying terrain and soi1 conditions. However, one-way discer seeders are still predominant

in many parts of the Red River Valley of Manitoba, as it has the advantages of both low

capital cost combined with high efficiency in penetrating the characteristic heavy clay-

based soi1 textures predominant in the region. Seeding with discer seeders cm often
commence without the need of s p ~ pretillage
g of the field. By eliminathg this spring

pretiiiage, fuel costs are lower, wbüe the threat of soi1 erosion is also reduced. Additional

advantages are a lower labour nquirement due to fewer tiiiage passes over the field, thus

resulting in food producers complethg seeduig earlier in our short growing season. This,

in tum, reduces the risk of laie season fiost damage to the crop.
Fig. 1.1. w i c a i discer seeâer.
W~ththe problems discer seeders have in maintaining consistent seeding depth,
agricuitural crops may suffer in both yield and quaIity when discer seeders are used and

due care is not taken to m ü h k excessive emrs in seeding depth. Th- negative effects

of impmper seeding depth have k e n observed by many researchers. For instance, in

manuaily controiied discer seeders, Dyck, at the University of Saskatchewan. found that

depth variations of plus or minus 1.27 to 4.45cm (0.5 to 1-75 inches) were not uncornmon

IDyck751. This fauity depth regulation may also lead to signikant increases in p w e r

requirement for heavy mil, particuiarly for large equipment [GKWD8 lb].

1.2 Thesis Objectives


The objective of this thesis is to present a control system that combines the speed
and precision of a digital system with the control reasoaiag of a humaa operator by the use

of fuzzy Logic contxol. The seeding depth controuer described in this thesis combines the
Chaptcr 1: Introduction

human control rrasoauig of fuPy logic with a traditional electrobydraulic seeding depth

controiler to provide optimal depth control with minimalinput fiom the operator.

13 Ovenlew of Thesis Chapter Contributioms


The order in which thesîs topics are presented reflect the research approach. The

k t three chapters provide background information. These include a dennition of the

problem of maintaining the comct seed depth using conventional iechnology, a

presentation of the basic concepts of hiay logic control and why this approach was

chosen in m i s study. Thus, the problems to be addressed by this research are defined.

These chapters are then followed by three chapters which present the system organization,

hardware details, and software design. Finaily, the 1 s t two chapters present the results and

recommendations fkom this research. The appendices contain iDformation related to the

execution of the hardware and software development, including schematics,

specifications, and source code.

Chapter 2
The problem of maintaining correct seeding depth and current methods used to

control seed depth are outlined in this chapter. The approach taken is from the viewpoint

of agricuitura researchers and producers, using tem commoniy used in agricultural

research and on prairie cereal famis. This aiiows for an intuitive definition of the problem

that is consistent with the reason funy control is king investigated for this application:

no accurate mathematical mode1 of a conventional seed depth controiier is found in the

lirerature that can define how such a system should respond to a wide variety of field

conditions.
Chapter 1: Inuoduction

Chapter 3
The theory of fuzzy logic controiiers is presented in Chapter 3 of this thesis. This
will be compared to the basic theories of conventional control law, and how tbis relates to

some of the problems encountered in conventional seeding depth control methods. The

reader is stepped through the profess of d e m g a control problem, generating niles, and

how the fuuy inference process works. A simple example is used to illustrate the major

points. The final portion of this chapter dso provides background information on the topic

of some methods used in the design of hiuy logic controllers.

Chapter 4
Once the problems with using conventional control law in designing seedhg depth

controllen has been presented. the system definition section wili explain how the theones

of hiuy control can be applied to solve the problem. By d e m g the problem and the

approach to a solution, the required hardware and software specincations are developed.

Vitrious choices in hardware and types of software algorithms wiil be explored. Finally,

the chosen design will be outiined, with an explanation of why this route was chosen.

Chapter 5
A more detailed blodc diagram wilî be presented in the Detailed Hardware Design

of the Fuzzy Seeding Depth Controller, with an explanation of the system architecture and

organîzation. The implementation wiii aIso be described, with speciai focus on how the

controLler is operated by the user.


Chapter I: Introduction

Chapter 6
In this chapter, the objectives and functions of the software design are presented.
This section wiU also outline how this relates to the nst of the system architecture. The

software organization and implementation will also be explained ben.

Chapter 7
The integration of the hardware and software to produce a working fuay seeding
depth control system is explained in the System Implementation section. This includes the

process of putting the different parts of the system together and vewing that the systern

Chapter 8
In the Discussion and Andysis of the Fuay Seeding Depth ControlIer section,

theoretical and field experirmntal results are presented. The design of the experirnents is

explained, with emphasis on the test methods and what parameters were king tested. The

final results will also be discussed, with an explanation of why the best results meet the

test criteria.

Chapter 9
Findy, the Coaclusions and Recommendations summarizes the proven points and

discoveries, as weIl as contributions to science and technology. The direction of bture

work in thïs area wiU aiso be presented based on what howledge was gained fiom this

research.

The approach of this research is to combine the theoretical aspects of hizzy logic

connol with the practical aspects of controliet implemntation and testing. The f h t sfep
Chapter 1: huoduction

of this process, the definition of the problem of accurate seeding depth control, will be

defined in Chapter 2.
Cbaptcr 2: Control of Seeding Depth

In this Chapter, the problem of maintaining consistent and accurate seeding depth

control is prrsented. The crop emergence and crop health coasequences of poor seeding

depth control are pnsented in Section 2.1. In Section 2.2, the most common methods of

seeding depth control with discer seeding ùnplements are described and compared.

2.1 Effeets of Seeding Depth on Crop Emergence


Lack of adequate depth control may Iead to variations in the depth of seeding. The

negative effects of improper seeding depth have k e n observed by many researchea. For

instance, in manuaily controlied discer seeden, Dyck, at the University of Saskatchewan,

found that depth variations of plus or minus 1.27 to 4.45 cm (0.5 to 1.75 inches) were not

uncornmon @3yckiS].This faulty depth regulation may Iead to signiticant increases in

power requirement in heavy soüs, particulariy with large equipment [GKWD8 lb],

[BBKR83].

Crop emergence can be signiscautly reduced by s d variations in depth. This

fundamental problem bas k e n studied for many years, and the effects n quite well

established in the literahue WuAr391, [Sund64]. In some crops, mathematical models

have even k e n developed that predict emergence based on seeding depth m 1 7 4 1 . The

effect can be quite severe, given the nonlinearity of crop emergence fuoctions.
Chapter 2: Conml ofS 4 n g Depth

O 2 4 6 8 10
Depth of Pfanting [un]

Fig. 2.1. Crop emergence as a function of seeding depth. (Mer woGe8Sa], [KGFT93]).

Using soybeans, with a peak mean of 3 cm (1.17 iaches), a variation of only 1 cm

(0.39 inches) fÎom this peak results in a reduction in emergence of 5%. In cornparison,

shouid seeding depth be erroneously set to 4 cm (1.56 inches), a variation of only 1 cm

(0.39 inches) in depth above and below this set point wiil resdt in reduced emergence by

5% and 30%. respectively, as show in Fig. 1 MoGe85al. Therefore, the benefits of

precise seed depth control are significant

Results such as those presented in Fig. 1 are genedy true for crops in which the

main independent variable, that is to Say, the ody major limiting factor, is the depth of

seeding. Other, less optimai situations typicaiiy arise on prairie fields that can f d e r

magnify the effects of improper seeding depth. Such extra limitations are chanicterized by
Chapter 2: Controi of Seeding Depth

adding additional stnss on the emerging crop, in addition to the stress induced by

improper seeding depth.

Stress factors due to the enects of nature include conditions that may slow crop

emergence, such as extreme environmental conditioas. Soils which are extremely hot.

cold, wet or dry all produce suboptimal conditions for growth. Other natwal factors that

can have a magnifying effcct on poor depth control include intense weed cornpetition,

cmsted soil surface, and the presence of soilborne diseases and insect pests [ H a D m .

Manmade stress factors have also been documented to magnify the negative

effects of poor seed depth control. These iaclude the presence of excessive herbicide

residues such as triailate and trifluralin, especidy in soils low in organic matter (under

2.5%) WSSA83J. This problem c m be very severe in areas such as central Saskatchewan,

where rolling soil with low organic matter eroded knolls are ofien seeded deeper than

surroundhg areas. This deeper seeding is due to depth control system of the seeder king

unable to adequately respond to the sudden change in terrain.

2.2 ' Q p s and Accur~eyof Seeding Implements

There are many dinerent types of implernents used in western Canada for seeding

cereal and oilseed crops. In tenns of the types of tillage or soil disturbance methods most

commonly by these implernent types in both cenals and oilseed crops, three are in most

common use today: the double disc press drill, the airflow or airseeder cultivator system,

and one-way discer seeders.


Cbapter 2: Control of Seeding Depth

The double disc press drill is the most accurate seeding implement used on the

prairies, with two flat discs peuetrathg the soil at an angle of o d y a few degrees h m the

direction of travel.
I

Seed Spout

Fig. 2.2. Double disc seed drill opener detail.

The discs open the soil in such a way that a h o w is produced at the desired
depth. Seed is then dropped iato the hurow, and soil is placed over the seed. Soil covers

the seed by two processes: soil falling back into the funow once the discs have passed by,

and by the compression action of a flat wheel or tire, about twice the width of the furrow,

pushing soil down over the seed and packing i t Depth control with these implements is

generaily by means of mechanical conml, by a stop bolted to the ram shaft of the

hydraulic disc lift cylinder. Most double disc press drills also have s p ~ g which
s act upon

the double disc soil penetrating assemblies, thus keeping fairly consistent depths even in

undulating tenain. The packing discs are mounted ngidy to the seeder fiame, and provide

a large surface area for the seeder to ride on (as wide as the entire implement). Although

they are very accurate, these systems are weil suited only for loose soils that have been
Chapter 2: Control of Seeding Depîb

preworked by cuitivatiag and barrowiagor on very light textureci soils. Some zero tillage

seeders use this system, but o k n need considerable weight and tractor hoisepower to

penetrate the soil to an ndequate deph without field prewodring. 2ero tillage double disc

press drills are excellent for soil and moisture conservation, and in fact have been

designed to preclude the need for any pretillage priot to seeding, thus eiiminating vimially

ail soil erosion. Unfortunately, they also tend to require a relatively high labour, draft. and

maintenance requirement per metre of width than do other systems.

Fig. 2.3. Airseeder system with high capacity seed hopper, air blower and cultivator.

The airseeder or airtlow system is increasing in popularity in western Canada, due


to its lower labour requirement, maintenance, and speed of seeding. These implements use

a very low lift cultivator shovel as the means of soil penetration. Depth control with these

systems is a challenge, with many companies using different configurationsof depth guide

wheels, dual tires for Boatation over soft soil, elecnic over hydrauLic conventional conml

systems, and various mechanical meam [GKWD8la]. Each rigid cultivator shank may
Chapter 2: Conml of Seedig Depth

have one or two springs holding it in place. The design is a compromise between accuracy

of seed placement and seedbed quaiity to time savings and low labour requirement.

By v h e of it's design, the discer seeder does not use the kind of precise seed

placement techniques used by otber systems. One of the major drawbacks of using one-

way discer seeders is the lack of precise seeding depth controi. Tn fact, depending on how

weii the seed outiet spouts are placed in relation to the discs, the seed could be placed

anywhere h m a narrow vertical band less than 1 cm wide, to as much as 4 or 5 cm in a

nonuniform distribution. Seeding rate also varies as the discs gang swings fkom side to

side over dinerent soil conditions, thus widening or narrowing the area seeded per disc

unit.

Fig. 2.4. One way discer seeder detail.

The discs can be describeci as the concave circular steel tools with a sharpened

edge making up the working part of a discer seeder Wen93J.Discer seeders use gangs of

single concave discs that penetrate the soil at an angle a few degrees fiom the direction of

travel. This angle ope= the concave side of the disc to the soil, where the edge of the disc
Chapter 2: ControI of Seeding Depth

cuts into the soil. The larger the angk of the disc to the soil,the Iarger the cross-section of

soil the disc is exposed to in the direction of travel. As a dtas the mgle of the disc to
,

the soil increases, so too does the draft, increasing the power nquirement h m the tractor
to maintain the same speed. Likewk, with the seed m g the hoppen above the discs,

this added weight can cornpress the tires holding up the discer unit This compression acts

to push the discer deeper into the soii, addiag to the seedhg depth. Lïkewise, with more

depth, draft increases, which adds a traverse force on the discer against the wheels,

causing the discer to swing perpendicular to the direction of travel, thus wideaing the

width of cut across the whole discer. Now, with a seed depth that is deeper than that set by

the operator, there is also an decrease in seeding rate proportionai to the decreased width

covered by the discer in each p a s at this depth. An expert operator is able to weigh the

different factors that affect these problems when choosing the best compromises for depth

sening, includiag such parameters as wheel positioning, speed, and tire pressure.

2.3 Advantages of using discer seeders in the Red River Valley


Agricultural producers choose a seeding method based on a number of criteria.

These include local soil texture(s), local experience, types of crops grown, costs, pre-

seeding preparation methods and labour requirements. In the Red River Valley, producers

on heavy soils such as Osborne Clay have two major problems: incorporating straw left on

the soii surface fiom the previous year's harvest, and penetrating the heavy soii deep

enough while seeding without producing too many soii lumps. One-way discer seeders are

well suited for these conditions. As an additional benefit of using discer seeders, many

producers fhd that they can seed straight into the soi1 in the spring without pretiiîage
Cbapter 2: Controi of Seeding Depth

preparation. This eliminates the tirne, expense, soi1 moisture l o s and increased ri& of soi1

erosion associated with pre-seeding tülage. Seecling with these implemnts has been

popuiar for many years in this region, and is still common, although other seeding

implements are being improved and are slowly being adopted over discer seeding-

2.4 Me&& of Ikpth Controi


The oldest depth control method that many fanners stili rely on is their own visual
estimate of the amount of a seeding implement buried below the soi1 snrface and their

"feei" for the sound and vibration of increased engine load when the seeder digs into the

grwnd. Many other schemes have been introduced to improve on this method Froe921.

With the use of a cornputer controlled electromechanical depth monitor for the

hydrauiic depth control mechaaism of a Seeder, average seeding depths varied within a 2

cm range IDyck751.

Fig. 2.5. Discer seeder, (typical of the types used in the Red River Valley of Manitoba),
used in this research.
Fig. 2.6. Illustration of the distance h m the cab to the disk gangs.

Depth control and monitoring devices are based on mechanical or electrohydraulic

control. These methods do not aiways provide consistent accwacy of seedhg depth over

varying terrain conditions, especiaiiy on one-way discer seeders. Commoa methods for

controlling the depth of discer seed implements in uneven terrain are tiring for the

operator, and are inaccurate, leading to increased power requirements and reduced crop

yields. The seeder, which is used for seeduig and on occasion tillage, is raised aad lowered

by hydraulic cylinders which are actuated by manual or electncal control of hydraulic

flow valves. As fuel and machinery costs rise, efforts to maximizc efficiency lead to the

use of larger implements such as 58-foot wide cultivators/air seeders and the practice of

hitching s e v e d discers PBKR831. These arrangements severely hamper the


Chaprer 2: Conml of Seeding Depth

effecriveness of even an expert human operator who must estimate the depth of the rear

furrow as far as 20 m away. Coupled with this, the operators' vision is often obscured by

dust, and they must mentally average out tbe depth for varying soi1 conditions. Errors in

the estimates increase with large variances in soii moistue, topography, soil texture, and

draf't load as the seed emptics out of the hoppers. In discer seed implements, this is M e r

compounded by the fact that the width of the ana seeded also changes with large

variations in draft Ioads.

Fuuy control offers a paradigm in which control d e s based on a human

operator's experience are used to produce control algorithms that have k e n effective in

controlling nonllliear. dynarnic plants that proved to be extremely difficult or too complex

to be modelied mathematically for creating effective conventional controllers mamd93].

The problems encountered with one-way discer depth control, with its combinations of

varying dr& loads, soil types, soi1 conditions and topography certainly make this seeding

problem a good candidate for determining the results of applying a hizzy logic control

algorithm mOTN87].

2.5 Chapter Oveniew


The importance of accurate seedùig depth and its effect upon crop vigour and yield

provide the main motivation for the investigations in this research. Characteristics and

limitations inherent in different seeding methods and depth controiler srpes were given.

The prevalence of one-way discer &ers and thek advantages and disadvantages for use

in the Red River Valiey of Manitoba was also explained.


To date, the prevalent types of seeding depth control methods have included visual

judging of depth with mechanical conaol actuation, mechanical "stops" on hydraulic

cylinders, and conventionai electrohydraulic controilers. Due to the noalinear nature of

depth control under varying soi1 and topographie conditions, problems have been

expenenced with these control methods. A more suitable control regime was investigated,

with an eye to providing more consistent coatrol by accurate sensing of the seeder depth,

in combination with the ability to vary hydraulic control signal gain based on the depth

position at the current instant in t h e and the position in the past. Fwzy logic control is

welI suited for this type of nonlinear application, and is evaluated in this research.
Chapter 3: Fuzzy Logic Control

Fuuy logic control is weli suited to control problems where tirne-varying.

nonünear inputs characterue the system [KiMa77]. Examples Uiclude a wide variety of

industrial and domestic uses, fiom controllhg the braking of high-speed commuter trains

in lapan, to the control of operating cycles of washing machines m 9 4 ] .

The concept of fuuy logic, and specificalIy, funy set theory, can be directly

attributed to Lotn A. Zadeh, of the University of Caiifomia at Berkeley. In the first paper

published on this topic, Zadeh d d b e d fuzy sets and the underlying theory behind them

[ZadedS].

In this Chapter, a description of hizzy logic by cornparhg it to what can be caiied

"conventional control law" in Section 3.1. In 3.2, then is a step by step explanation and

example of how one would formulate a hizzy control algorithm. Once the basic principles

of huzy logic control have been presented, Section 3.3 deals with the issue of how to

represent and model a futy logic controller.

3.1 F m y vs. Conventionai Control


One common feature of conventional control law is that it is based on algorithms

that can be described precisely by equations. They generaüy require a formaiked

andytical description of the controiied system in the form of a mathematical model in

order to synthesize the algorithm mamd93]. Fuzy control algorithms. on the other band,
Chapter 3: Fuzy Logic Control

are constructeci using logical mies. Each d e defines what the output of the controlier

must be, based on the specific value(s) of input state(s). Rather than behg derived pmly

as the result of creating a mathematical model, the d e s are ofkn fonnulated under the

direction of an expert human operator. Linguistic contml algorithms are used, which are

constructed from a nile base that in nim is fomulated fkom human experience and

intuition. The theoretical and practical aspects of the dynamics of the controlled system

may also be used [Zade73].

Under conventional control law, dgorithrns (such as proportional, derivative,

integral, PD, P D )can aü be denved fiom the generai form of the control law for different

fùnctions of various orders Dorfû91

p(k) = f ( e ( k ) , e ( k - l ) , ...,e ( k - v ) , u ( k - l ) , u ( k - 2 ) , ..., u ( k - v ) ) (3.1)

w here

f is, in general, a nonlinear fuactioa,

k is the instance or sampie number,

e is the error between the setpoint and the output of the controller,

v defines the order of the contmiler, and

u is the change in output.

The fuzy logic controllet (FXC),on the other band can ofken be repnsented in a

sirnilar fonn
Cbapter 3: Fwzy Logic Control

where F is the contml law described by a d e base. It should be noted, however,

that an FLC is not a type of ciifference equation or tramfer fiuiction as in conventional

control logic. In fact, the representation above is only limited to situations wbere it is not

ciifficuit to describe it verbaliy. This is especially tnie when it is considered that a FLC

uses a knowledge base, so past higher-order values of both the control action u and the

error e are not always needed in order to complete the fuuy algorithm. Since the FLC is

based on d e s , it is possible to incorporate combinations of the enor e and control u that

are relevant to the mal-world operation of the plant in ways not possible with conventional

control law WaFi94J.For example, the various operations can be easiiy incorporated into

an FLC's control des, including

error change

error sum

control change

Au(k) = ~ ( k- u
) (k-1) (3 -5)

In conventional control law, one of the main paradigms is the concept of

analyticity. Ln the FLC,the main paradigm is the concept of a Imowledge-based algorithm

operating as a kind of expert knowledge-based system, containhg the control algorithm in

a simple nile base.


Chapter 3: Fuay Logic Control

3.2 Fomulating a Fuay Loglc Control Algorithm


In constructing a funy logic controlier, it is necessary to M y understand the plant

to be controlled. This knowledge can originate as the control actions of an expert human

operator for each set of input variables. It can also originate as a set of &ta containhg

observations of a properly operating system. In a few circumstances, the d e base can be

derived fiom a conventional controf tramfer function FaFi94J.

Through the aext several sections of this Chapter, an example funy controuer

with nine d e s , two input variables and one output variable will be used to illustrate the

concept king explained.

3.2.1 Fuuy Contmi Rules


Once the system to be controlied is undentwd, the next step is to constmct the

fuzy control d e s . The control d e s constitute the fuuy control algorithm. These d e s

are consmicted using logical (Boolean) "&then" d e s . The d e s are based on the

implementation of human undestanding and rhinking of the plant to be controlied.

Rules may appear to be simple intuitive statements based on an observation or a

base of experience, but in reality they have a very specific syntax. The foilowing is an

example of the form they would follow.

IF antecedent 1 A N D antecedent 2 THEN consequent 1 AND consequent 2

ALSO

where

- The "IF'portion of the d e contains the antecedents. This part of the nile

-21 -
contains the conditions that a e c t the plant.

- AND is one of the ailowable fuuy logic Bookan operators, (such as AND,OR.
Non
- the antecedents are in the fom of an input variable equal to some value. For
example, "temperature is HOT",where temperature is the input variable, and hot

is one of the membership fùnction labels associated with temperature.

- the "THEN" portion of the rule contains the consequent This gives the output or
conclusions, should the conditions in the antecedent part of the d e be satisfied.

If the output of a consequent applies, it is said that the d e 66fires".

- the consequents are in the fonn of an output variable equal to some value. For
example, "fan speed is HIGH", where fan speed is the output variable, and high

is one of the membership b c t i o n labels associated with temperature.

- ALSO is the equivalent of the Boolean operator OR.


The terms, or linguistic labels qualitatively describe the input and output in each
d e . Descriptors such as Positive, Negative and appmximately zero are examples of

Linguistic labels.

In the application described in this thesis, the FLC describes the relationship

between error e(k), change in e m A e(k) FeKi93J.

3.2.2 Membership Functions


Each variable in a d e constitutes the measured observation or output control

action, such as the error, change in enor, and output. The linguistic labels within the d e s

each constinite a fbzzy set, or a referencefuuy set. When a number of refennce fuzzy sets
Chapter 3: Frtay Logic Conuol

are grouped for a specinc variable. this is a tenn set. The variable king measured or

cdculated exists within a finite range of values, or the unberse of discoure. In mmmary,

this means that for one variable, for example, emr; e(k), the t e m set contaias a number of

reference fupy sets (wgative, appmximately zero, and positive), ail defiwd over the

same universe of discourse. Each reference fuzzy set represents the associated linguistic

variable.

Negarive Appmximiatety Positive


Zero
-
.
5
1.0
Li
g 0.5-
E
Z O
I
- 1.0 -C S I
O
I
0.5
1
1.O

Fig. 3.1. Membership functions, each a reference hiuy set of the tem set for erroi; e(k).

Generaily, the scaliog of variables and reference fuzzy sets within a universe of

discourse ranges over the input variable values. The shape of membenhip functions can

Vary; trianguiar membership h c t i o n s are quite easy to code in software, but other shapes

caa include Gaussian, rectangular (non-fuzy or crisp control), and variations of merent

noaliaear fùnctions and cuves.

3.2.3 Fuu~jïcatiun
The process of converthg crisp input values of the FLC variable(s) into a level of

membership in each membership function is cd.ied~ificution.


As each input variable is
Chapter 3: Fuzy Logic Control

evaluated, membership values in each reference fuuy set (for each membership function)

are determined.

Negutive Appmximately Positive


Zem

Input X* = -O. 1
membership in Positive = 0.
membeahip in Appdmately Zkro = 0.75
membersbip in Negative = 0.25

Fig. 3.2. Fuzzification of the crisp input Xointo the membership fiinctions of erra>; e(k).

Negative Apprvximtely Positive


Zero

hput X1= 0.2


membeahip in Negative = 0.0
membership in Apptvximateiy Zero = 0.3
membership in Positive = 0.6

Fig. 3.3. Fuzzification of the crisp input Xlinto the membership functions of change in
error; Ae(k).
The degree of membership of an input in a membecship fwction is determined by
cornparhg the value of the input to the values defmed for each membersbip hinction. The

resulr, thetefore, is the level of memkrship that the input value has in each rnembership

funftion, described as a number between O and 1. For example, the crisp input for error

may be a value of -0.1 uni&. In Fig. 3.2, this value of 4.1 cinits gives a degree of

membenhip in negamte of 0.25, and a degree of membership of 0.75 in approm*mateiy

zero,

3.2.4 F u m Inference
The degne of membership in each fuay set is then determined for a i i other input

variables. Once complete, the membership values for each membership function are

substinited into the mies goveming the process of the fuuy controlles. This process,

calied rule evaluation, or fuuy inference, appLies the fuuy input values from the

fimification process to the d e s that govern the controller. Each mie is then evaiuated to

calculate the "level of firing" for each rule.

Here is an example of a simple fuay d e base with 9 d e s :

1. IF the error is positive AND the change in error is positive TEEN the change
of the control is negative;

ALSO

2. IF the e m r is positive AND the change in error is appmximately zero THEN

the change of thc control is negative;

ALSO

3. IF the enor is positive AND the change in error is negative THEN the change
of the control is approximately zero;

ALSO
4. LF the error is approximateIy zero AND the change in emr is positive TEiEN

the change of the con@ is negative;

ALSO

5. IF the error is approximately zero AND the change in enor is approximately

zero TEEN the change of the control is zero;

ALSO
6. IF the error is approximately zero AND the change in emr is negative TEiEN

the change of the control is positive;

ALSO
7. IF the error is negative AND the change in error is positive THEN the change
of the control is approximately zero;

ALSO

8. IF the error is negative AND the change in error is approximately zero THEN
the change of the control is positive;

ALSO

9. IF the error is negative AND the change in error is negative THEN the change

of the control is positive.

The complete d e base that describes the control actions of the FU3 in this

example under a range of States can be summarlled in the foilowiog chart:


Chapter 3: Fuzzy Logic Control

N - Negative 2- Approximately
P - Positive Zero
Fuzzy Decision Rule Chart for the example rules

Fig. 3.4. Fuzzy control nile summary.

This intuitive description of control action under a range of conditions c m serve as


a very accurate summary of the actions of the system without a detaiied mathematical

model.

The value of each antecedent of each mie is determioed, and substituted into each

d e . The mle strength or degree of m r h of each d e is then determined by evaluating the

antecedents. In this case, the Boolean operator linking the antecedents is AND. This

means that the nile takes on the lowest value of each antecedent for the d e . Using the

antecedent notations given in Fig. 3.4, we substitute the degrees of membership in e w r

e(k) and change in ezror Ae(k) into the d e s of the sample d e base to obtain the degree of

membership in the respective output membership fiiactions, Au(k).

1. IF e(k) is P (0.0) AND &(k) is P (0.6) THEN h ( k ) is N (0.0) ALSO


2. IF e(k) is P (0.0) AND &(k) is Z (0.3)T ' E Nâu(k) is N (0.0) ALSO
3. IF e(k) is P (0.0) AND &(k) is N (0.0) THEN Au(k) is Z (0.0) ALSO
Chapter 3: Fuzzy Logic Conml

4. IF e(k) is Z (0.75) AND Ae(k) is P (0.6) THEN &(k) is N (0.6) ALSO


S. IF e(k) is Z (0.75) AND &(k) is 2(0.3) THEN Au(k) is Z (0.3) ALSO
6. IF e(k) is Z (0.75) AND &(k) is N (0.0) THEN &(k) is P (0.0) ALSO

7. IF e(k) is N (0.25) AND De(k) is P (0.6) THEN &(k) is Z (0.25)ALSO


8. IF e(k) is N (0.25) AM) &(k) is Z (0.3) THEN &(k) is P (0.25)ALSO

9. IF e(k) is N (0.25) AND &(k) is N (0.0) THEN h ( k ) is P (0.0)

We now have assigned degrees of truth or degree of finng (DOF) to each d e ,

based on the vaiues of the antecedent input values. Each of these values were cietermined

using an AND-type (or intersection) conjective connection, the Min A operator, between

the two inputs. This can be expnssed in the following form:

ri = Bi 1 (XI) A Bi2 ("2) (3-6)

Where Ti is the DOF for the i' ruie with respect to the input values within the

universes of discourse (LI,). U I= xl and CI2 = x2. Bil and Bn denote the membership

functions of antecedent 1 and 2 for ruie i.

Now that we have the d e strengths for each nile, we can proceed with the

aggregation of these values using the OR-type (or union) disjunctive conneciive ALSO.

This operation is conducted using the Mar v operator


In our example FLC niles, this equation would be evaluated as:

1. ...change of the contrd is negative (value of d e = F(1)= 0.0) ALSO

2. ...change of the control is aegative (value of nile = F(2)= 0.0) ALSO


3. ...change of the control is zero (value of d e = F(3) = 0.0) ALSO

4. ...change of the control is negative (value of d e = F(4) = 0.6) ALSO


5. ...the control is zero (value of mie = F(5) = 0.3) ALSO
6. ...the control is positive (value of d e = F(6) = 0.0) ALSO

7. ...change of the control is zero (value of d e = F(4) = 0.25) ALSO


8. ...the control is positive (value of d e = F(5) ~ 0 . 2 5 ) ALSO
9. ...the control is positive (value of rule = F(6)= 0.0)

The result of the fuzzy ORing operation yields degrees of membenhips of the
consequents in each membership fiiaction of the change in output Au(k):

negative change in control = 0.0

zero change in control = 0.3

positive change in control = 0.25

These values now cm be applied to the output f b z q sets, in the process of

defuuicicotion.
Chapter 3: Fuay Logic Control

3.2.5 Deficmcation
Now that we have the values of the consequents. we move on to the h a 1 step,
defuwcation. In this pnicess. a singie crisp output value is caicuiated by any one of a
number of defuuification techniques. Three common defuaification methods are the

Center of Area (CO& or centroid method), the Singleton methoci, and the Mean of

Maxima (MOM).

In the centroid method, each output membership function is truncated above the
indicated level of its degree of membership. This is c d e d an alpha cut. AU the @ha cuts

for each membership functions of the term set output are determined, with the center of

area caiculated as a f b z y centroid. Here, we consider the finite universe of discourse Y

and the discrete membership functions F(y):

This results in the output king the ~ s doft a weighted average taken as the center

of mass of an area comprishg the combined areas under the alpha cuts. In the example

given above for the nine membership functions, the output is represented graphicaiiy Fig.

3.5.
Chapter 3: Fuzy Logic Control

for output Au(k): membership in Negative = 0.0


membership in Appmximtely Zero = 0.3
membership in Positive =0.25
Negative Appmximately Positive
Zero

term set for change in output. &(k)

output Y= 0.3
resultiug alpha cuts and output for change in output, &(k)

Fig. 3.5. Alpha cuts for the output h ( k ) when N = 0.0, Z = 0.3, P = 0.25.

In the MOM methoci, the defuzzified value is determined as the meaa of al1 values
of the universe of discourse having the maximum membership values:
Where J is the set of aU elements of the universe of discourse of Y that have the

maximum value of F(y). The element q is the cardinality of J.


The singleton defuvification method is commonly used on microcontroliers,
where speed of caiculation is often a limiting factor. Generaily, singleton dehiaincation

results are based on a lookup table for vaiues withh a given range, rather than using extra

clock cycles to compute a summation. This does not result in values that are as precise or

6nely-tuned as the previous two methods. It is important, therefore, to ensure the

effectiveness of the plant to be controiied is not compromised by the reduced graaularity

of this method.

for output Au(k): membership in Negarive = 0.0


membeahip in A p p r ~ ~ m a t eZero
l y = 0.3
membeahip in Positive = 0.25
Negative Approxinately Positive
Zero
These areas not used in calculation -
1.O they do not constitute local maxima

Fig. 3.6. The resuiting mean of maxima (MOM)output for change in ourput, &(k).

In the singleton method, the mie consequent values are ploned on the Universe of

Discourse of the output range. The average value between the points is then calculated.

This average is the resuiting output value.


Chapter 3: Fuzzy Logic Control

3.2.6 Summary of the Decision Pmcess


The process of calculating the aisp output of a FU3 can be summarized as
follows:

1. Determine the degree of fiRng @OF')of the d e s . This is determined by taking

the minimum (AND)of the antecedents. The value of antecedents were

determined by the level of matching the input values with the respective fuuy

set for the d e .

2. In the next step, findication (or huy implication), the degree of membership

in each consequent fuuy set is determined, according to the respective niles'


DOE

3. Rule aggregation takes place when the maximum (OR) function is performed

on the consequent membership funftions across aii of the d e s . This produces

the final output from the mie base.

4. Finaiiy, in defuPification, a discrete output value is determined by calculating

the fimified centroid of the output hizzy set.

3.3 Representation and Analysis of a Fuzzy Logic ControUer


As the h z q logic pracess often involves two input variables and one or more

output variables, FLC's can be represented geometrically. The antecedents of each d e can

be mapped over a 2 dimensional m a , with one antecedent on each side. In Fig. 3.7, the

universe of discourse for each antecedent is represented by two dimensions XIand X2,

(the fwzy input space) while the memkrship fiinctions are represented by Bi 1 and Bi2.
Chapter 3: Fuzy Logic Conml

The inputs fiom the universes of discoune (Ul. Ud are mapped to what is

essentidy a state space for the input variables (antecedents) in the dimensions Xi and X2.

Each overlapping area A and B indicate d e s of the form

IF U1(for example, emr) is Bii AND Ui(for example, change in error) is Ba

THEN V (for example, change of the conwl) is Di

Thus, the output membership fuaction is determined by the conseqwnt. The

output, (for example, the control action) Di, is within the universe of discourse It is

shown in Fig. 3.7 as the Y axis. The DOF of this output is a resuit of the huy inference

process. Therefore, this representation is similar to a control surface with the overlapping

regions of the control d e s analogous to areas of gradua1 slope on the surface (Fig. 3.8).

If,

Fig. 3.7. Geometric representation of fuuy sets A and B (from YaFi94).

It is important at tbis point to undentand the basic operation of the hiuy

controller. The relationship to conventional contml can be made by describing the actions
Cbapter 3: Fuzzy Logic Control

of the fuuy algorithm. For a Proportionai-Integral f h q conaoller, the change in conml

is related to the e m and its change.

o m

Fig. 3.8. A fuzy control output surface.

It should be noted that the degree of overlap of rnembership fwctions w i t h the

state space, for example, regions A and B in Fig. 3.7, are important in the measurement of

the fuzziness of the FLC. Should these regions not overlap at all, the result would be a

disjoint collection of d e s which operate as a variable gain relay. Only one d e could 6re

at a time.

3.4 Design of the Fuzzy Logic Cootroller


Once it bas been detennined that a control system utilizllig fuzzy logic will be

consüucted there are several approaches that can be taken to do this. The traditional

method is to put together a d e base in a simüar way that an expert system would be buiit.

An expert operator is asked to describe their actions when the system is in various States.

As this may not produce optimal control actions, the operation and characteristics of the

plant to be controlied are M e r studied, much in the same way as for conventional
Chapter 3: Fuzzy Logic Control

conaol. The d e s are then fomulated and the h t membenhip functions are put in place.

The controller results arr then found by simulation or testing- Suitable changes are made
to the membeahip fimctions an& niles untiI the resuits are satisfactory.

Another approach to the formulation of a fuuy controller is the template method

wacV77]- This method uses a standard d e base that is modified to fit the particular

controlier. It is a more formal approach to producing fuay control mies than the

traditional method described above.

The basis of the template method is that mies are produced based on three

metaniles:

If ERROR e(k) and CHANGE IN ERROR Ae(k) are 0, the CHANGE IN

CONTROL h ( k ) is O.

If ERROR e(k) is approaching O at a satisfactory rate, the CHANGE IN


CONTROL &(k) is O.
If ERROR e(k) is not approaching O at a satisfactory rate, the CHANGE IN

CONTROL &(k) is in nonrem, with the magnitude and direction depending


on the direction and the amount of ERROR e(k) and CHANGE IN CONTROL

fW)-
These metaniles are then expanded to cover the input States and the corresponduig

expected outputs of the system to be controIIed.

With having defîned the niles and membership fùnctions of a fuzy logic control

algorithm. the next step is to implement this into a workable controller. The example we

have been describing as the example in this Section is similar in hinftion to a conventionai
Chaptcr 3: Fwzy Logic Control

PI type controlier. As such, the block diagramdescniing the hardware of a Marndani-type

FLC is similar to that of the block diagram of a conventional PI controller.

Fig. 3.8 shows a basic block diagram of a Mamdani-type FLC. The input error

signal, e(k), a direct input to the FLC, is ais0 stored in memory for the next sampling

instance, and compared to the previous sampling instance to determine the change in emr.

The defuuined output is also cornparrd to the previous output value, which provides a
feedback mechanisrn to prevent control oscillation when output varies around the set

point.

- change in error between instance (k) and (k - 1)


u(k) - output in instance (k)
Au (k) - change in output between instance (k) and (k-1)

Fig. 3.9. The Fuuy Logic Controller (FLC) in the fhmework of a control system (fiom
YaFi94).

Appropriate sensory and control devices are chosen to meet the original criteria for

the fuay controller inputs and outputs. Appropriate controller cornputer design
Chapter 3: Fuzzy Logic Control

specifications are also worked out, given the fuay code to be implemented, the speed of

actuation needed, and other considerations in the design such as cost, powet availability,

size requirements. and operathg environment Once the controk has been built, the

control actions are tested agakst the expected results from the theoretical and simulated

predictions. Appropriate changes in fuay control algorithm and hardware are then made

if necessary-

3.5 Chapter Overview


A description of tbe theory of fuzzy Iogic control relevant to the research in this

thesis was presented here. Of course, there is a growing body of research found in the

iiterature about fuuy set theory and b z q aritùmetic methods as they pertain to funy

controllers, so there are other interesthg approaches that can be taken in any further

research, as explained in Chapter 8.

In formulating a fuuy controlier, expert operator advice is used to produce the

niles and definition of the limits of fuuy sets that govem its operation. The number of

membership functions depends on how smooth the controlier output must be for proper

operation. In implementing the resulting controïier, extra hardware-dependent

considerations wiil also affect the number and shape of d e s . An example of this is the

degree of accuracy of AID converters (for example. 8-bit vs. Idbit), hearity of sensors,
and the amount of precision needed for the output actions.

In considering the criteria for the system definition in the next Chapter, the

advantages and Iimitations of a huzy controller were considered. Defuzzification methods

covered in this Chapter included COA, MOM and the singleton mcthod. The dinerences
Chapter 3: Fuzzy Logic Control

between these methods have a significant impact when considering an efficient MPU

implementation.
Cbapter 4: System Definition

CHAPTER
4
SYSTEMDEFINITION
OF THE ~ Z Z SEEDING
Y DEPTH
CONTROLLER

In this Chapter, the basis for the hypothesis that a hizzy logic controller is suitable

for use in controlîing the depth of seeding of a one-way discer seeder is developed. As

discussed in Chapter 2, the main methods of controlling seed depth are manual,

mechanical, elecuical over hydraulic limit switching, and computer-based controllers

using conventional control laws. In Section 4.1, the results of cesearchers that have

investigated these methods are presented. This is foiiowed by a discussion of the main

attributes of each method that has been investigated, as well as the attributes of funy logic

control. The criteria for a system to investigate the suitability of hizty logic control for the

control of the seeding depth of a one-way discer seeder is developed in Section 4.2. A

discussion of the spexifications of the hardware and software to conduct the research, is

given in Section 4.3. A discussion of the choices for hardware and software

implementation will aiso be given hcre.

4.1 Resuits of Seediag Dopth Studies


The problem of correctly positioning the seeds of cereal and oilseed crops beneath

the surface (and on the surface, in the case of seeding with granular appücators and

aircraft) of prairie fields has been a topic of study for decades NuAr391.
Chapter 4: System Definition

Present methods of controlling seeding depth include the use of manual,

mechanical, and electrowchanical systems and techniques. These methods do not always

provide consistent depth accuracy, which may lead to seed placement at less than optimal

depths for vigorous crop emergence. This is especiaily mie for variable terrain conditions

and when using one-way discer seeders.

V i r d i y aIi one-way discer type seeding irnplements corne equipped from the

factory with a mechanical stop that is bolted at the desired position on the shaft of the

hydraulic ram that controls the depth of the implement. As this ooly provides a very rough

control of seed depth, most operaton h d that they s a m u t manuaUy adjushg depth by

actuating a hydraulic control lever. This can lead to great variation in depth, as the

operator must estimate the depth of seeding visually, someiimes obscured through dust

and at distances of up to 20 m. This can be very tiring for an operator when conditions are

such that constant adjusanent is necessary. Errors increase under conditions of varying

soi1 moisture, texhue, and varying draft loads due to changes in the weight of the

implement as the seed empties out of the hoppers.

A number of commercial seeding depth controllers have k e n made available to

overcome the deficiencies of manual control. These controllers utilize mechanical or

elecuomechanicai PI, PD, and Pm type control. Even with these systems, however,
problems have been encountered with lack of accuracy, as weii as oscillations about the

depth set point. Seeding depth variations of 1.27 cm to 4.45 cm (0.5 to 1.75 inches) have

k e n observed [MoGegSa]. This is due to the noniinear nature of controllhg seed depth-in

a PD-type controller, for example, the transfer fùnction must take into account each
Chapter 4: System Definition

necessary chaage in the error s u m scaiing and control change as field conditions vary. This

leads to a cornplicated equation that can be quite unwieldy to incorporate into aa

electromechanical system, and virtuaiiy impossible to apply to a purely mechanical

controiier at a reasonable cost.

Fig. 4.1. View of tandem discers h m the tractor cab.

It has also beea shown that it is possible to maintain average seeding depths to

within a 2 cm range by using microcornputer control utiliùng conventional control laws

[Dyck75]. However, as these methods of depth monitoring and control have increased

seeding accuracy, so too have problems with complexity of operation for the operator and

persistent problems with overshooting the control set point. They also do not incorporate

the human operator's ability to adjust to changing field conditions [Dyck75]. New

digitaily-controueduni& have eliminated Som of the overshoot problems mtt911 but still

require the operator to adjust gain and daxnping factors (for example, 15 dinerent settings

on the Senstek DC-3)[Sens89].


Chaptcr 4: System Definition

Modehg a conventional controlier to mat varieci input States has been a

persistent challenge. No mathematical mode1 of a conventional seeding depth controller

was found in the literature. As funy logic control has been effective in contrd problems

where nonlinear inputs characterize the system, this approach is k i n g investigated to

determine how well it solves the problems encountered with cunent conventional manual

and electronic systems, since seeding depth control is a nonlinear coatrol problem.

4.2 System Definition Criteria


The type of control needed for seeding depth is based on two variables: the depth
at the present t h e as compared to the set point, and the rate of this error change. For a

conventionai controiler, the error aione would be enough to formulate a control aigorithm,

while more complicated cornputer-controlled depth control units would use change ia

error with variable gain adjustments.

The fùzzy controller developed here would most resemble a PI-type of


conventional controlier. This means that the f h z y if-then d e s describe the relationship

between the change in control (output) and the error and change in enor (inputs). For the

purposes of this research, the procedures to be used here include an overview of the

mechanics of the process to be controiied, generation of various hizzy control algorithms

for simulation, simulation in FIDE, Manifold Editor and Mathcad, testing on a lab bench,

and testing in the field. A labolatory test fixture with a microcontrolier evaluation board

was used for software and hardware development. For field testing, a proof of concept
control system was built for testing the conml algorithms in the field.
Chapter 4: System Definition

When devising the system to be tested, it becarne clear that a number of

requirements had to be met In order that the system provide reliable data, a number of

criteria had to k met in the design and construction of a l l hardware.

The controller be of sufncient speed and memory capacity to operate as a


Mamdani - type fuay logic controller.

The entire system be designed to provide sunicient eleceical noise immun@

in order that all meanirements are accurate aad reptoducible.

That a l l mechanical components, includhg sensors, be free fiom excessive

variation in accuracy.

The controiler be easily reprograrnmed in the laboratory and field.


AU electronic components be sufnciently protected hsurges and
fluctuations in voltage levels of the tractor electrical system.

The ground detection sensor be sensitive enough to d o w operation within


the minimum error defined for accurate seeding.

The conuolier MPU operate fast enough to ailow for a l l necessary calculations
and operations to occur and still have a seasor sampling rate fast enough to

prevent aliasing.

The hydrauiic valve have sufticient bandwidth to raise and lower a disc type
seeding implement as steps as small or large as necessary, with sufficient speed

to keep seeded depth at optimum.

The rate of oil flow of the hydrauiic valve must k variable to diow NIuse of

the huzy logic control capabilities of both direction and speed.


Chapter 4: System Definition

10. The system must have a means of 1ogg.gdata in order that algorithm

operation and efficiency can be ptefisely measured.

11. The tractor mounted controlier m m not impede the safe operation of the

tractor whiie operating pefiomiance and other measurements are made.

Therefore, it must easily fit in the cab, with an interface that is easily viewed

and operated.

4.3 Seeding Depth Control System Hardware


A complete seeding depth conml system has four basic parts: the signal processorl

control (or simply controller) module, depth sensing module, soleaoid valve module, and

power supply module. For the field data collection unit, al1 the electronics of these

modules are protected in a single shielded aluminum box that is operated in the cab of the

tractor. Information about the depth in the f o m of variable DC signals are sampled fiom

depth senson, through the sensor module. An analog conaol signal is generated which

controls an electrohydrauiic solenoid valve through the hydrauiic control module.

The controuer module includes all controller memory, interfaces to other modules,
operator user interfaces, and the CPU which conducts the computation functions. The

controller has been designed so <hat it c m display information for the operator while

aiiowing the operator to control normal operating and calibration huictions. The controller

dso cornes equipped with suitable interfaces for gathering sensor input information,

transmitting control signal information to the hybuiic control module and to an extemal

PC logger through a serial intecface.


Cbapter4: System Definition

The computational role of the controiler is to compare the input signais from the
depth sensors to a set point, and calculate an appropriate contml signal to correct any

ciifference in an optimal way. The decision about the type of microcontroller used was

based on a number of criteria, which include

- sunicient addressed memory capacity to be able to store the necessary cornputer


code;

- sufficient speed to d o w for at least one samplhg every 6 inches in the field, at a
speed of 6 miles per hour;

- as many of the necessary peripherals as possible, in order to reduce chip count,


which would result in higher reliability and lowered complexity (important when

debugg*g);

- adequate monitors and compilers to be able to write, compile and debug assembly
code effectively;and

- the availability of an evaluation board for laboratory testing.

MPUs (micropmcessor units) are VLSI chips that include not ody a CPU core for

computations, but also have on-chip modules for such fuactions as y0,RAM, ROM,

EPROM or static RAM memory, pulse wide modulation module(s). A D converten. There
are a very large number of chips available fiom a number of vendors with variations of

these features, with the major mes considered for this work. Some of these include

- Motorola MC68HC11,with &bit CPU, y0,ND'S. Runs at 2 MNz,and has less


addressable memory space.
Cbapter 4: System Definition

- Motorola MC68HCO5, with %bit CPU,U0,AR)'s. Very s m d addressable


memory space, and nuis at only 2 M H i .

- Texas l n s m e n t s TMS320 DSP series, with very fast operation for DSP
fiuictions, with II0 and extemal ND'S. Evaluation board version not readily

available, and not as weil suited to controiler functions with less Il0 ports.

In order that it meet a i l these cequirements, the controiier is based upon the

Motorola MC68HC16 microcornputer unit (MPU), with on-board analog-tdgital

converters, memory, and a 6805-based microprocessor. This MPU ruas at a speed of

16.78 MHz, which has proven to be adequate to conduct a i l computations and hinctions

fast enough to provide a sufficient sampling rate of 23 times per second.

Power Supply Module


Power Protection and Conditionhg
I I I

Fig. 4.2. System block diagram-seedingdepth controiier.


Chapter 4: Systern Definiaon

The depth sensor unit used is a simple novel design, produchg a DC voltage signai

proportional to the height of the seeder fiame above the ground. A second sensor monitors

the position of the discs relative to the fiame..

Highiy linear potentiometen convert the angle variations of the two sensor

assemblies hto voltage signals. As it is difficult to miiintain high accuracy with one-way

discer seeders, the sensors were selected to meet this worst-case scenario.

A gauge wheel used in the sensor uses a wide, low-pressure tire designed to ride

on the soil regardiess of the soil consistency. This method should also be unaected by the

varying actual height profile of a zero-tillage stubble field surface and to moderate field

trash (straw), both of which are read by ultrasonic sensors [GKWDl 1a1.

The hydraulic control module is the interface and buffer between the 5 V control
module and the duai 12 V hydrauiic solenoid valves. This module also serves to convert

the output PWM signal nom the controlier to two opposite signals, one for each solenoid

valve. A proportional hydraulic valve is the best choice for this application, as it is capable

of both variable rates of oil flow through the main spool and fast enough actuation in

either direction for this application.

The electrohydrauiic solenoid valves control the height of the seeding implement.

They are driven by opposing signals fiom the hydraulic control module: one which forces

the main hydraulic spool to produce a positive hydrauüc flow in order to move the

hydraulic ram piston in one direction, and the other to d o w oil to drain fiom the opposite

side of the piston of the hydraulic ram,thus allowing the piston to move. The signals can

be reversed to move the hydraulic ram piston in the opposite direction, or equalized to
Chapter 4: System Definition

keep the piston in place. A small, constant cüther signal was imparted on the main spool at

128 Iiz. This is required in these types of proportionai valves, as it maintaias an oii füm on

aii moving parts, reducing spool Wear aud improving reaction tirne.

4.4 SSeedhig Depth Contml System Software


The software design requirements are based upoa the requirements for the fuay

logic controller and the practical requirements of this research.

1. The operator must be able to calibrate and control the fuuy logic controiler,

2. The operator must be able to log data to v e w results.

3. The interface must also be as simple as possible in order to prevent mistalces or

pose a safety hazard by distracting the operator.

4. The fuzzy logic algorithm must provide for a target accuracy of 1cm.

The software flow is given in Fig. 4.4. Once the controller has k e n initialized it
then checks for any operator input. This is an intempt-driven routine, in that if a keypress

has been detected. the seed depth control operations in the main flow of the code is

temporarily suspended in order to execute the operator's comma~d.The operations that

are controiied by the operator include the cdibration routines. raising and iowering of the

discs, measuring units and depth control seniags.

Once past the keypress detection stage. the controuer proceeds to the sampling

routine. On the discer seeder, there are two sensors, one on the disc a m and one on the

depth sensor in the fkont. Both sensors are sampled, and the emr calculated based on the

distance from the desired seeding depth set point.


Chapter 4: System Definition

In the emr conversion stage, the nsdt is convened to a form suitable for use in

the fiiw logic control algorithm and the depth display algorithm. The units used in these
calcuiations are in thousandths of an inch, as this provides the best combination of

roundoff error reduction and computational efficiency for later operations.

Once the error has been caiculated, converted and store& the fuzzy control

algorithm reads the error h m the c m n t sensor readings and the reading from the 7th

previous sampling instance to put through the fuuy inference engine. A decision value is

determined, and passed on the hydraulic control routine.

The hydraulic control routine cakes the value form the fuzzy decision, and scales it

appropnately based on the type of hydraulic valve king controiied. It is then converted to

a pulse width modulated (PWM) signal, h m the PWMA port on the MPU.

The value of the current depth is read nom the registers storing the converted

depth sensor values and displayed in the LCD screen for the operator. The uni& can be
either imperid or metrïc, depending on which choice is made by the operator.

Finally, data fiom the sensors, error, change in error and hizzy decision is

convexted to ao RS232 signal and transmïtted to a PC laptop sewing as a logger. The data

can then be analyzed to determine how well the process is working. Once this operation is

completed, the program loops back to the keypress detection routine to begin the entire

process over again.

4.5 Chapter Ovemien

The o p e r a ~ and
g construction requirements for the fuzzy seeding depth controuer

were given in this Chapter. These requirements are the result of the necessity for a certain
Chapter 4: System Definition

degree of accuracy over a variety of soi1and topographical conditions. Results of

experiments explained in the literature showed the strengths and limitations of different

seeding systems and control methods. Roblems with cumnt systems were considered,

with an eye to setting system specitications that meet or exceed the accuracy which can be

gained using colluaercialiy availabie equipment and control philosophies. The primary

objectives were the ehination of excessive oscillation while maintainhg as much

simplicity in the controllerprogramcode and hydraulic system as possible, and maintaiaing

depth to at least 2 cm.

Once the main fiiactional criteria were established, M e r defition of the

hardware and software was the next step. The choice of the MC68HC16Zl MPU was

justified by its capabilitiesto meet a l l the necessary I/O. memory, availability and processor

speed requirements. The choice of a proportional hydraulic valve offers the system a robust

control actuator that is compatible with the variable output gain needed in this

implementation of hizzy control. The depth sensors met the cnteria for accuracy, with noise

suppression maintained by shielded cable and differential inputs. FinaiIy, the flow of the

software code actions to tie ali these hardware components and the fuay control algorithm

together was defined. Most of the code is used in measuring the sensor positions,

calibration, processing the input signals and displaying the depth on the LCD.

With al1 of the major hardwan criteria defmed, and hardware types chosen ia order

to meet or exceed these criteria, the hiuy depth conml system can now be described in

detaii. In Chapter 5, the controiler modular hardware design is described, based on the

general requirementsjustified in this Chapter.


CEAPTER
5
DETAILED DESIGNOF
HARDWARE
-
THE Fuzm LOGIC BASEDDEPTHCONTROLLER

The systern descriid here has been constructed and is being testai on a one-way

discer type seeding implement There were two versions of this system built: a

preliminary version built with the MC68HC16ZlEVB evaluation board h m Motornia,

and a field test unit for operathg h m a tractor to log pertinent controiler state data in the

field for later evaiuation.

The seeding depth contml system description will be by modules, as described in

the previous Chapter. Section 5.1 wiii cover details relevant to the controiier module, 5.2

wiii describe the depth sensor module, with Section 5.3 c o v e ~ g


the hydraulic control

module. The power supply and conditionhg module wili be explained in Section 5.4.

Fig. 5.1. Lab test unit.

-52-
Cbapter 5: Detalled EIardware Design

The hatdwm descriptions in sections 5.1 to 5.3 will be bised upon the basic

operations and components of the controiler, with Section 5.4 also covering noise and

EMT considerations thaî apply to the p w e r supply and signai cabks.

Fig. 5 2 Field test and data logging unit,

Conmuer Module Power Supply Hydraulic Control


Module Module

Fig. 5.3. Coaaoller main modules.


Côaptet 5: Detailed Hardware Design

Connecter for -
Sensors

Solenoid

,/'
1,'
SA Fuse Holde

Fig. 5.4. Main control box connectors.

5.1 The ControUer Module


The controiler iacludes the hardware involved in the processing of the input signal

to produce the desired output contml signal. This includes analog to digitai ( A D )

conversion of the input signal, cornparison of tbis signal to preset parameters in software,

and the fuuy Iogic decision process that controls a pulse width moddated output signal.

This module also serves as the openitor interface, so is located in the tractor cab next to

the operator. It has a numeric keypad for input of calibratioa and control point information

fiom the operator, and an LCD digital display that serves as a visual inte~ace(see Fig.

5.3).
Cbapter 5: Detaiied Hardware Design

The microprocessor unit employed in this application is the Motorola


MC68HC1621 (referred henafter as the HC16). The HC16 is a microcontroller that is
suited to this task because of the suite of on-chip features and a dock speed of 16.78 W .

Features utilized in the fuzzy seeding depth contmlier include the A/D converters.

on-chip generai purpose tumr (GPT), queued serial module (QSM), and 1 KB of battery-

+=
backed static RAM.

Port GP

Queued
Port QS Seriai

J-
Control

Fig. 5.5. Block Diagram of the MC68HCl6Zl showing main mobiles and ports.

The A/D converters are selectable between 8 or 10 bit, with &bit conversions
king used in this application. This is because it provides adequate accuracy in monitoring

the depth sensors, while enabiing the 8-bit A and B registers to be used in the CPU16. This

results in a reduction in complexity in pmgramming and aliows two bytes to be used for
Cbapter 5: Detaiied Hardware Design

data, not 3. They are successive approximation (SA) type ND converters, with a sample

and hold ( S m unit to increase the effective aperture time -911. As the N D module
c a . nia at up to 2.1 MHz,an 8-bit conversion only requhs 9 rnicmseconds (ms)to
cornplete a conversion.

A.nalog/A/D Refemce EPR0Mlml.M Serial Comm


LC Filters SelectionJumper Interface

EPROMs:

Even Byte
Clock
Circuitry
ûdd Byte

MC68HC16Zl MPU Disc Sensor B S e r

Fig. 5.6. Controiler moduk main componeats.

The QSM is used to communicate between the HC16 and a PC in order to log test
results. The QSM is configureci for 9600 baud fidi duplex asyncbFonous coinmunication in

this mode. Serial communications signais fiom the QSM are converted to RS-232 levels

by a Motorola 145450 serial interface. This chip was chosen over the more common 1488

and 1489 chip combination in order to reduce the part count, and eliminate the necessity

for plus and minus 13 V supplies. The 145450 uses four 10 uF electrolytic capacitors in a
Chaptet 5: Dttailed Hardware Design

charge pump circuit to produce its own plus and minus 10 V supplies. This is usehil for

the field test unit, as this reduces the size of the boards and box needed to do the control

and data logging. Likewise, whenever the necessary fiinctions can be implemented with

fewer parts, there are less chances for failures in initial &bugag and in operation.

On-chip static RAM is used to store program variables, such as the caiibration

values. These variables are maiataiwd by a lithium 3 V battery while the unit is in a

battery backup standby mode when the main power is switched off. As a i l the registers in

the HC 16 are memory-mapped, there are no other special addressing procedures needed to

access this memory other than to ensure the correct base address of the 64 KB page is in

the K register More reading or writing these locations.

In order that there wouid be enough room around the HC16 chip to use wire

wrapping in the construction of the field unit, a single sided PC board was made. This

enabled the HC16 to be securely ddered in place using surface mount technology, while

allowing the cntical clock circWtry to be assembled on the same board. There are several

advantages to having the clock crystal and capacitors mounted directly to the PC board:

the distance to the HC16 pins is minimized; problems due to stray capacitance of wire

wrap pins affecthg the clock waveform are eliminated; and puttir~gthe crysial on the PC

board ailows for a foii ground plane to be extended under the crystai, thus M e r ensuring

stability of the output waveform.

The HC16 is also capable of addnssing up to 1MB of program and data space, of

which 32 KB of program space are used in this application. Two fast (70 os) 256K

EPROMS or 70 ns 256K battely-backed RAM acting as pseudo-ROM can be used in the


Chapter 5: Dctailed Hardware Design

controller. There is a jumper block that sets the correct addressing, chip select and chip

enable pins for the appropriate type of memory configuration in use. The ability to use

battery-backed R A .is very advaatageous for 6eld use. The two RAM chips are each

powered by a Dallas Semiconductor SmartSocket This way, the chips c m be programmed

in the lab bench controller setup, which is co~ectedto a PC running the HC 16 assembler

(MASMl6) and control program (EVB16). Once the chips are programed, the whole

system is powered dom, and the chips cm then be removed and placed into the memory

sockets of the tractor unit for in-field testing. This way, it is not necessary to have an

EPROM burner and a large collection of EPROMs and an EPROM eraser on hand, so

quick changes to the code can be made easiiy on the spot

W
lth
in the GPT are two pulse width modulation units. One of these

(PWMA) is used to produce the output signai for controliing the hydraulic valve. The
output from PWMA is a periodic square wavefonn set to 128 Hz,which is optimal for the

Rexroth proportional valve king used in this research. The duty cycle of the waveform is

then modified ia software to cause the appropriate valve action.

The keyboard and LCD display are both mounted on the top of the controller box

for easy access by the operator. Both are socketed in order that they cm be easiiy removed

if it is necessary to repair connections or add co~ectionsor parts underneath them later. A

plexiglass cover protects the LCD display.

The keypad is a hexadecimal keypad, amnged in a 4 X 4 matrix for operator input.


Key press detection is by scanning rows and columns via the 8 Il0 lines of control port F,
as shown in Fig. 5.4. When a keypress is detected, an interrupt routine is triggered in
Chapter 5: Detaïleci Hardware Design

software that is controiled by the GPT. This software subrouthe will then intermittently

resample the lioe for 10 milliseconcis. This enables the microcontrolier to determine

whether a detecwl key press was due to electncai intecference (noise) or whether the

event was a reai keypress by the operator. This serves as a software-based key debounce

function. W u p resistors on each line maintain a steady 5 V Ievel on the port pins until

puiled low by a keypress.

Port F

Fig. 5.7. Keypad connections to Port F of MC68HCl621.

A ldsegment LCD display serves as the visual display interface for the operator.

The LCD has an adjusmient for contrast, and is set for maximum visibility by a

potentiometcr inside the controiier unit. Instructions are supplied to the operator via the

LCD in naturai language to facilitate caiibration and operation. Resent depth is displayed
while in normal seed depth control operation. The unit used is the single h e , 16 character

Optrex DMC40401 which bas its own built-in control logic and osciilator, thus requiring

no extemal parts. Custom charactea could be programmed and stored into display

memory,such as mows indicating depth correction signals.


Cbapter 5: Detaiied Hardware Design

5.2 The Depth Seasor Malule


The de# sensor module includes the sensor mechanism mounted on the discer

(see Fig. 5.5). the shieldeâ cabks running h m the discet to the tractor cab. and the two
differential sensor intefiaces that produce the controller A D input signals, The h n t depth

sensor used here is a simple, novel design that produces a varying DC signal based on the

angle of a gauge arm h m the soil surf" to the d i s a r h u e , A second sensor signai

bdicates the angle of the d i s gang to the implement fiame. Highly iinear, cahirated

potentiometers convert these angles to voltage signais. Noise suppression is achieved by

the use of a differential input buffer, and shielâed cabhg gmm&d to the controiler box.

Fig. 5.8. Front sensor gauge wheei assembly.

The novel ground-sensing unit used in the design is key to obtaining diable depth
readings. A gauge wheel used in the sensor uses a low pressure tire designed to ride on the

soii surface, regardless of the implement weight or soi1 consistency. The adjustable weight

of the gauge wheel allows the operator to prevent excessive sinking in soft soil. Simiiarly,

the use of a low-pressure tire to sense ground level serves to dampen out insigniscant

topographicai features, such as s d fuwws, whiie stül giviag diable readings in fields

with standing stubble. In modehg this system, the sensor assembly itself serves to act as

an integrator and a low pass filter. This is particularly important foc minimum and zero
Chpter 5: Detailed Hardware Design

mage fields, where straw and stubble are not left intact in order to minimize soi1 erosion.

This dampening feanin, combiDed with analysis of the rate of change in depth by the

fuay logic aigorithm. nIters out the effects of sudden changes in depth reading caused by

large soi1 clods or b o w s . These features provide this sensor design with a distinct

accuracy advantage over ultrasonic sensors and other types of mechanical sensors

presently in common use, although it could be argued that low-pass filtering of the signals

from these units can be done in software.

The sensors themselves are highly linear (< 0.5% variation across 85 degrees of
travel) units that are sealed from moisture and dia. They employ robust rnounting flanges,

and employ spring pressure to ensure that they always are in contact with the rnachined

sensor linkage. Cabling is with dconductor, 100% shielded cable. The shielding is

grounded at the tractor, and is not comected to the gound wire on the sensoa, in order to

prevent a ground loop. Cables are mounted on the seeding implement in an elevated ring,

to prevent damage fiom dmgging on the ground. An Amphenol-type screw connector is

used to securely fasten the cable to the controller box and provide grounded shielding at

the cable to connector interface.

Each of the senson are buf5ered by TMS4066 operational amplifiers. This serves

to protect the HC16 A/D converter inputs fiom any high voltage spikes that may be

induced in the sensor cabling. The operational ampMers aiso serve a noise eiïmination

function, as they employ differential inputs. This technique of noise suppression has k e n

shown to eliminate noise to about 60 dB. These op amps are aiso unique in that they

operate as single-supply, rail-to-rail differential amplifiers. The advantage of this is that no


Cbapter 5: Detailed Hardware Design

extra negative power supply is needed to run the op amps. The rail-to-rail feahire also

means that the op amp inputs are sensitive right acnws the m e r voltage level, so can

detect signas h m O to 5 This eliminates the need for additional analog scaling

components, thus reducing part comt and eliminating the extra variables of temperature

and age effects on the input scaling io the op amp differential inputs.

53 The Hydradc ContrdMd&


An electrohydrauiic proportional valve adjusts the height of the seeding implement

(see Fig. 5.7). It is dnven by a 12 V pulse width moduiated signal in order to contml both

the speed a d direction of disc depth adjustment (Fig. 5.6).

Inverting Butfer FET Switches Protection Diodes

Fig. 5.9. Hydraulic conml subsystem components.

This module consists of power field effect transistor (FET)switches, protection

diodes, logic circuitry to divide the puise modulated signal h m the PWM uni& on the

microcontroiler, and a proportional hydraulic valve controiied by two solenoids. The

HC7414 CMOS inverting b e e r protect the control module circuitry h m any elecaical

shorts or power spikes in the 12 volt section of the hydraulic conml module. Protection
Chapier 5: Detailed Hardware Design

diodes ailow back EMF in the inductors of the hydrauiic valve solenoids to bypass the

FETs when the torrent is cut by the switch logic.

Valve Solenoids Secondary Valve Body Main Spool Body

Fig. 5.10. Hydraulic proportional valve.

The hydraulic solenoid valves operate at a fiequency of 128 Hz. This produces a

dither on the main valve control spool that significantly increases its response speed over a

valve that must operate h m a state of rest At a duty cycle of M%,an equal force is

imparted on the main spool in both directions. This results in no net oii flow to the discer's

iifi cylinder through either of the main spool's ports. However, as that duty cycle changes,

there is a proportional change in the flow of oil fiom the valve to the hydrauiic cylinder

controlling the implement depth. Therefore, by adjusting the control signal duty cycle

above or below 50%.the speed and direction of oil flow to the cylinder is controlled.

The cable to the solonoid valves is a 4-stranded, 100%shielded cable with the

shielding grounded to the controiler box. In order to prevent ground Ioops, the grounded
Chapter 5: Detailed Hardware Design

shielding is not comected to the ground of the solonoid control wires. The cables are

comected to the controuer with and Amphenol-type steel s m w comector that is

grounded to shield the solonoid control wiring where is meets the connector. The solonoid

end of the cable is comected to a plastic plug which is provided by Rexroth and custom

designed to fit over thme solenoid lugs and bolt into place.

SA Electricai Noise and EMI Supptessîon


Constnicting electronic equipment using microprocessors for industrial and

agricultural environments poses unique challenges. Agricultural tractors pose a unique

hazard to electroaic devices, as EMI sources as varied as the uactor electncal system,

wireless communication devices and high power overhead liaes may a i l be present at the

same time in worst-case situations. This is especidy tme for systems such as that used in

this resewh, where cables to senson also act as very good antennas!

Precautioas wen also implemeated to protect the controiler unit from power

fluctuations within the tractor electricai system. For example, in a load dump, in which the

comection between the batteries and the charging system is suddenly severed while the

motor is running and the electrical system is othemise functioning normaily, voltage

spikes have been recorded to over 400 volts Man94J.

The controlier box itself serves as an RFI shield*It is constructed of aiuminwn,


with only minimal openings where needed to provide user and cable interfaces. To

rninimize the amount of cable withia the contro11er box that may cany noise fiom the

tractor electrical system, shielded h e s to the power supply module only pass beside the
Chapter 5: Decailed Hardware Design

hydrauüc control module, aad do aot pass through the control module. The power supp1y

module is also separated h m the adjacent moduks by aluminum shielding.

5.5 Power Suppiy Md&


The 12 V power cable h m the pactor electrical system comects directly to a 5 A

hise, then to a 24 V metal oxide varistor (MOV) that is designed to take any voltage spikes

above 24 V to ground Likewise, a 500 mH ferrite COR choke and a 300 mi?electrolytic

capacitor serves as a low-pass LC circuit to resist large, low-hequency signals or spikes.

This is foiiowed by a 1 0 mF electrolytic capacitor, to m e r take higher kquencies to

ground.

MOV Ferrite Core hductor Filter Capacitors


'a- -

Voltage Regulator

Fig. 5.1 1. Power Suppiy Module.

In the voltage reguiator circuit there are two 10 mF capaciton, which also act as

filters. A 0.01 mF capacitor also acts to take even higher fiequency signals to grouud.

Finally, regulated SV power to the controiier module is supplkd via shielded cables which

pass over the aluminum shielding to supply the module. 12 V power to the hydraulic

connol module is via a shielded cable which passes over the shielding between the power

supply module and the hydraulic control module.


Chapter 5: Derailed Hardware Design

Liberai use of decoupling capacitors and several inductors throughout the

controiler module keep voltage variations to a minimum. Special attention is paid to the

memoty supply pins and the N D contmller power and reference pins. Decoupling

capacitors are especially important considering that the rnajority of parts in the controiler

module were buiit using wire-wrap construction. W


1h the HC16 dock speed at 16.78
t

MHz, this is just below the generally accepted Mt of 20 MHz for wire-wrapped circuits.

There is aiso an alurninurn shield between the hydraulic control module and the controIler

module to nduce noise effects that may occur due to the back EMF in the solonoid cables

generated by the collapsing fields around the coils in the valve solenoids. Ali of the

modules were built as small as possible to minimize the length of connecting wires.

5.6 Chapter Overview


When reading the detailed hardware design description, it is not immediately

apparent that the hardware choices used in this study are the result of extensive searches

for the appropriate components. For example, there are hundreds of types of

potentiometers in a wide array of packages available, but very few have the combined

capabilities of king dustproof, able to be securely mounted, and a high degree of liaearity.

Once all the suitable testing hardware was found, the software was designed and

Mtten. Hardware characteristics were taken into account in this process, including the

speed and zero position of the proportional valve main spool, and the linearity of the

sensors. In the next Chapter, this s o h a r e design is described in detail.


Chapter 6: Software Design

Software design in this Chapter describes the fuzzy logic controuer and how the

most important software twls associated with this research were used. The fuzzy logic

controiier itself is written in the &bit MC68HC16 assembler code, with portions of the

fuzzy logic routine written in &bit MC68HCll assembler code. This format is M y

compatible with the MC68HC16Zl. Other programs written for the purpose of this

research. but not directly used in the formation of the hizzy logic controller code, are

discussed in Chapter 7, System Implementation. Source code of ail software presented in

this thesis can be found in the appropriate appendices.

This Chapter is presented in three sections, each covering huictions occurring

before, during, and after fuuy decision routines. These sections are detailed descriptions

of the block diagram components and pNnary system functions given in Chapter 4. Each

subsection describes a major subroutine, in the order they are executed in the

microcontrolier, The subsections are:

1. Initiakation - Initialize MPU modules and other registers.

2. CHECK-KEYS - Detect a keyprrss and identm key, execute key function.

-
3. SAMPLE Sample the sensors.

4. ERROR-CONVERT - Convert the sensor signds to a usable form.


Chapter 6: Software Design

-
5. ERROR-BUFFER Store c u m n t enor. read emr 7 samples previously.

-
6. FUZZYrrST Fiazy contml decision mutine.

7. HYD-CONT - Send the conml signal to the hydraulic valve.


-
8. DISPLAY-DEFTH Display depth on the LCD.

9. SEND-DATA - Send data to the PC data logger computer.


Section 6.1 describes the program and micmcontroiler initiakation, calibration

and data preparation for the funy logic decision routines. Section 6.2 presents the fuzsr

routines, while 6.3 covers the hydraulic control, data logging and LCD display functioas.

A detailed flow chart of program execution is given in Appendix B.

6.1 Initisüzatioa and Data Preparation Routines

6.1.1 Initiulizution

Each of the modules of the HC16 are controlied by memory-mapped registen that

must have initial values written to them in order to perfomi in the appropriate marner

Mot092b].

The nrSt module initiaüzed is the SIM (system integration module), controlling

bus and software watchdogs, configuration parameters for the HC16,system clock, system

address and data buses, chip selects and a system test block.

The systern dock provides timing signals to all operations in the MPU. In the
MPU configuration used for this rcsearch, the clock is driven by an external32.768 kHz

watch crystal. This in turn controis the speed of an intemal oscillator (PLL,or phase lock

Ioop). The high fiequencyoutput fiom the P U is divided down by a dividerlprescaler and

the output cornpared to the phase of the input crystal frequency. Once the PLL locks on
Cbapter 6: Software Design

this signal. the HC16 boots up. The speed of the HC16 is determined by the value passed

to a divide by two prescaler bit, a 3-bit pfescaler in the PLL feedback divider. and a &bit

moduio 64 down cornter. System speed with a 32.768 ItHz crystal can be set h m as low

as 4 Hz, to vaiws in excess ofthe maximum rated operating fkequency of 16.78 MHz.The

HC16 is set at this maximum allowable speed by the initiakation routine.

The modules are mapped to a 4 Kilobyte block in the MPU. The location of this
block is set by the module mapping bit ia the S M module configuration register. This bit

is set at initiaikation so that the addresses are spread w i t h the range fiom SFFFOOO to

SFFFFFF.
The the SWE (software watchdog enable) is also turned off to prevent immediate

software interruption by the watchdog. This is a timing circuit that, if not disabled would

continuaiiy interrupt the operation of the CPU if the software watchdog timer location was

not written to within a specined time.

Initial values for the CPU (centrai processing unit) also are set. The memory page

registen are set so that the code wiil start at the correct memory page base location. Each

memory page on the HC16 is 64 Kilobytes.

The SRAM (stmdby RAM module) consists of 1 Kilobyte of fast static RAM and
a control register block. This memory is where calibration and scahg values are stored, as

they can be maintained by a backup battery when the MPU powers dom. This memory

can also be mapped anywhere within the entire HC16 memory space (as long as it does

not overlap any module régisters or the bootup and intempt locations nom $00 - $200). It

is initialized by sening it to the base location $10000.


Chapter 6: Software Design

The QSM (queued serial modnle) is initialized to be able to send and receive data

at 9600 baud. This module sen& and receives signals at 'Ml. levels. It is comected to the

MC l4S4O7 RS-232interface chip.

The ADC (analog to digital converter) module is enabled by Wnting to the


associated control repisters for ADC channels O and 1. CùanneI O is the input for the front,

or depth gauge wheel sensor, and ADCL is the input for the rear, or disc sensor.

GPT (general purpose timer) initiaibation values are written to the appropriate
control registers, setting the fiequency of PWMA to a rate of 128 Eh.The duty cycle of

this signal carries the information to the hydraulic solenoid valves, while the fiequency

remains constant throughout operation.

Initial values for controiler operation variables are set once all the modules are

enabled. These include calculation constants for the theta correction in the sensors, rough

sensor zero positions, sensor mode setthgs, and rough calibration factors such as seeding

depth setpoint and raised height for lifting out of the ground. Initialization subroutines that

enable the appropriate I/0 ports for the LCD display and keypad are also m.

Once the HC16 modules and calculation values have completed initialization, the

huzy logic controller code enters the main software operation hop.

6.1.2 CHECK-KEYS Routine


This code routine checks to see if a key has been pressed. If this is true, the key is

identified and the appropriate action is taken.


Chapter 6: Sofiware Design

Scan
Direction
of Rows

Scan
DiW * o n
of Columns

Fig. 6.1. Keypad scanning directions.

The keypad is scanned in this routine, on every loop of the main program. If a low

signal is detected on one of the lines of the keypad port (Pon F), the code immediately

branches to a key debounce subrouthe. Port F is s c a ~ e dagain in 10 m. to see if a

keypress (iow) signal is stili present If so, it is assumed that a key was pressed, (that the

first low signal detected was not caused by noise). The program then branches to a routine

to identify the key pressed. If the identification produces a jump to a subroutine, the HC16
then executes the appropriate function. These functions include calibration and control

routines for the fuzzy logic controiier.

Real

ldeal
,

Fig. 6.2. Actuaï and ideal signals fkom a switch, iiiustrating the need for a key debounce
routine.
Chapter 6: Software Design

Once the routine has finished, the program exits the CHECK-KEYS routine and

continues on to the SAMPLE routine.

Control and calibration submutines are eatered, dependhg on which key is

pressed. The fitnction of each keypress is explained in Chapter 7, System Implementation.

Caiibration subroutine structure wili be explained hem.

There are k e e major types of caliiration subroutines. The fim, and most simple

to implement in code, an operator set point value settings. These are the values for desired

display units (metric or imperid), sensor modes (both sensors or fiont only are used),

seeding depth and raised height. Setthg these are a simple matter of entering the numeric

values when prompted by the appropriate message on the LCD.

The second type of calibration setting includes values that are read from sensoa,
then directly stored to their respective locations in memory. This includes the setting for

the field "zero depth" position. No calculations occur in this setring; it is a straight "read -

-
and storet' operation.

The third type of calibration setting includes values that are detennined by reading
sensor positions, and using these in calculations to detennine the appropriate scaling and

conversion factors. These calibration subroutines include the sensor scaling factor and the

theta correction factor.

This scaling value WU be unique to each different combination of depth sensor

and seeding implement combination. Once it is set, it does not have to be updated unless

there is a change in the position (such as the location or rotational pitch) of sensors relative

to the implement they are mounted on. Therefore, this calibration should be repeated
Chapter 6: Software Design

anytime sensor mechanical mountings are remounted or any changes are made to the

sensor system, such as a change in gauge depth wheel tire pressure.

The scaling faftor is obtained by calculating the difference between the 6" height
position of the disks and the 0" (gromd level) position of the disks, and then dividing this

Merence into 6 to obtain sensor units per inch of mvel. These measurements are made

on a soiid, level sudace, such as on a concrete pad. It is critical that the suface be level

and ail measurements be as accurate as possible. as any error in this caiibration will results

in the same relative e m r throughout all depth sensing operations.

The theta correction factor is ais0 determined in this operation. It is necessary to

correct for this enor due to the rate of change of seasor angle per change in depth

becoming srnalier as the angle increases. The disc gang is raised so that the sensor M a g e

for the rear sensor is positioned in such a way that the connecting arm from the sensor and

the connecting ann to the discs are precisely 90 nom one another. The front sensor wheel

is also positioned so that the sensor connechg ann is precisely positioned 90 from the

sensor arm connecting the ground sensor. The positions of both senson are now stored as

the zero degree angle position.

By using %bit ADC conversion rather than 10bit, each degree of movement of the
sensors used here translate to a change in ADC reading of precisely $3. This is due to the

fact that in an 8-bit ADC,the range is fkom decimal O to 255. The total degrees of rotation

of the sensor type used in this research is 85. Thus?decimal 25985 = 3. It has also k e n

found that a variation of 1 unit of ADC measurement with the discer and sensor

combination used in this research was the equivalent of 14 units per inch around the zero
Chapter 6: Software Design

point, to about 12 unîts at the 3 inch &pth point This is sufficient to give the 0.1 inch

sensor accuracy des- for this controller. Using the 10-bit settkg for the AM3 would

provide ôner readings, as there wouid be decimal 12 units rather than 3 per degree.

However, baving to use 10 bits of accuracy would coaiplicate propmmbg, as the &bit

accumuiatoa A or B could not be w d independently with the ADC readings in the

controlier routines (such as conversion, data logging and memory management

operations).

Once the 90 sensor b g e positions are determined, the number of degrees of

rotation of the individual sensors nom this position is simply this dinerence divided by 3.

Therefore, the degrees of movement of the 6 inch positions fiom the 90 points of the

sensors is known. This gives the value of the opposite side of a right angle triangle (is

equal to 6 inches). Basic trigonometry gives the length of a hypotenuse equal to the length

of the opposite side divided by the sine of the opposite angle. Using this "opposite" value

(6 inches) and the angle fkom 90. the length of the hypotenuse is determined. This

hypotenuse length now becomes a constant for use in a l i other calculations.

Other depth values can then be determined by converting the sensor readings into

degrees, then converting the degrees rotation into sensor position above or below the

ground by applying the scaling factor obtained in the 6 inch calibration routine, and using

this to determine the length of the opposite side of a right angle triangle to get the depth

value. In order to prevent excessive roundoff e m r throughout the correction calculations,

the sensor values are converted to thousands of an inch in a 16-bit format This process

includes a hexadecimal to decimai base conversion subroutine.


Cbapter 6: Software Design

6.1.3 SAMPLE Routine


Each of the two semors are sampled in this subroutine. If the controller is in

normal operation mode,the signals are passed onto the next subroutine. If it is in a single

sensor mode,only the respective single sample is passed on.

The sensors are highly linear nsistive elements operathg by indicating the

position of a contact on a circular track In order to preserve accuracy in reading the sensor

positions, the theta correction factor is employed for all nadings. This works by taking the

sine of the angle from the 90 position of the sensor iinkage, where it is precisely 90 £tom

the sensor. In order to ensure maximum calculation speed, an 8-bit sine lookup table is

used, rather than calculating each valw by division. In the HC16,the sine table technique

takes 6 clock cycles to load the value. If sine had to be caiculated. it would take 34 cycles

to clear, load and scale the ADC reading (in degrees) and the value 1 into another

accumulator, then 24 more cycles to divide these two, and another 10 cycles to sale them

again, for a total of 56 clock cycles. This would have to be conducted twice every tirne

through the program, resulting in an unnecessary loss of 124 clock cycles per main

program execution. The only downside of using the sine table is that it takes up extra

EPROM memory, but with only about 10 Kilobytes used out of a total of 32 Kilobytes
available, this is not an issue. In this design, opthkations have been made for speed

whenever possible, as long as accuracy is aiso within specincations.

Initial conversion values for the theta correction subroutine are written to the

respective registers during controfler initiakation. This allows the operator to raise the

implemcnt for transport to the area of use. Once at the field, the operator then goes tbrough
Chapter 6: Software Design

a calibration routine that sets the ngisters with the correct conversion and setthg values

for the cunient soil conditions and desired depth.

6.1.4 ERROR-CONVERT Routine


Once the positions of the sensors are determined and corrected for theta error, the

error is converted fiom thousands of an inch to tenths. This facilitates the calculations that

will include only addition, subtraction, and maximum and minimum comparisons.

6.1.5 ERROR-BUFFER Routine


In this routine, the change in e m is detennined by taking the present error

reading and subtracting it fiom the error reading 7 samples previously. This equates to

about 112 a second, or the equivalent of one m e a of distance covered at 6 mph. This

value is written to the CHANGE-IN-ERROR variable for use in the next routine.

6.2 The Fuay ControI Subcoutine:


The hiuy control algorithm used here is a Mamdaai-type controller, based upon
the rnax-min composition. This type of fuuy controller has been appiied to a wide variety

of industrial processes since it was introduces 20 years ago CKipe90, Mura841. This

control strategy is based upon the experience of a human operator, who iinguisticaüy

describes the control actions as a set of heuristic decision d e s in the fonn of "if this

occurs. then do that" [KiMa77]. The resuit is that the conml algorithm incorporates the

"grayness" or 'Kuzyness" of natural human decision processes, where gradua1 changes

are perceived on a gradient rather than in terms of crisp absolutes.

The inputs to the funy control d e s include the error from the desired depth set

point, and the change in the error between the present and last sampling instances. This
Chapter 6: Sofiware Design

error change leads to differential control KGFï931. These proportional and differential

input signals should guarantee stability of the control system.

Linguistic variables descriibe the direction (either positive, P or negative, N), while

the size of the change is descnkd as small, S. medium, M and big, B (see Table 1). Rules

used in this fuzzy logic controiier are of the fonn:

IF ermr is PM and change in error is NS then the output is PM.


The fuzzy output variables are the desired speed and direction of change in seeding
depth. As for the f i inputs, these are described by means of a linguistic variable, for

ERROR, c
OUTPUT

, - Negative
N S - Small
1 - Positive
P M - Medium
B - Big
Fig. 6.3. Fuzzy d e s output table.

example, Positive Medium. This value is changed to an 8-bit numkr by def'uzzification.

Bot. Mamdani-type (utilizing wmbership fwictions) and singleton (center of gravity)

defuuincation methods an king consideced for accuracy and speed of execution.


Chapter 6: Software Design

6-2.1 FUZZYTEST Routine


The fuuy algorithm is based on the Mamdani fouy control algorithm.

Membership h c t i o n s were ocîginally determined by using Mathcad and a Microsoft

Wmdows graphics-based fuay logic simulation and analysis tool, FIDE (Fuz2y Merence

Development Engine) nom AptronUr. The different rnembership fuactions were set up and

nui through simulations.

Aithough fuzzy algorithms can easily be coded in a high-level Ianguage such as C,

FIDE speeds up development with increased accuracy by the use of several valuable

development tools. Each membership function can be viewed graphically, and quickiy

changed using the mouse. Likewise, FIDE instantiy generates the fwzy control surface for

any set of membenhip fûnctions and inputs. Once a given combination of membenhip

functions produce an acceptable gain level of monotonie control, a visual simulation can

be run with inputs nom either artincidy generated signals and actual recorded field data.

If, at this stage, the control looks like it will produce the appropriate results, FIDE can

immediately generate &bit (MC68HC11compatible) assembler code. This code c m then

be pasted into the controller code and compiled The code automaticaily takes into

account scaling factors for sensor inputs and the hydraulic control output signal. These

scaling factors are used to match the fuzzy output signal to the actuation speed

characteristics of the type of hydrauiic proportional valve used. Therefore, code is

produced quickly and accurately that can be tested in the field. Some setting up of the code

is necessary, such as naming variables and memory location redefinition, but this is trivial

compared to having to rewrite all fuuy membership function tables manually. Of course,
Chapter 6: Software Design

rnembership hctions can be modined by editing the tables. but it is much more

productive to modify only small part of the code in the field rather than having to remn aU

the simulations and repaste code for only minor variations.

In this routine, the fuay logic algorithm operates the four steps of determinhg a

control decision:

The input values ERROR and CHANGE-IN-ERROR are fuuined according

to the lookup tables generated nom the membership fûnctions in the FIDE

simulation. The degree of membenhip for each membershïp hnction is then

passed on the funy inference engine.

The fuuy values are evaluated according to the d e s . The DOF for each mie is

detennined.

The mies are aggregated, and the mies that apply are determined.
The hiuy decision fiom the mie analysis is defwzified. The algorithm uses

the singleton method of defuuification. Although this method is not as elegant

as the COA or MOM methods, it is much more efficient to code and execute in

assembler, and does provide sufficient 8-bit accuracy for this application.

Using the Mamdani max-min preposition is very conducive to the assembly code

mnemonics in microcontrollers, as these operations cm be conducted with only three main

steps: two register Ioad commands, and a cornparison for size.

For the MAX operation, the equivafent is a union operation. This operation is

given here in MC63HC16 assembler language.


Cbapter 6: Software Design

Assembler Commriad

ldaa ht-nunber

dab second-number

cba

bmi b-is-larger

mva result,of,max

rts

b-is-larger (titIe of the foUowing subrouMe)

movb result of- max 8

rts 12

This is a total of 44 clock cycles per MAX operation, or 7 X 44 = 308 cycles for

the 6rst group of MAX operations.

The MIN operation is equivalent to the intersection operation. It is given here in

MC68HC16 assembler language.

Command Cloek Cycles

ldaa first-nwnber 6

dab secondCnumber 6

cba 6

bpl a-is-larger 6

mua result-~f~xnin 8

rts 12

a-is-larger (title of the following subroutine)


Chapter 6: Software Design

movb result ,of'min 8

rts 12

This is a total of 44 clock cycles per MIN operation, or 7 x 44 = 308 cycles for the

first group of MAX operations.

At the end of this MIN operation, the resultîng fhzded value is then defuzzitied.

It is compared to the values for output, in this case, 4, and the two closest values are

averaged.

Fuuincation and defuzzitication of the values for each membenhip hinction is

very computation intensive uniess done with the aid of lookup tables. Without lookup

tables, individuai dopes would have to be calculated for each membership function-

trianguiar and trapezoidal membership huictions cm be handled by simple division, but

other hinctions can be quite complex. Of course, with look up tables, you trade accuracy

for speed. For the purpose of this nsearch, the accuracy using 8-bit lookup tables for the

f u z q inference engine is sufncient This matches the format of the data and the AID input

signal accuracy, which is 112 of the LSB.

The output range for the controller is between decimal 120 to 135 (CHECK). This
is due to the characteristics of the proportional valve used and the hydtaulic system of the

tractor used. The tractor used in testing was a Case International 7210 Magnum with a

closed center hydrauiic system. This type of system maintains constant pressure at ail

times, so WUprovide a consistent hydrauiic control response regardless of the demamis

on the system.
Chapter 6: SoftwareDesign

6.3 Hydrauiic, LCD Display and Data bg@g Routines

6.3.1 HYD-CONT Routine


Once a hiay decision has ken produced, the con& signal is sent to the pulse

width modulation unit A (PWMA)of the MPU. This modulates the duty cycle of a 128 Hz

signal that controls two solenoid valves that control the position of the main spool on a

proportional hydraulic vaive. By having a constant 128 Hz pulse on the main spool, a flow

of oil keeps the main spool moving. The motion is not enough to significantly change the

position of the hydraulic ram on the seeder, but is essential to keep valve response t h e at

an optimum level. The duty cycle of the two smaU solenoids that contml the main spool

are equal when the main spool is in the proper position. When the seed depth (disk

position) has to be changes, the spool must be moved off center by changing the duty

cycle of the tow s m d solenoid. This is done by changing the duty cycle of the signal from

P W M A . The signal is split, with one signal controlling one solenoid, and the other.
inverted signal controlling the other. Therefore, when the duty cycle is changed, one

solenoid will open wider, with the other opening with an equal. opposite narrower

opening. The ciifference in pressure moves the main spool one way or the other, thus

acting as a hydraulic amplifier by aliowing a large volume of oil to move fkom one side of

the seeder hydraulic cylinder to the other.

6.3.2 Display-Depth Routine


Now that the contml signal has k e n sent to the discer, the controller moves into

the LCD depth display routine. The depth error value is compared to the soi1 surface

value, and the difference is displayed on the LCD.The routine includes a subrouthe that
Chapter 6: Sotbuare Design

convei%sthe depth number to inches or centimetres and tenths of an inch or millunetfes.

Once all the numbers have been calculateci, the LCD display routines are cailed to put

each character on the screen. The unit preference can be clected by the operatoc

Fig. 6.4. Hydrauiic valve detaü.

The Op- display used in the controller has its own intemal memory and display

osciliator circuitry. As a resuit, any characters wntten to the display will stay on the screen

until the "clear display" commaad is sent by the controlier. In order to reduce display

flicker due to unnecessary display writes. the code in this routine will check the contents

of the display registers before writing a character to the display. This way, if the desired

character is already diplayed on the screen, the write routine for this character is skipped.

By doing this, LCD flicker due to constant redraws is virhtaily eIiminated.


Chapter 6: Software Design

6.3.3 Send-Data Routine


In order to subjectively test the performance of the controlier, a serial

communication data logging routine is utüized Data read h m registers in the controller

is sent to a laptop cornputer for saving in a log file and later analysis.

Data is read h m the ERROR, CHANGE-IN-ERROR, and OUTPUT registers in

order that these calculations can be céecked during program debugging to ensure that they

are correct. These data ailow crossthecking the controller huy decision with the

expected output Born previous simulations. Also, if any changes are made in the field, the

results of these changes can be recorded and monitored.

Sensor position information is important to ensuring that the ERROR and

CHANGE-IN-ERROR calculations are comct. By having the unprocessed 8-bit ADC O

and 1 readings over the time of the trial, the entire process of calcuiating ERROR,

CHANGE-IN-EERROR, the fuuy decision and final hydrauiic valve output value can be

evaluated. Parts of these data can be used as input values to the simulator in FIDE and the

simulator written in Mathcad to test a new fiuq a l g o r i t h Likewise,the huzy output

values fiom the field unit c m be tested against the results of FIDE and Mathcad simuiator

calculations to ensure that this part of the program is giving the expected results.

The ADC O aad 1 readings can be used in other Mathcad routines to test how weli
the controller calibration and operation subroutines work. These readings also can be used

as a record of the &roundcontours at the test site.

The sister PC routine operates by checking for valid data being in the serial bufXer,
reading the data, and sending an acknowledge signai. Once received, the controlier
Chapter 6: Sofiware Design

increments an index, and sen& the next data byte. Both the contn,Uer and the PC are

synchronized to prevent data skew.In total, 10 bytes are sent per sampling instance. The

PC logging program automatically formats the data for saving into an ASCII file for easy

importing into a spreadsheet, mathematics or signal analysis pmgram. As data are being

collected, a bar graph display on the PC aliows the operator to monitor the progress of the

logging and control operations, thus detecting obvious problems early.

When the controUer has nnished the SEND-DATA routine, main program

execution loops back to the CHECKJCEYS routine, to begin the next loop through the

MAIN program subroutines.

The present system m s fast enough to log data 23 times a second. This is

equivalent to one sample king taken every 7 cm (2 1/2 inches) at a speed of 10 kmmt (6

mph)-
Several versions of the control software are used in different parts of the research.

The program described here referred to the fmt version, where the operationai purpose is

to log data pertinent to controiier operation, as weli as control seeding depth. The second

program version is intended for use when logging is not needed, such as when debugging

controller code with the tractor and discer in a stationary position. in this version, the

SEND-DATA program routine is commented out before compiiing. Finaiiy, an FFï

routine for the MC68HC11 was adapted to the 16-bit MC68HCl6Z 1, for deteminhg the

operating fkequencies of the front depth sensor.


Chapter 6: Software Design

6.4 Chapter Overokn


A controUer of this type takes as much effort producing the code for support

routines as it does to write the core control algorithm, Calibration was especiaiiy

challenging, as if necessitated a considerable amount of stationary testing with the discer

to e n s w that the readuigs were consistent and accurate. It was also discovered at this

point in code development that a single seasor on the front of the implement would not be

accurate, as it would not be able to give the position of the discs as they chmged. A single

sensor also would not be able to discern sinking of the discer into the soi1 nom discer

rocking motion over the axis of the discs and implement tires.

The hardware has been designated, as well as the software design defined. This

now takes us to Chapter 7, Fuzzy Depth Control System Implementation, where these two

design activities are combined to form the total system.


Chapter 7= System Implementation

The emphasis in this Chapter is to explain how hardware. software and the process
of simulation and verification combine in the formation of a system suitable for e v a l u a ~ g

the suitability of f k z y logic for the application of seed depth monitoring and control. In

Section 7.1, the field test and &ta logging functions are discussed. Section 7.2 presents

how the calibration routines work. Finaiiy, Section 7.3 deals with how data is verified and

new funy routines simulated and tested. AU HC16 software was written directly in
assembly language to maximize execution speed. Software written for the PC was in

Turbo C [Bor188],with simulation in FIDE script and within Mathcad.

7.1 Field Test and Data Logging Mode


As the purpose of the depth controllcr being descnbed here is to test the suitability

of fuzzy logic for the application of seeding depth control, it is imponant to have a means

of couecting field data to use in software simulation. evduation and design. The field test

and data logging mode is useâ to control seeding depth and record observations and

contml parameters, thus, measuring actual field conditions and ncording them for

analysis.

This mode is used when operathg as a depth conuoiler and data logger. The

sampling rate can be set to up to 24 samples per second, which translates to one sample

every 12.35 cm at a speed of 12 kmmt


7.1.1 Operational Issues
The controiier box is consüucted so that it can easily fit on the side of the cab of
the tractor, witbin easy mach and sight of the operator. Power is provided by the cigarette

lighter through a power cord constmcted for this purpose. A power switch on the case

operates in series with the power connecbon to the power supply module. A 5 ampere

fast-blow fuse is also installed, to protect the board and tractor circuits fiom short circuits.

Cables to the sensors and the hydrauiic valve solenoids are c o ~ e c t e dto the controller on

the side of the box facing the rear of the tractor. Cables were nui through the rear of the

tractor cab.

Some ergonomie issues were taken into consideration in the design of the conuol

box even though it was constructed for research purposes, and would not have many hours

of use in the field. The interface for the controL1er was made to be simple. in order that the

design met the cntena for making operation as safe and non-distracting to the operator as

possible. One reason the controller box was constructed as small as possible was to enable

it to be easily placed beside the operator without impeding operator movements. The

operator is able to see the display while tumed panially backwards when watching the

discs. Likewise, the box couid be fitted over the dashboard above the steering whed,

allowing the operator to see the display without Ruaing or looking to the side, away from

the direction of travel. If the controiler box was cwibersome to use and obstnicted the

operator's movements in the cab. this would pose a senous distraction for the tractor

operator and pose a safety hazard to anyone wodting behind the tractor while it was
Chapter 7: System Implementation

7.1.2 Field Operation


On p o w e ~ up,
g the HC16 fin& the iaitialization vectors starting at location $00,

goes through the module and memory initialization steps, and enters the main program
loop. Upon entering the SEND-DATA routine, the HC16 copies the parameters to be

logged to temporary locations. These include the values for the Mit format sensor

position rcadings fkom ADC O and 1, the 16-bit quantities for enor and change in error,

and finally, the 8-bit fuuy decision output.

As there are no hardware handshaking lines, serial communication relies on

passing handshaking characters between the PC logger and the HC16.The HC16 enters a

loop where the Receive Data Register is checked for new data If the Start signal ($F) is

received from the PC logger, the routine continues. If then is noise on the h e or the PC

logger is out of synchronization. $F will not be received and the HC16 goes back to the

wait loop for the correct character. Therefore, in order for the HC16 to work. it must be

comected by a null modem cable to the PC logger computer. The contmller must be

started kt,then the PC logger program. Using a specinc stm character e l M a t e s the

possibiiity of data king written to the log 6le that is out of the correct sequence. Of

course, as the log fiie is formatted in a certain way,if information was out of sequence it

would be obvious once this text format file is inspecteci.

Once the Start commaad is received by the HC16,it then sen& the k t data in

byte format. After each byte, the HC16 checks the Receive Data Register for the character

"E".which is the C o n ~ u signal


e h m the PC logger. In this way,the data is sent fkom the
HC16,saved by the logger program, and an acknowledge signal is sent to the HC16 by the
Cbapter 7: System implementation

logger when it is ready to receive the next character. Once this pmcess has been repeated 6

iimes, the HC16 r e m s to the top of the main pro- loop of the controiier code. and

continues und execution again reaches the SEND-DmA routine, where the Receive Data

Register is again checked for the Start character.

Whüe the HC16 is executing code for the other routines in the main program loop,

the PC logger program reformats the data received for storage, stores it to the log file, and

writes a bar graph line for each data item to the PC screen. The bar graphs are a graphical

representation of the processes occumhg in the hury logic controller. Extreme conditions

can be spotted immediately, and the controller stopped for code modification and

checking. The data logger can be stopped by pressing the Escape key on the PC. The

HC 16 wilI continue execution until it reaches the Receive Data Register test loop, where it

wiii continue looping until the logger is restarted. This way, the controller can be stopped

and restarted without having to reboot.

There is also a version of the HC16 controller code that has the data logging

routine commented out. This is used for initial installation and check-out of the system

when it is king installed in the tractor and hooked up to the sensors md the hydrauiic

valve.

DEPTH
Fig. 7.1. LCD interface display in operation.
Chapter 7: System Implementation

The LCD interface is very simple. W e the controiier is operating, the LCD

displays the depth in the units that are chosen by the operator. It is bolted to the top iid of

the connol box above the keypad A 20 cm niboa cable coanects the pc board bolted to

the box lid to the coatroiier module main board. The controuer box can be tilted toward

the operator if the angle of the LCD is too high to see it properiy.

@) 0@ @) Set Modes and Raised Height


Set Seeding Depth @@
Raise Discs
@@@@* Lower Discs
(Resume Normal Operations)

Fig. 7.2. Keypad functions.

The alpha keys on the keypad are used for initiating calibration and control of the
depth control operatioos. The "A" key starts the set raised height and modes subroutines.

The "B" key is for raising the discs, while the "(2" key is used to start the subroutine for

sening the seed depth. The " D key is used for starting the process of setting the ground

position. The "E" key is used for initiating calibration, while the "F" key is used to lower

the discs.

By hitting any key except the "F'key, the controuer stops operating as a seed

r enters the chosen subroutine. The key fuactions were chosen based
depth c o n ~ l l e and
Chapter 7: System hplemeotation

on how an operator would intuitively remember the functions. For example. the "Raise

Discs" command key is located above the "Lower Discs" command key.

The keypad type chosen is a membrane keypod with raised keys. This keypad

requins some effort on the part of the operator to activate individual keys, thus reducing

accidental fiuiction activation.

The most cornmon hinctions were located on the edges of the keypad. For
exampie, the taise discs command was located on the right side of the keypad. so the

operator c m operate it with their thumb with the rest of the hand steadying the thumb by

resting on the right side of the box. Steadying the thumb is important, since this button

would be pressed while the tractor is in motion over the field. The position also reduces

the lïkelihood that the operation of the controller would be intenupted by hitting the

wrong key, as the number "7" key above the 'B" will have no effect. and the "F" key

below it will not intempt controller operation, either. If the "A" key is hit accidently, the

controller wiii stop operation, but quickly hitting the "B" key will cause the controller to

recover and raise the disks. This enor would not be iikely to occur ofien, as the operator

must stretch the thumb fanher away fkom the nght edge of the box. The "F" key is located

on the right hand lower side, so that it is easüy found and operated when the operator

wishes to &op the discs and resume opration.

While seeding. the operator need only use two keys: the UP position key for

raising the seeder, and the DOWN position key for lowering the discs to operating

position. Sethg the disc raised position provides the üP key subroutine with the desired

height for the discs to be raised above the ground when actuated. The DOWN position key
Chapter %: System implementation

releases the conml software fiom a W m loop (initiated with an UP key press) that

r e m s the program to normal seed depth operation. When the dûcs arr in the lified

position, it displays "DISCS RAISED" and wili lower hem by hitting the "F' key on the

keypad. This command directs the fuuy controller to remme normal operation, so the

discs descend to the depth set point.

Two main parameters to meanire are the shape of the topography of the field (S),

and the characteristic rates of change as one moves across the field (dS/dt). A data

sampling function in this mode samples both the discer sensoa at a relatively high speed

(24 Hz) in order to provide accurate promes of the soi1 surface for use in simulation of the

control system in the lab. The sample data are collected by the control module, and

transmitted asynchronously to a portable computer serving as a data storage unit. This

provides a the-domain wavefom that is used as the perturbance input in system

simulation and for analysis of how the controiler responds to different inputs.

The rate of change in field topography is important to know to ensure that the
sampling rate used in the depth control operating mode (normal operation mode) satisfied

the Nyquist sampling theorem. This States that in order to prevent errors due to aiiasing,

the sample rate must be at least double the rate of change of the signal. In actual use, this

sample rate is set to about 1.6 times the rate of change of the signal. An HCl6-native. 16

bit fast Fourier transform (FFD was written for this purpose, based on the l3T produced

by Ron WiUiam of Ohio University for the MC68HC11, which in tum is based on the

witten by Richard Lord [Lord79]. Output is sent to a portable computer, which logs the

data and provides a real-tirne graphical display of the resdts. The FIT' used takes
Chapter 7: System implementation

advantage of the Idbit operathg capabilities and digital signal processing cotnmands of

the HC16.

7.2 Calibratioa Mode


The operating mode also includes the keypad fimctions for calibration and control.
Ail of these fiuictiotls are conducted while the tractor is stopped. As the LCD is only 16

characters wide. where messages encompass more than 16 characters, each iine of the

message is displayed with a pause of about one second between lines.

W1th increasing height,


& angle change per unit

/
/

I
/' l
height increase is
I reduced

Sensor
Axis

- - -
Disc ComectioD
Point I
Fig. 7.3. Calibration hctions - 90 degree setting and theta correction.

In the operation of the controller. the lîrst operation to be conducted is the

calibration operation. This ensures that a i l subsequent sensor readings are interpreted

correctly. The h e e control parameters described here include setting the raised position

of the disks. setting the operating depth (the depth set point), and the field surface level.

Raised level and operating depth are programmed by pressing numeric keys when
prompted to do so. These parameters can be set in either metric or impenal uuits. The

units are chosen as a sub-menuof the raïsed &CS level setting. Field surface level is found

g disks to the ground, thea pressing a key to store the A/D value directly to
by l o w e ~ the

static RAM as a variable. Once these three values are set after calibration, the depth

controiler is ready to operate.

7.2.1 Keypod Funcrions


The keypad functions include one key used to start calibration routines, t h e keys

for setting pararneters, and the two previously mentioned used in controlling the height of

the discet.

The "A" key starts the subrouthe for setting the height of the discs when lifted,

and choosing the operating modes.

When the "A" is pressed. the controller displays the message "Choose

Function: P r e s s O to pick sensor modes, 1 to set seeder

raised position, 2 to set units".Ressing the "0" key causes the controller

to display "Choose Scan Mode Press O for dual sensors, 1 for

single sensor". Pressing "û" at his point causes the controller to determuie disc

position by sampling both the front and rear sensors (this is also the default mode, and is

part of the controller initiation settings on initial start-up). Pressing "1" sets the controiler

to use sensor data fkom the front depth wheel sensor oniy. This mode is used in studies

where the ftame height above the ground is the oniy parameter desired, as in determinhg

the amount of wheel sinkage on a given field. Once either the "0"or "1" keys are pressed,
Chapter 7: System fmplementation

and the controiier Wshes writing to the respective register, the controiler resumes depth

control operation.

Pressing "1" ta set seeder raised position, the message ''ENTER INCHES: '5s

displayed. The operator aow presses a numeric key to represent the inches raised. The

controlier then displays the message "ENTER TENTH INCH". Once the operator has

pressed a numeric key for tenths, the controller resumes depth control operation.

Pressing "2" for setthg units results in the display 'Y) for imperial, hit 1 for

METRIC". Choosing "O" sets the units to imperial, and the displayed depth is shown in

inches and tenths with the word "INCHES" on the K D display. Choosing "1" sets units

to metric, and the uni& are displayed in centimetres and millimetres, with "(34" on the

LCD.
The "C" key triggea the subroutine for setting the seeding depth. The LCD
displays the message "SET SEED DEPTH", then "HIT ANY KEY'. Once the operator

has pressed a numeric key, the LCD shouts, "ENTER INCHES:". When the operator

presses a numeric key, the value is stored as the inch setthg. The LCD then displays,

"ENTER TENTH INCH".Again, when the operator presses on a numeric key, this value
is saved as the tenth of an inch setthg. Once this has been done, the controiler resumes

depth control operation.

The " D key initiates the "set ground level" subroutine. The LCD displays "SET

S O L SURFACE" message, followed by "HIT ANY KEY' several seconds later. Once

the operator has pressed a nwmric key, the message 'ZOWER TO G R O U N D appean,

foliowed by "HIT KEY TO STORE".The operator manually lowes the discs to the
ground on the field, using the hydraulic levers. Once on the gromd, the operator presses a

numenc key to store the value as the "Zero" depth position, or ground surface. Once this is

complete, the c o n W e r resumes depth coatrol operation.

The '2" key starts the calibration subroutines. For calibrating both the front and
rear sensors. the implement is moved to a hn, level surfacc where the disks do aot sink

into the ground when lowered The b t variable to be set is the point in which seasor

linkage arms are 90 degrees to the depth linkage amis.Fiialy. the ground positions of the

senson, and their positions with the disks at 6 inches above the gromd are recorded. This

results in a characteristic calibration factor king calculated for the specinc sensor setup,

that is used to provide the correct depth in normal operation.

When the "E"key is pressed, the controiler prints "Choose Funcfion: Press O to set

sensors 90 deg to Linkages, 1 to cal disk sensor. 2-cal front sens" to the LCD display. If the

operator presses 'Y)", the message "PRûCEDTJRE TO STORE THE SENSOR POSITION

90 DEG TO DISK LINKAGE' is displayed, foilowed by "HIT ANY KEY". Once the
operator has pressed a numeric key, the message bbPositi~n
disk so sensor arm is 90 deg to

disk arm" is displayed. This is foliowed by the "HI. KEY TO STORE message. The

positions of the rear and front sensor anns are then set 90' fiom the respective connecting

a m to the discs and fiont sensor. When the operator presses a numeric key, the values in

the sensors are stored as the position where the sensor arms are perpendicular to the

connection amis to the disc gangs and front depth sensor assembly. Once the values are

stored, the controiier resumes seed depth control operation.


Pressing the "1" key wiii stact the subroutine for calibrating the disc sensor. The

controiier displays the 'mISC SENSOR CAL" message on the LCD. This is followed by

"ON LEVEL SURFACE"' then "HiT ANY KEY". The operator presses a numenc key,

and the 'ZOWER TO SURFACE" message is displayed foiiowed by ''HïïANY KEY".

The operator then lowers the dixs to the ground manuaüy ushg the hydraulic levers, and
then presses a numeric key to Save the value. The message "RAISE DISKS UP SM

INCHES" is displayed foiiowed by 'HIT' ANY KEY'. The discs are lifted manuaiiy, and

the distance from the ground to the bottom edge of the disc is measured. The discs are then

raised or lowered untA they are 6 inches above the &round. To ensure that the height

reading is not in error due to sagging of the disc gang when above the ground. make the

measurement at the centre of the disk gang.

Once the discs have k e n set to 6 inches, the operator presses a numenc key, and

then the "HïïKEY TO STORE"display is written to the LCD. Once the value is written

to memory and the respective calculations have been made, the controller r e m s to seed

depth control operation.

Pressing the "2" key WUstart the subroutine for calibrahg the front sensor. The

controiler displays the ''FRONT SENSOR CAL" message on the LCD.This is followed

by the "ON LEVEL SURFACE" and "HIT ANY KEY' LCD messages. The operator

presses a nuwric key, and the "LOWER TO SURFACE'' message is displayed, foliowed

by "HïïANY KEY". If the front sensor is on the ground a numeric key is pressed to Save

the value. The message "RAISE DISKS UP SIX INCHES" is displayed, followed by

"HITANY KEY".The sensor is lifted six inches on measured blocks.


Chapter 7: System hplemeotation

Once the sensor wheel has k e n biocked up 6 iaches, the operator presses a

numeric key, and then "Kïï KEY TO STORE" is displayed on the LCD.Once the value is

Wnnen to memory and the respective caicuiations have k e n made, the controiier rehuns

to seed depth control operation. Once sensor calibration is complete, the parameters for

operation can be set.

7.3 Chapter Overoiew


The operation of the fuzry depth controiier has k e n desigwd to take advantage of
the combination of a simple 16-key keypad and the easy programmability of the LCD

display. Each of the six alphabetical keys on the keypad contml a separate depth controiier

set of functions.
Cbapter 8: Dixussion and Analysis

CHAPTER
8
DISCUSSION
AND ANALYSIS LOGICBASED
OF NZZY
DEPTHCONTROLLER
SEEDING

Increasing depth control accuracy is an important means of maximizing cmp

retums without additional input costs or t h e . The limitations of cornmon seeding depth

control methods and the suitability of fuay control for this application have k e n

preseoted in previous Chapters. A proof of concept controlier design was built using the

MC68HC MZl microcontroller. Testing of operating fwlctiom has been completed.

8.1 Fuzzy Contml


The fiizzy controller is a Mamdani-type controlier, based upon the max-min

composition. The Mamdani type of hiuy coatroller, first inuoduced 20 yean ago

[KiMa77]. has been appüed to a variety of industrial processes. For example, it has been

used in heat exchangers. cars, and w a s h g machines iKipe90, Mua84J. Thus, fuuv

control is gaining in popularity in control applications that use nonlinear, tune varying

inputs. Seeding depth control also presents this type of probiem.

In utiiizing fuuy logic in the decision process of the seeding depth controlier, the

state of the seeder position is described using linguistic labels. The fuuy membenhip

fuoction mA(x) describes the extent to which the adjusted value x of the two sensor inputs

belong to a specific Linguistic input classification describing the error Born the set point.

Similarly, mB(y) describes the degree to which the Merence between the depth reading
Cbapter 8: Discussion and Analysis

seven samples previously and the present reading belongs to a specinc linguistic

classification for the change in e m (seven samples rrpesents about 113 second for the

data Iogging controller. and about 1/7 second for the non-data logging contder-ushg

adjacent sarnples provided very littie difference in enor). For instance. the rneasured

error from the depth contdier set point input may k classified by its degree of

membership in the linguistic classincation, Negative Medium, and the error change from

the previous depth reading classioed by its degree of membership in Positive SmaU (see

Fig. 8.1).

NM

NS

ZE

PS

PM

NS
2 . CHG
IPS IPS JPM IPM IPB JPB

Fig. 8.1. Fuuy control mies for 7 memkrship fvnction algorithm, fiom FIDE
simulation.

A list of linguistic conaol d e s were formed based on the fuuy relation. Each nile

is based on the advice fÏom an expert human operator. Linguistic variables are set up in

the manner iiiustrated in the following example.


Chapter 8: Discussion and Analysis

IF <INPUT VAEUABLE #I> IS ~ C E ANDD<INPUT


~ #2> ~
1s

cANTECEDENT> THEN COUTPUT VARIABLE> IS cCONSEQUENT>

where

<INPUT VARIABLE # 2 b are the input variables being monitored;

cANTECEDNT> are the input hiay membership hctions;

<OUTPUT VARIABLE> is the controiling signal; and

<CONSEQUENT> is the fuzzy output membeahip fiinction

In the f h t example for this research, seven Linguistic variables for &or, and seven

iinguistic variables for Change in Error were constructed in the fouowing form.

IF ERROR IS NB AND ERROR CHANGE IS PB THEN CHANGE IN DEPTH IS NM

ELSE

IF ERROR IS NM AND ERROR CHANGE IS PB THEN CHANGE IN DEETEI IS NS


ELSE

A total of 49 d e s constitute the summary of the expea operator's experience in a

form usable by the fuzzy logic coatroiier. The hiuy depth conml algorithm is therefore

defined by these d e s . The control action is determinecl by the max-min product of the
Cbapter 8: Discussion and Analysis

depth reading input x with the h z y depth control algorithm, D,denoted by xOD.The

fuzzy depth control algorithm D consists of fuuy relationships ktween the inputs x and y,

and the control signal output, r Additional tests with 25 d e s and 9 d e s were nui with 5

membership fimctions for error and change in enor. and 3 membenhip huictions for enor

and change in emr, respectively.

The discrete numkrs representing the e m r and change in error are fuzzified. This

means that the discrete input values are classifîed as king mcmben of given fuuy

membership functioos if their values f d wiihin a given membership fuactions' range of

values. The degree of membership in each given membership funftion is given by a

number between [O,L]. This is also said to represent the degree of membership in the

respective fuuy set. The algorithm is based on the max-min composition of theses values,

represented by the fuuy control d e s . For example, when X is the degree of membership

of a given depth input in negative medium, and Y is the degree of membenhip of the

corresponding change in error in positive srnail, the hiuy phrase P describes the min of

the inputs. or X X Y

mP(x,y) = min { m-ve medium(x),m+ve big(y) 1 (8.1)

According to the fuzzy d e s presented in Fig. 1, mP(x,y) describes the

membership of the min of the input variables (x,y) in the output variable negative srnail.

Matbematically, this c m be represeated by m-ve smaU(x,y,z) = X X Y x 2,denoted by

fuuy phrase Q
Chapter 8: Discussion and Analysis

mQ(x,y) = min{mP(x,y)m* small(z) 1 (8 .a


The max of al1 the huzy phrases QN gives the hiuy value S of the output signal,

where N is 1 to 49, 1 to 25, or 1 to 9, coffesponding to the number of hizy d e s in the

controuer

mS(x,y,z) = max { ~ Q ~ ( x ~ Y , ~ ~ , ~1 Q ~ ( ~ ~ Y,~)~~~,


(8-3)

The value, mS(x,y,z), is then dehiuined using the center of gravity (COG)

approach. This approach determines the output using the weighted average of singleton

output functions. The resuitant output signal voltage is then appiied to an electrohydrauiic

proponional valve.

8.2 Simulation
In preparing for simulations, the objective was to approximate the decisions of an

expert operator as closely as possible. The k t step was to form the f k z y control d e s .

These provided the reasoning for the actions, and serve as the implementation of an

operator's actions. A combination of the "conventional" and the "template" method was

used. The next step was to determine the control parameters based on the mechanical

characteristics of the plant to be controiied. The maximum height and depth the discs

could obtain are the iimits of movement and the Limits the membership hinction Enor

(about half this total distance negative, and half the total distance positive) could obtain. in

a simüar fashion, the working depths of different seed types were considered and

compared to the maximum rnovement of the discs in order that the best membership

fuaction shapes couid be determined Fmaiiy, the maximum speed of movement of the

front sensor and disks was considered, in order that the sampling rate was fast enough to
Chapter 8: Discussion and Analysis

satisfy the Nyquist sampling theorem. By observing the motion of the d i x s and fiont

sensor, this was àeemed to be about 75 cmlsecond This provided the information needed

to put together the membership functiom for Rate of Change. Thenfore, it was possible to

assess the performance of fuzy logic control aigorithms by comparing results to the

desired output.

The values for the fiuzy controller were then simulated, using Manifold Editor
(Version 1.8.01- 100049, Fuay Systems Engineering, San Diego, California, USA),

Mathcad (Version 6.0 - MsthSofi, 101 Main Street, Cambridge, Massachusetts, USA

02142) and FIDE (Fuzzy Inferroce Development Engine, nom Aptronk, CA, USA).

Manifold Editor enables the user to graphically edit membership functions, set input

values, and view output values given different input values. Mathcad is designed to

operate like a clean sheet of paper, where the user enters equations and variables just as

they would with pen and papec Data nles can dso be imported, so once field readings

were available, these were imported and processed. FIDE is meant to be a complete fuuy

logic development tool, with graphic membership function editing. simulation functions.

viewing of control surfaces and generation of &bit code for several microcontrollers.

In using Manifold Editor. initial input parameters for membership funftions were
entered, then analyzed using the Manifold Walker. As each input was changed, the

resulting output value was noted and recorded. Output values were compared to the

desired values.

Output values for this application must be monotonic, in order to preserve the

stability of the controller. Output values of the Manifold Walker were graphed to ensure
Cbapter 8: Discussion and Analysis

rnonotonicity. Minor adjustments weE ma& to the input and output membership

functions to epsure this. The fuzzy membership functions and their mal values are

indicated in Figs. 7.2,7.3 and 7.4.

Fig. 8.2. Manifold Editor input membeahip fhction exampie - 7 membership function
algorithm. Error on Ieft, Change in Error on nght.

Fig. 8.3. Manifold Editor - output membership function for 7 membership funftion
algorithm.
Chapter 8: Discussion and Analysis

Fig. 8.4. FIDE simulation screen example: input and output membership functions for the
7-membership fûnction aigorithm.

The membership functions in "Error" (Fig. 8.2) refer to the degree of error

between the acnüil depth of the Unplement to the desked target depth (the set point = O).

The fuil scale readings Vary kom -15 cm (15 cm below the set point) to +15 (15 cm above
the set point). In the "Change in Enor" membership fuactions (Fig. 8.2) are the rate of

change in between the depth sensor readiags is measured, in te- of cm/second.


Cbapter 8: Discussion and Analysis

1.a

B.5

B.B
-1s 125

Fig. 8.5. Input membership fuactioos for change in emr fkom prpviobus depth reading.

The output memberrhip hiactions, in "Depth Adjust" (Fig. S), refer to the distance
the irnplement must move in order to approach the set point. This is expressed in terms of

-cm (distance to move dom) and +cm (distance to move up).

Fig. 8.6. Output membership hinctions for depth adjustment.


Chaptcr 8: Discussion and Analysis

Once the vaiues of the output were recorded from the Manifold Walker, a surface

plot was produced to give a graphical representation of the fuzzy controiler output (Fig. 8-

8)-

lis

Fig. 8.7. Fuuy control surface (fiom a FIDE simulation). The X axis represents positive
64 mm to negative 64 mm change in emr, the Y axis representing positive 125 mm to
negative 125 mm error from the set point, and the Z axis the change in output of -15 cm/
second to 15cm/second.

The control surface shows the monotonie control characteristics of the fwzy
controiier. The surface near the zero error and zero change in depth point shows a gradua1

positive slope, where control signais need to correct the depth a small amount. Areas

closer to the extremes of the control surface have a higher rate of change in the slope. By

inspection, no part of the curve is seen to take on a reciprocal slope, therefore

monotonicity is ensured.

Mathcad required complete programming of the fuzzy control algorithms. It ais0

aUows the user to use programmulg hinctions, including loops, iterations and if-then

statements. The variety of graphing functions also made it possible to instantiy see the

effect small algorithm changes had on huzy contml, as a two dimensional output result

and as a three dimensional surface plot. As it was possible to produce a variety of output
Chapter 8: Discussion and Analysis

results quickly while knowing exactly what calcdations were taLing place to prduce

them, this was the tool in which most simulation was done. It was more tiw consuming

than other tools but had the important advantage of having the flexibility to modify the

funy control algorithm and analyze results statistically-

A 7-membership, 5-membenhip and 3-membership huiction fuuy controiler was

set up in Mathcad to compare the results. Cornparison of results included several

parameters. One comparison made was the granulanty of data. The fineness of control was

compared in the three regimes. Obviously, the minimum control achievable on output is

one unit in 256, or 8-bit control. The minimum amount of each membership function

output was compared to this.

Another criteria for comparison was how weU each regime fit into the

requirements for the fuzzy depth controiler. For example, in the 3membership function,

was necessary to reduce the slopes of the Zero fiinction to the point it was no longer

possible to achieve fast response tirne on extreme Error readings, whiie rnaintaining fine

(slow rnoving) control when there is very Little error. A weli-designed fuzzy controlier

should be able to quickiy move the discs to the set depth, without overshooting the target.

In conventional seeding depth controllers, lack of overshoot is often attainable only at the

expense of speed andlor accuracy by the use of a "dead band". It is worthy to note here

that as the slopes of the membership fiinctions of a fuuy controlier becomes steeper, the

controiier cornes closer and closer to approximating the actions of a conventional, non-

fuuy controiier. The 5- and 7-membership function algorithm both provided sufncient

speed of action with accuracy (gxanularity)of control for this application.


Chapter 8: Discussion and Anaiysis

Work with FD)E dealt mainly with the assembly code producing capabilities of

this program. Membetship fuactions were set up and verifi.ed, then the assembly code

produced. The version of FIDE king used here produced assembly code for the

MC68HCll. Although this is 8-bit code, the MC68HC16 compiler MASMl6.EXE will

properly compile this code for use in the HC16. The code to be tested in the controller

hardware is placed in the fuzzy controiler assembly code, and the respective variable

names adjusted and memory space ailocated to aliow it to work with the rest of the code.

FIDE version 1.0 uses only singleton output functions. This is appropriate, given the

characteristics of the hydraulic valve. Although the valve is proportional, the speed of

operation does not vary considerably once the P W M A output exceeds 25 hex uni& fkom

center, or about one nfth of the total PWMA output possibility is usable in this way.

8.3 LabTesthg
Once a new algorithm wodd be produced in FIDE, it was compiied with the HC16

controller code and tested in the MC68HC16EVB evaluation board laboratory test unit.

The sensors were taken through their entire range to observe the depth reading results on
the LCD display. An osciiloscope was also used to examine the PWMA output waveform

as the inputs wen varkd to the controiler. Once it was detennined that code produced a

monotonie control action and approximated what was needed to work in the field, the lab

unit would then be comected to the actud disk sensors and hydraulic proportionai valve.

A tractor comected to the discer supplied hydrauiic pressure for the testhg. In order to

simulate a "fieldtzeroTTcondition, the discer was operated in one spot, but the "zero"
Chapter 8: Discussion and Analysis

position wouid be set severai inches above the ground in order that control on both sides

of the set point could k moaitored.

W~thoutthe damphg effect of the soil, it was found that the discs would oscillate

when ushg the 7-membership and 5-membership fiinction algorithms. Oscillation was

stopped by scaling the membership algorithm outputs d o m 50% in speed. It was found

that once oscillation began, the resonant frequency of the discer would be obtained quite

easily, as it rodred back and for& on two baiioon tires. The tires are located about 10 feet

from the other, so the resuit of this distance was a lever action using the implement frame

that tended to ma- the rockkg motion of the discer. Thus, with a combiaation of large

rubber tkes ~spendingseveml tons of steel discs and associated hardware, oscillation was

very easily achieved by several quick movements of the &ont sensor. If this work was to

use a conventional, bbbang-bang"


hydraulic valve that opened and closed at N1throttle,

the oscillation problem would only be defeated by using a valve that would be too smali to

move the discs quickly when the error or rate of error change was high. Cascading several

valves wouid also work, but would add complexity in the hydraulic valve plumbing and

lead to increased possibility of leais, complexity for servicing. cost and increased nsk of

failure due to a higher number of electric solenoid valves and associated wiring.

8.4 Field TestiDg


Once several hizzy control algorithms controiied the disc position weli, they were

med under field conditions. The lab MC68HC16EVB control unit was suitable for use on

a table in the laboratory and stationary testing, but would serve to be impractical for use in

the field when the tractor was in motion. An umbilical setup could have been set up for use
Chapter 8: Discussion and Analysis

with a vehicle following the movhg disc, but a mch simpler tractor cab mountcd unit

was constmcted in a s m d aluminum box for testing and logging of tesuits. Shielded

! ~ the sensors and the hydraulic proportionai valve were nin into
control wûes C O M ~ C ~ € to

the cab. and securely cornecteci by amphenol-type shiekkd screw connectors. A shielded

aluminum box enclosed the controller electronics. with sbïelded compartments for the

power supply and hydraulic signal switching. Power was suppiied to the unit via the

tractor's 12V cigarette Lighter socket.

Fig. 8.8. Field data logger status display screen.

In order to facilitate logger operation and ensure it is bctioning conectly, a

screen display was produced that graphically indicatedthe cunent ~adingsbeing received

from the controlier (Fig 7.9). In order that it would function on any PC,and not just a
Chaprer 8: Discussion and Analysis

Wmdows-3.1 or above capable machine, the software was written in Turbo C. with

graphics set up for use in MS-DOS.

The m e n was set up with a simple interface for easy interpmation of the state of
the controller. The text across the bottom is as follows: Error, Ermr Chg (change in error),

Fuzzy Decision and the sensor position readings Fnt Sensor (front sensor, on the gauge

wheel) and Dsk Sensor (the rear seasor, on the disk gang). Shon lines on the vertical

access of each screen parameter represent the median positions of enor, change in error.

and hzzy decision when error and change in e m r are zero. For the disk sensor positions,

the median line represents a hexadecimal reading of $7F or 127 decixnai, the center of the

sensor range. The h e at the top represents SW,or 255, with the bottom axis of the graph

representing 0.

The PC logger graphic display proved to be invaluable in field testiag. In some of

the tests, an incorrectly wired sensor was causing a pronounced darnping effect on the

level of error. producing values that were much below the expectation. The deficiency was

spotted immediately with the display values, and the changes made. In another example, a

sensor was not clamped in the center of its total operating throw. This meant that the

sensor would rcad zero nom the to time, resulting in incomplete data and erroneous

conaol action. Sensor connections were loose in one experiment, resuiting in wildly

changing output values. Steps were then taken to eliminate this effect. If the logger had

not had the display, it would have led to fuaher delays in development of an operating

controller, since problems would not have been apparent until the logged data was

graphed.
Cbapter 8: Discussion and Analysis

A numbu of different trials were nui with the 7 membership function algorithm.

on unworked stubble. soil disced once and soil disced twice. Tractor speed was a constant

6.8 miles per hour, typicd for seedïng. It was found that the low-pressure tire of the front

sensor foilowed the soi1 contours very weU, but wouid be easily lifted up by piles of straw

larger than 1" thick Also, if there were intermittent piles of straw within severai feet of

each other, the resonant vertical motion fkequency of the sensor would sometimes be

obtained, leading to steady bouncing of the sensor up to 4" off the ground In this case, the

aigorithm with the speed of the discs dampened by 50%was unable to move the discs fast

enough to follow the bauncing, so the discs actually remained quite stable as the front

sensor bounced across the set point.

Data was collected giviag the enor, change in error, decision and the sensor

position readings fiom the A/D converters. This way, the sensor readings could be

converted to inches, and the action of the hizy control algorithm checked against what

was expected.

Fuzzy Decision
Value
Change in Error Front Sensor Reading

Rear Sensor Reading


15599134740
156513730
15957132880
161 52 127 66 1
1S559 134 74 O

Fig. 8.9. Portion of data output fiie showing data format for PC logger.
-ter 8: Discussion and Analysis

A sample of the data coUected is given in Fig. 8.9. A time domain plot of the

sensor position over time is also given in Fig. 8.10. Emr, change in error, and fuay

control output is given in F i p s 8.11,12, and 13, respectively.

Error, Chg in Error and Output


Field Test 5

Sample Number

Fig. 8.10. T î e domain plot of the sensor positions.

The FFI' of the data is given in Fig. 8.13 and Fig. 8.14. This shows that there was a

considerably higher amount of movement in the front sensor, with most motion to about

5 Hz, with a smaller amount to the fiill measwable bandwidth of 9 Hz. The disc sensor

reading shows a much different scenario, with the majority of action to about 2 Hz. The

readings in the graph werr taken at a sample rate of 24 sampleslsecond.

In an excerpt fiom Trial 1 Fig. 8.14, the error over tirne show that the discs had

peaks up to 5 inches h m either side of the set point, with the grratest variation due

mainly to sensor bouncing on lumps of siubble in the unworked stubbie field portion of the
Chaptet 8: Discussion and Analysis

test However, emr peaks of several inches are expected in the field trial. since the soii

topography will change rapidly as the dixer moves acmss the field.

' Error and Sensor Position Relationship


1 Field Test 5

O 20 40 60 80 IO0
Sarnple Number

Fig. 8.11. Example plot of error and sensor position for 100 samples from the PC logger
data fiie for the 5 membetship fuaction algorithm.

w
FFT d front Sensor

Fig. 8.12. FFT plot nom PC logger, h t sensor, for field test 5.
Chapter 8: Discussion and Analysis

w
Fft of Rear Sensor

Fig. 8.13. plot fiom PC logger, disc sensor, for field test 5.

Fig. 8.14. Error plot fiom the 5 membership fuaction algorithm. field test 5. with mean,
standard deviation and variance measurements.
Chapter 8: Discussion and Analysis

Fig. 8.15. Field trial 5 emr from set point, over 1400 samples (78 seconds), with
statisticai measwernents for these data.

Figure 8.15 shows the results of the field aiai. The units for emr, FL,DOERR, are

in decimal, and are the ciifference fiom the set point to the curent depth position as read

by the two N D converters. Each decimal unit corresponds to one hexadecimal unit for the

A/D readings, thus the range of the graph is from 60 to -60,representing the hexadecimal

values 7C to -7C actually recorded by the PC logging program. The approximate number

of sarnples used in this calculation are 1,450, representing approximateiy 78 seconds of

sampling t h e over both unworked stubble, stubble disced once and stubble disced two
Chaptet 8: Discussion and Aodysis

times. These areas are repnsenting différent soil topographies and discer sink rates into

varying degrees of support fiom the soilThe unworked snibble represents very solid soil,

in which the tractor and discer sink o d y about 1 inch, with level soi1 and 1-2 inches of

intermittent straw cover. The area disceci once represents an area with soi1 ndges 4-6

inches deep, with tractor and discer sinking about 3 inches. The area disced twice has a

more even topography, with soil ridges about 2-3 inches deep, but with a higher discer and

tractor si& rate, about 4-5 hches.

The mean of the e m r over these different regions was 0.954 of a hexadecimal A/D
unit, or about 1.0 units considering two signincant digits due to samphg accuracy. This
represents an error overail of approximately 0.10 inches (2 mm), based on the calibration

value of (decimal) 14 hexadecimal units per inch in the calibration sequence. The standard

deviation for these readings was 15.451 units, or 1.1 inches (28 mm). Vkriance was

238.784, which is the square of the standard deviation.

The significance of these results is that although the sensor was moving across the

set point a significant amount, with peaks as many as 4 inches (10.2 cm) fkom either side

of the set point, the seeder was able to maintain a mean e m r within the 1 cm goal set in

the cnteria for the controller to operate with adequate accuracy for seeding depth control.

û.5 Cbpter Summnry


In tbis Chapter, results h m laboratory simulations and field nsults were
presented. WMe stationary testing indoors in the Gamby farmstead workshop and in the

field, minor code revisions were made with the aid of the battery-backed RAM module.

However, after each day in the field testing a major variation in an algorithm or controller
Chaptcr 8: Discussion and Analysis

code procedure, major rewrites had to be conducted off-site. Extra testing of different

fuzzy control algorithms. and possibly an impmved PC logger routine for faster operation

could have been conducted if it was not for the onset of winter 1996. Field results obtained

are only for the 5-membership fuaction algonthm, and although it appeared to work quite

weil for this operation, additional testing of variations to fine-tune this code and compare

it to other membership £bnctions would have added fiutber interestkg results for

cornparison in this research. In all, however, the objective of this work was to test the

suitability of hiuy control for the application of seeding depth control with one-way

discer seeders, and this objective was achieved.

In Chapter 9, Conclusions and Recommendations outhe the contributions of this

work. and present thoughts on fuhue work based on the research in this thesis.
Chaptcr 9: Conclusions and Recoinmendations

CHAPTER
9
CONCLUSIONS AND RECOMMENDATIONS

Improving seed depth conml can improve crop performance. The most common

seed depth control methods and the limitations of their accuracy were described. Fuvy

logic controllers are well suïted for control applications B e seeder depth control, where

the inputs are nonlinear and tirne-Maut. A model of a seeding depth controller

utilizhg fuay logic has also been described. Simulation results of the model were

presented in the fiom of the final structures of the mernbership functions and the resulting

control surface.

9.1 Performance of the Sensors


Field conditions can affect the performance of the depth sensor wheel. It was

found that compacted straw on the field h m the previous harvest was m e r packed by

the action on the wheel, but that the reading would be for the disc depth was shown to be

deeper than it actually was. As a resdt, the disc would be lifted by the erroneous amount.

The fuvy algorithm did tend to low-pass nIter s d impedections in depth, such as that

caused by wheel tracks in the field. However, the "very large" membeahip functions did

cause the discs to move quickly when there were large changes in depth, such as in

drainage ditches and wide nits. The integration actions of the depth gauge tire. mass of the

sensor and time for the hydtaulics to move the disc depth control cylinder also add enough

t h e lag that the discs can adjust to changes in depth 2 m ahead, at the wheel sensor.
Cbapter9: Conclusionsand Recommendations

The front wheel sensor essentidy gave a reading of the amount of main wheel
siakage and discer swivel as it crossed various soil conditions - soil that is previously

cultivated and loose, soil compacted by large agricuiturai vehicles, and soi1 with varying

moisture contents. In soil with straw cover less than 70% [reference on measuring straw

cover] the effect of straw on the depth reading was not significant. DBerent weights of the

sensor, as weil as different tire pressures and even the use of a Buid-nlled or solid rubber

tire codd also be tested for immunity fiom straw aad soil clamp "noise".

9.2 Hadware Observations and Recommendations


In actudy building and testing a field data collection version of the fuzzy seeding

depth controiier, it was found that the construction of the device was critical. Any wires

within the unit that were tw shon or under excessive pressure soon came Ioose or became

disconnected in the vibration of the tractor cab. It is necessary to ensure all connectors

lock into place, and are securely soldered to prevent separation in the connecton.

Likewise, the original sensors had contacts that easiiy corrodeci if not completely covered

in storage. It was necessary to clean the corrosion fiom both the contact ends to prevent

periodic signal interruptions due to vibration and shock as the discer moved across the

field. It was also necessary to ensure al1 wires to the discer were properly secured to

prevent dragging and catchhg on the grouad.

The proportionai valve has a variable speed setting that varied the rate of oil flow

through the main spool. It was found that at the high rate, the discs would respond much

more crisply to controller commands. However, if the discs were raised out of the ground,

thus eliminating soil resistance to movement, the discs would osciïiate across the set point
Cbapter 9: Conclusions and Recommendations

until they contacted the grouod This was noticed using the 5-membersbip hinction

algorithm and the 7-membership fiinction aigorithm, without 50% gain reduction. At that

point, the gnwid would slow the disc gang movement, and stop the osciilation.

9.3 Algocithna Development Rceomarended Impmvements


The= are three additional techniques which would have sped up aigorithm

development: the use of an anaiog simulator. use of a hydraulic vaive and ram driven by a

motorized hydraulic pump, and the use of a soi1box.

An analog simulator can be built out of a combination of RC circuits and

operationai amplifiers, each element of which would mode1 a different part of the

controiler and discer system. Sensor inputs wouid be the combined voltages nom

simulator feedback and an added perturbame, to simulate the changing soil contours. The

action of the wheel sensor assembly can be simuiated as a low-pass filter, with only

changes above the minimum characteristic fkquency of the sensor passing to the

controller. Likewise, the integration action of the hydraulic hoses, hydraulic proportionai

vaive. hydrauiic ram and the soil itself can be modelled with op amps. Thus, an output

voltage would feed tbrough the simulator. with the output (representhg the changing disc

position) feeding back to the senson as a slowly changing signal, at the characteristic rate

of change of the plant king controlied.

In this reseamb, hydraulic conirol routines w e n tested by fust travelling to the


discer's location in a heated workshop near Stony Mountain, setting up the laboratory test

unit with a w w controller code revision to M e r test the characteristics of the hydraulic

proportionai valve/tractor/ram and hose combination, returning to the lab the next day to
Chapter 9: Conclusions and Recommendations

recode a set of control actions. retuniirig again to the tarm to test the code several days or

weeks later. Having access to a hydrauiic valve and ram powered by an electric hydraulic

pump at the University wouid have enabled development of the output parameters of the

fuzzy control algorithm to take place much more rapidiy. Controk code changes couid

be made quickly on a PC located at such a hydfaulic testbed enabling the researcher to

take whatever time is necessary to snidy the characteristics of the system and produce the

desired output. A hydraulic bench apparatus at the University would also have enabled

more detailed measurements to be made of the control action. such as iitres of oil moving

per second, oil pressure, optimization of hose configurations and comections for

minimum oil flow resistance and heating. A more detailed evaluation of different valve

spool combinations, oil flow rates and throitle positions in investigating the optimal

actuation rate could also have k e n dertaken.

A soi1 box, such as the unit in the Agricultural Engineering A ~ e x would


, have

ailowed algorithm and controiler development to continue throughout the winter months

and without the necessity of travelling to a remote location. More extensive testing of both

conventionai and fuuy control algorithms would then be possible, as different soii

contours couid be set up for testing un&r varying terrain conditions.

The simulations done in Mathcad were facilitated by the Version 6.0 capabilities to
program in if-then loops and other iterations Wath96J. Otherwise, the only other option in

punuing an effective simulation wouid have k e n to write it in a programming language,

such as C or C++ - this would have required mon tirne spent on the implementation of the

test code and interface, and less time on evaluation of results. Of course, if the time was
Chapter 9: Conclusions and Recommeadations

avaiiable to p m e this option, a u s e N CASE tool couid have been produced, as outlined

in the next Section-

9.4 Productionof a Fuag CASE Tm1


Having produced the control surfaces in three dimensions and controller outputs in

two dimensions, it becomes obvious how to produce a CASE tool that would provide a

fast method of simularing the results of varying membership fiuiction and d e variables.

Such a tool could also be set up so that assembly code could be produced based on the

shape of the membership functions and the des.The assembler code generation

capabïiity could also be set up for a number of rnicrocontroUers, with a menu for the user

to choose the appropriate program path. The code generation portion of the program codd

use several branches for dinerent defuuification h c t i o n types that can be chosen by the

operator. A general fuuy inference engine can be used for determining rule suengths. The

number and shape of membership functions could be varied by the operator, using not

only point-and-click modifications with the mouse, but also have the option of choosing

md modifying fimctions for different membership fwictioa shapes - such as Gaussian


distributions, normal distributions. and quadratic functions describing the result of a

membership fuaction shape d e t e h e d by other means, such as by a unsupervised

training of a neural network.

9.5 Future Work


In this research, the 5-membership fuay algorithm was tested in the field. It would

be advantageous to extend this into testing of more variations of the huzy control

algorithms. For example, a Gaussian membership huiction s h a p for the Zero membership
Chaprcr9: Conclusions and Recommendations

hinction could be evaluated, with a 3-rnembenhip fhction algorithmto d e t e d e if more

graduai control c m be achieved than was found in the lhratory simulations. The 3- and

7-membership fiinction algorithms could dso be tried in the field. Viriations on

defimification, for example. the mean of maximum, could also be tested to see how well

it works with the hydraulic valve.

In this system, it should be noted that although the control algorithm is based on

fuzzy control, it operates entirely using discrete data. The sensors are imprecise to a smail

degree (although within tolerances for this application). Therefore. the controller

algorithm interprets the analog signals and classifies them by degree of membership of

different membership functions. Rather than undergohg this process in such a discrete

way, fuuy sensors codd be utilited that would sent the controller signals giving the

degree of membership in membersfüp huictions directly.

Fuzzy control is a relatively new conaol method for agriculhira.1 applications.


Control of agicultural implements usually means that heavy machinery is used, which

can be W c u l t to predict or generalize. There are a number of noniinear control

applications that cm be investigated in this field.

This research, concerned with the depth of seeding, is only a smail part of what c m

be investigated for the use of artificial intelligence techniques such as furzy control.

Pesticide and fertiiizer application takes on many forms, with grandar, low and high

volume liquid, mist, gas. and emulsion methods used commonly on the prairies, each with

their own unique challenges. The combination of accurate positioning and a better

understanding of crop responses m e r adds a number of new dimensions that can be


Cbapter 9: Conciusions and Recommendations

explored in these areas. Increased efficiency in the harvesting and handiing of crops can

take the form of reduced combining losses tbrough more accurate machine controls, better

sensors in stored grain and reduced shrinkage whea handliag large volumes. Neural

networks and genetic algorithms are king applied to market data in order to reduce the

risk individual growers and agribusiness enterprises face when planning fùture crop pnces

and saIes levels.

In the area of optimization of ruies, it was found that the controiler performance

could be changed considerably with minor changes in d e s . The use of a neural network

method in deteminhg mies, such as that proposed by Hung m g 9 5 1 that uses a

nonsupe~sedieaming selfsrganizing map to quantize the input vectors into groups, and

then using a Iearned vector quantization backpropagation network to determine the

optimal number of antecedents, consequents and the number of d e s [HeKF91].

9.6 Chapter Ovemew


Recommendations are based on the resdts of the previous Chapter. Appendices A

through E contain the controller schematic diagrams, software flow charts, source code for

the controller, source code for the PC logging program, and an example of Mathcad

simuiation for a 5-membership "template"algorithm.


ANSVASAE EP455 MAR91, Environmental Considerations in
Development of Mobile Agricuitural Elecmcai/Electronic Components.
ASAE 1993.

Brian Armstrong, ' R C design for ûoboded separable fimctions with hear
inputsutput relations as a special case," IEEE Trans. on Fulzy Systems,
Vol. 3, NO.1,72-79,1995.
The Amencan Radio Relay League, Ihe ARRL H'dbook for Radio
Amateurs 1992, Newingtoa Cornecticut: The Amencan Radio Relay
League, 1991.

Naba Barkakati, nie Waite Groyp's Essential Guide to Turbo C,


Indianapolis, Indiana: Howard W.Sams & Company, 1989,304pp.

Borland International, Turbo C UserS Guide, Scotts Valley, Califomia:


Borland International, 1988.

Borland Intcmational, Turbo C Referme Guide. Scotts Valley, Califomia:


Borland International, 1988.

P.D. Bloome, D.G.Batchelder, A. Khalilian and G.G.Riethmuller, "Effects


of speed on ciraft of mage implements in Oklahoma soils," Papers of the
Amencan Society of Agriculturol Engineers Microfiche Collection, fiche
no. 83-1032, 1983.

Nyle C. Brady,The Natum a d Properties of Soils 8th Uition, New York,


New York MacMillan Publishing Co., Inc.. 1974.

Ronald N. Braceweiî, "The fast Hadey transform," Pruceedings of the


IEEE; Vol. 72, No. 8, August 1984.

Paul Buchanan, "Ultrasonic GOra inpth Monitor," B.Sc. Thesis, Dept.


Electncal and Cornputer Engineering, Univ. of Manitoba, Mar. 1986.

E-RL Deane, J.A. Harrison and J.C. Jeffery. "A microcornputer-based


agricuitural digger control system," Cornputers and Electmnics in
Agriculture. 433-42,1988.
References

J. Diamond and W. Pedrycz, VLSI hplementaion of a fuuy flip Bop,"


C&M Conferrne on Electrcul and Cornputer Engineering* Ottawa,
Ontario, 1990.

Richard C. Dorf, Modem Contml Systems, Reading, Massachusetts:


Addison-Waley Publishing Company, 1989,603 pp.

F.B. Dyck, "Automatic depth control for a dixer," Cadiun Agkulturaf


Engineering, vol. 17, no. 1, pp. 47-49, June 1975.

Dean B. Edwards and John R Canning, "Fuzzy control system for an


autonomous vehicle," Pmceedings of the 9th International Conference on
Mathematical and Computer Modellng. Berkeley, California, 1993.

R.A. Froese, ""Aseeding depth monitoring system," B.Sc. Thesis, Dept.


Elecmcal and Computer hgheerhg, Univ. of Manitoba, Mar.1992.

Sylvie Galichet and Laurent Foulloy, 'Fm controilers: synthesis and


equivalences," IEEE Trans. on FU= Systems, Vol. 3, No. 2, 140-148,
1995.

[GKWD8la] D.G.Gunderson, TG.Kkk, I.N. Wdson and J.N. Dyck, "A cornparison of
ultrasonic, ski, and ski-wheel systems for mage depth measurement,"
Papers of the American Society of Agricultural Engineers Microfiche
Collection, fiche no. 81-1602, 1981,

D.G. Gunderson, TG. Kkk, J.N. Wilson and IN. Dyck, "Drift-speed-
depth characteristics of cultivators and discers and their effect on fuel
consumption," Paprs of the Arnerican Sociev of Agricultural Engineers
Microfiche Collection, fiche no 81-1603, 1981.

P. Gong, "Change detection using principal component anaiysis and fuuy


set theory," Canadian Joumal of Remote Sensing, Vol. 19, No. 1, January,
1993.

Joseph D. Greenfield, m e 68HCII Micmcontroller, Orlando, Florida:


Sauders College Publishing, 1991.

Harris Semiconductor, Transient Voltage Suppression Devices, Melbourne,


Florida: Harris Semiconductor, 1994.
Thomas C. Hayes and Paul Horowitz, SNdent MmwI for The A n of
Elecn~nics,New York,New York: Cambridge University Press, 1991.

A. Hadjicbtistodoulou, Athena Dciia and J. Photiades, "Effect of sowing


depth on plant establishment, tillering capacity and other agronomie
characters of cereals," Journal of Agricultural Science. 889: 161-167, 1977.

John Hertz, Anders Krogh and Richard G. Palmer, Inrroduction tu the


nieory of Neural Computatiotz, Redwood City, California: Addison-
Wesley Publishing Company, 1991, pp. 236246,327 pp.

Frederick J. Hill and Gerald R. Peterson, Digital Systems Hardware


Organization and Design, New York, New York: John Wdey & Sons,
1987,601 pp.

R.D.Horrocks and F.D. Clouinger, "Mode1 for predicting emergence of


gmin sorghum," Crop Science, 14:365-367, 1974.

Paul Horowitz and Winneld Hill, m e AH of Electrunics Second Edition,


New York, New York: Cambridge University Press, 1989.

Kaom Hirota and Kanihiro Ozawa, "The concept of a fuzy Bip-Bop,"


IEEE Trans. of Systems, Man and Cybemetics; Vol. 19, No. 5, Septembed
October 1989.

Chuan-Chang Hung, ''Building a neuro-huy learning control system," AI


@en pp 40-49, Nov., 1995.
W. Kinsner, G.Gamby, RA. Frmse and T.Tessier. "A fuuy seeding depth
monitoring and control system" in P m IEEE WESCANEX '93,
(Saskatoon, Canada), IEEE 93CH3317-5, pp. 27628 1,1993.

P.J. King and E.& Marndani. "The application of fuzzy control systems to
industrial processes" in Fuuy Automata und Decision Processes. New
York, NY: North Hoiland, pp. 321-330, 1977.

W. Kinsner and W. Pedrycz, "A configurable fuzzy inference engine using


Logic Ceii Arrays," Pmc. Can. Con$ Elecnicul & Cornputer Eng.;
(Ottawa, ON; Sept. 4-6, 1990). pp 30.2.1-30.2.4, Sept. 1990.

Frank Klawonn. Jorg Gebhardt and Rudolf &se, bbFuzzy control on the
basis of equaüty relations with an example fiom idle speed control," IEEE
Tram on Fuuy Systerns, Vol. 3, No. 3,336350, 1995.
References

Seong-Gon Kong and Bart Kosko, "Adaptive fuuy systems for backup up
a truck-and-trailer," IEEE Trans. on Neural Netwonks; Vol. 13, No. 2,
Match 1992.

I. Leonard and R Maki,"An automatic cutterbar height controller for grain


hanresting machines," The Anrerican Sociev of Agncultural Engineers
Microfiche Collection, Paper No. 90-1560.1990.

Richard Lord, 'FFT for the 6800," Byte; pp. 108-119, Febmary 1379.

P.J. MacVicar-Whelan, "Fuzzy sets for man-machine interactions,"


International Journal of Man-machine Studies; 8,687697. 1977.

E. H. Mamdani, 'Twenty years of fuuy control: Experience gained and


lessons learned," Pmceedings of the 2nd International IEEE Conference
on Fuuy Systems, San Francisco, 339-344, 1993.

E.H. Mamdani. "Applications of hiuy set theory to control system" in


Fuuy Automara and Decision Pmcesses. New York, NY: North Holland,
pp. 77-88, 1977.

Fuzzy Systems Engineering, Manifold Editor, San Diego, California:


Fuzzy Systems Engineering, 1992.

F.D.MartAoff, "The development of a guide on surge voltages in low-


voltage AC power circuits," Proceedhgs of the 14th IEEE ElectricaV
Elecmnics Conference, Boston, 1979.

MathSoft Inc, Mathcaù User 's Guide, Cambridge, Massetchusetts:


MathSoft Lnc. 1996,694pp.

Raaier Palrn, "A huzy logic controller for an ABS braking system." IEEE
Trans. on Funy Systems, Vol. 3, No. 4,38 1388. 1995.

Mark McQuilken and James P. LeBlanc. Digital Signal Processing und the
Microcontroller, Phoenix, Arizona: Motorola Literatuce Distribution, 1992.

Merriam-Webster, hcorporated, Merriam- Webster Collegiate Dictionary,


Massachusetts: Memam-Webster,
Tenth Edition, sp~gfïeld,
Incorporated, 1993.
JE.Momson. Jr. and TJ. Gerik, "Planter depth control: Predictions and
projected effects on crop emergence, Part I," T r m . MAETvol. 28, no. 5,
pp. 1415-1418, SeptJOn 1985.

J.E. Momson, Ir. and T.J. Gerik, "Planter depth control: Empincal testing
and plant responses, Part II," Trans. ASAETvol. 28, no. 6, pp. 1744-1748,
NovJDec, 1985-

Moto9 la] Motorola, GPT General Pwpose îïmer Rcference Manual, Ph~enÿc.
Arizona= Motorola Literature Distribution, 1991.

Moto9 1b] Motorola, Parts List and Schematic Diagram for REVision E
M68HC16EVB printed cincuit board REWsiion 5 M68HC16EVB schematic
diagrams, Phoenix, Arizona: Motorola Literature Distribution, 1991.

Motorola, MC68HCI6Zl User's Manual, Phoenix, Arizona: Motorola


Literature Distribution, 1992.

Motorola, ADC Analog-to-Digital Converter Reference Manual, Phoenix,


Arizona: Motorola Literature Distribution, 1992.

Motorola, QSM Queued Serial Module Reference Manual, Phoenix,


Arizona=Motorola Literature Distribution, 1992.

Motorola, System Integration Module, Phoenix. Asizona: Motorola


Literature Distribution, 1992,

Motorola, TMOS Power MOSFET Transistor Data DL135Zü REV 4,


Phoenix, Arizona: Motorola Literature Distribution, 1992.

Motorola, M68HC1621EVB User's Manual, Phoenix, Arizona: Motorola


Literature Distribution, 1992.

Motorola, lechnical Summary 16-Bit Modular Microcontroller


MC68HCI6ZI T S D , Phoenix, Asizona: Motorola Literature Distribution,
1992,

Motorola, Linearflnteflace ICs Device Data Vol. II DL128/D REV 4,


Phoenix, Arizona: Motorola Litetature Distribution, 1993.

Motorola, Snrall-Signal Transistors, FETs and Diodes Device Data DL126/


D W 4 , Phoenix, Arizona: Motorola Literature Distribution, 1993.
References

William E. McCarthy and Mohamed BE. Trabia, "Selection of


membmhip sets for optimal penormanœ of a fuay logic controller,"
Pmceedings of the 9th Intenautional Confemce on Mathematical und
Cmputer Mdelling, Berkeley, W o m i a , 1993.

R R M q h y and A.C. Amy, 'Th emergence of grass and Iegume


seedlings planted at different depths in five soi1 types," Journal of the
of Agmnomy. 3l(1): 17-28, 1939.
American S o c i e ~

Mark A. O'Neill, "Faster than fast Fourier," B M 1 pp. 293-300, April


1988.

J.A. O'Suiiivan, "Evaiuation of a polaroid ulaasonic proumity


transducer," Journul of Agricultural Engineering Research; 34, 63-73,
1986.

Henry W. Ott, Noise Reduction Techniques in Elecmnic Systems, Second


Edition, New York, NYi John Wdey & Sons, Inc. 1988.

PADS Software Inc, PADSLogic Evaluation Package User's Manuai,


Littleton, MA: PADS Software Inc, 1992.

Ranier Palm, "Scaling of fùzzy controllers unis the cross-correlation,"


IEEE Tmns.on Funy Systems. Vol 3, No. 1, 116-123, 1995.

G.S. Pask, J.N. Wdson and G.C. Zoerb, "An automatic height-of-cut
conaol system for windrowers," 1973 Annual Meeting, m e Anterican
Society of Agricultural Engineers, Paper No. 73-155, 1973.

W. Pedrycz, G. Bortolan and R Degani, '6Classification of


electrocardiopphic signals: a hizzy pattern matching approach."
Artilcial Intelligence in Medicine, (3) 2 11-226. 1991.

wtold Pedrycz, ''Fuzy neural networks and neurocomputations," Fuuy


Sets and Systems, (56), 1-28, 1993.

W11liam H. Press, Saul A. Teukolslq, William T-Vetterling and Brian P.


Fianger, Numencal Recïpes in C nie An of Scientiic Computing Second
Mition, New York,New York: Cambridge University Press. 1992.

Bradley L. Richards, ' m e n facts get ruYy," BYTE, pp. 285-289. April
1988.
[Schu89] John K. Schueiier. "'Digitalsimulation of combine ceel and forward speed
controllers," Cornputers and Electmnics bt Agncuftute, 459-7 1. 1989.

[Sche891 Francis J. Scheid, Nmerical Analysis 21ed. New York, New York
McGraw-HiIl Book Company,1989.

[ShDH9 11 Bumsoo Shin. Roy B. Dodd and Young I. Han, '%round d a c e detection
using dual-fiequency continuous-wave radar," 1991 Intemutional Mnter
meeting, m e Americm Society of Agricultural Engineers, Paper No. 91-
3540.1991.

Senstek, Operaror's nuutual DC-3, Senstek, Saskatoon. Saskatchewan,


1989.

A. de Sam Lazaro, VS. Manoranjan, DB.Edwards, A. Athdye. "'Design


and optimization of a f i m y controiier," Pmceedings of the 9th
Intematio~lConfemce on Mathematical and Compter Modelling,
Berkeley, California, 1993.

Donald W. Sunderman. "Seedling emergence of winter wheats and its


association with depth of sowing, coleoptile length under various
conditions, and plant height," Agmnomy Journal, 56(1):23-25, 1964.

T. Tessier and W. Kinsner, "Fuuy modemg of a seeding depth control


system," Proc. 9th Int. Con$ on Math. und Comp. Modelling. M y , 1993.

T.Tessiet and W. Kinsner, "ImpIernentation of a hiay logic based seeding


depth control system," in P m . IEEE WESCANEX '95, (Wi(Wipeg,
Canada), IEEE 9SCH3581-6. pp. 489-494. 1995.

Texas Instruments Tncorporated, Operationul Amplijiers a d Comparators


Dota Book Volume A, Dallas, Texas: Texas Instruments lncorporated
Literatwe Response Center. 1994.

Texas Instruments Incorporated, Opemn'onal Amplijîers and Cornparctors


Dura Book Wme B, Dailas. Texas: Texas Instruments Incorporated
Literature Response Center, 1994.
N.D. TUet, "Automatic guidance sensors for agriculniral field machines:
A review," Journal of Agricultural Engmeering Reseurch; 50. number 3,
November 1991.
Donald W. Trim,Engineering Mathematics, W ~ p e g Manitoba:
, Ruskin
Publishing Company, 1989.

B k i l Walsh, "Fuzzy logic: Concepts to constructs," A2 Erpert, pp 26-39,


Nov., 1995.

WB.Whalley, 'Development and evaluation of a microwave soil Moistw


sensor for incorporation in a n m w cultivator the," Journal cf
Agricultrtrul Engineering Research; 50, number 1, September 1991.

W.R. Whaüey, T.J. Dean, P. Izzarci, 'Evaluation OC the capacitaace


techmique as a method for dynamicaily measuring soil water content,"
Jouml of Agricultural Engineering Research; 52, number 2, June 1992.

Tom Williams. "Fwq logic is anything but rUny," Cornpufer Design, pp.
113-127, A@, 1992.

Tom Williams, "New tools make fuuyheural more than academic


amusement," CornputerDesign pp. 69-84, July, 1994.

Weed Science Society of Amerka, Herbicide Handbook of the Weed


Science Socieîy of Arnerica Fifh Edition - 1983, Champaign, m o i s :
Weed Science Society of America, 1983.

Ronald R. Yager, Dimitar P. Fiiev, Essentials of Fuuy Modeling and


Conml. New York, New York: John Wdey & Sons Inc., 1994,388 pp.

M. Yasin, RD. Grisso and G.M. Lackas, "Non-contact system for


measuring tillage depth," Cornputers and Electronics in Agriculture,
7: 133-147, 1992.

R.R. Yager, S. Ovchinnikov, RM. Tong, H.T. Nguyen, Fuuy Sets and
Applications: Selected Papers by LA. M e h , New York, New York: John
Wiley & Sons hc., 1987.

Lotfi A. Zadeh, "Fuzzy Sets." Information ami Connol8.338-353, 1965.

Lotfi A. Zadeh, "ûutline of a new approach to the analysis of complex


systems and decision processes," IEEE Trans. on System, Mun, und
Cybemetics, SMC-3,2844,1973.

Q. Zhang, J.B. Litchfield, I. Bentsman, ''Fuzzy prediction of maize


breakage,"Joumal of Agricultural Engineering Research: 52,7740, 1992.
References

[ZiSc93] Klaus Zinser, Roif Scbreiber, "Fuzzy logic - an innovative technology


hoIding grrat promise for automation systems," ABB Review, pp. L3-20,3/
1993.
Appendix k- PC Logger Source Code

The schematic diagrams were fint produced in PADS, then edited for size as a

postscrîpt nle in Adobe Illustrator. Several parts were not found in the libraries, and had

to be made. Tbis included the MC68HCMZl MPU, the MC145450 serial interface, and

the inductors.
wrnr; TOM f ESSlER
R
DRL.I).
WI e, im
DWD;
ul a, itn
UTICITZINC FU2ZY COGIC
CKCNID; DA IlD.
CWi WC W. MVi

FDC 10 11.0
Appendix B: Software Fiowchart

B.l ControUer Initiaüzation

Once initialization is complete, main program execution begins (box Al).

SPEED=16.78 MHZ, SET K REGISTERS, COP OFF

biUTXRE ND PORT
SET FOR 8-BIT OPERATION

1 h l I T b U 1 . E PULSE W T H MODULALION OUTPUT A 1


1 SET FOR 128 HZ FOR PROPORTIONAL HYDRAULIC VALVES 1
w
1 LOAD MïML REGISTER VALUES 1
1 FOR TIMERS. SENSOR POSITIONS, CALCUU\TION C O N S T M S 1

DISPLAY WELCOME MESSAGE

INITIALIZE LCD
INlTiALIZE REGISTERS, SET UP CHARACïER DISPLAY MODULE
DISPLAY WELCOME MESSAGE
8.2 MainPmgrsmExecution
The main program consists of eight main parts. Each part is a subroutine that is
executed in sequence:

1. CHECK-KEYS - This module checks to see if a key has k e n pressed. It scans


the keypad on every loop. If a Iow signal is detected on the keypad Port F, the code

immediateIy branches to a key debounce subroutine. m e r 10 ms, Port F is then rescanned

to see if a keypress (iow) signal is still present. If so, it then identifies the key pressed and

jumps to the appropriate function.

2. SAMPLE - Each of the two sensors are sampled in this subroutine. If the

controller is in normal operation mode, the signals are passed onto the next subroutine. If

it is in a single sensor mode, only the respective sarnple is passed on.

The sensors are highly h e a r resistive elements operating by indicating the


position of a contact on a circular track. In order to preserve accuracy in reading the sensor

positions, a theta correction factor is employed. This works by taking the sine of the angle

from the "zero" position of the sensor Liakage, where it is precisely 90 fiom the sensor. In

order to ensure calculaiion speed and accuracy, at l6-bit sine look-up table is used, rather

than having to calculate each value by division.

Initial conversion values for the theta correction subroutine are written to the

respective registea during controller initialization. This allows the operator to raise the

implernent for transport to the area of use. Once at the field, the operator then goes through

a calibration routine that sets the registers with the correct conversion and setting values

for the current soi1conditions and desired depth.


Appendix B: Software Flowchart

In order to prevent excessive nnindoffemr throughout the comction calculations,

the sensor values are converted to thousands of an inch in a 16-bit format. This process

includes a hexadecimal to decimal base conversion subrouthe.

3. ERROR-CONVERT - Once the positions of the sensors are determined and


corrected for theta error, the error is converted fiom thousands of an inch to tenths. This

facilitates the calculations that WUinclude only addition, subtraction, and maximum and

minimum comparisons.

4. ERROR-BUFFER - In this routine, the change in emor is deteimuied by taking


the present exror reading and subtracting it h m the enor reading 10 (CHECK) samples
previously. This equates to about 1/2 second previously, the equivaleot of one metre of

distance covered at 8 km/hr. This value is written to the CHANGE-IN-=OR variable

for use in the next routine.

5. RIZmTEST - The hiuy algorithm is based on the Mamdani hizzy control


algorithm. Membership functions were originally detemiined by using a Microsoft

Windows graphics-based fuuy logic simulation and anaiysis tool. FIDE (Fuuy Merence

Development Engine) ftom Aptronix. The different of the membership functions were set

up and nui through a simulation.

Although fùzzy algorithms can e a d y be coded in a high-level langage such as C,

FIDE speeds up development with increased accuracy by the use of several valuable

development tools. Each rnembenhip bction can be viewed graphicdy, and quickly

changed using the mouse. Likewise. FIDE instantly generates the fuzzy control surface for

any set of membersbip fimctions and inputs. Once a given combination of membeahip
huictions produce an acceptable gain level of monotonie contml, a visual simuiation can

be nui with inputs h m both artSciaUy generated signals and acnial recorded field data.

produce the appropriate resuits, FIDE can


If, at this stage, the conaol looks like it WU

immediately generate 8-bit (MC68HCll compatible) assembler code. This code can then

be pasted into the controller code and compiled The code automaticaliy takes into

account scaling factors for sensor inputs and the hydraulic conml output signal.

Therefore, code is produced quickly and accurately that can be tested in the field.

In this routine, the fuuy Iogic algorithm operates the four steps of determinhg a

control decision:

- The input values ERROR and CHANGE-IN-ERROR are fuuined according to


the lookup tables generated fiom the membership functions in the FDE simulation. The

degree of membership for each membership fuoction is then passed on the fuzzy inference

engine.

- The fuzzy values are evaiuated according to the des. The DOF for each d e is

determined.

- The rules are aggregateà, and the d e s that apply are determined.
- The fuzzy decision fiom the nik d y s i s is defuruned. The algorithm uses the
singleton method of defuuincation. Aithough this methd is not as elegant as the COA or

MOM methods, it is much more efficient to code and execute in assembler, md does

provide sufficient 8-bit accuracy for this application.

The output range for the controiler is between decimal 120 ta 135 (CHECK).This
is due to the characteristics of the proportional valve used and the hydraulic system of the
Appcndix B: Software Flowchan

tractor used. The tractor used in testing was a Case International 5240 (CHECK)with a

closed center hydraulic system. This type of system maintains constant pressure at all

times, so will provide a consistent hydraulic conûol respow regardless of the demands

on the system.

6. HYD-CONT - Now that a fury decision has been produced, the control signal

is sent to the pulse width modulation unit A (PWMA) of the MPU. This modulates the

duty cycle of a 128 Hz signai that controls two solenoid valves that control the position of

the main spool on a proportional hydraulic valve. By having a constant, opposing 128 Hz

pulse on the main spool, a constant tiow of oil keeps the main s p l in constant motion.

The motion is not enough to significantly change the position of the hydraulic ram on the
seeder, but is essential to keep vaive response t h e at an optimum level. The duty cycle of

the two srnail solenoids that control the main spool are equal when the main spool is in the

proper position. When the seed depth (disk position) has to be changes, the spool must be

moved off center by changiag the duty cycle of the tow small solenoid. This is done by

changing the duty cycle of the signal h m PWMA. The signal is split, with one signai

controlling one solenoid and the other. inverted signal controlling the other. M e f o r e .

when the duty cycle is changed, one soleuoid wiU open wider, with the other opening with

an equal, opposite n m w e r opening. The Merence in pressure moves the main spool one

way or the other, thus acting as a hydraulic amphfier by ailowing a large volume of oil to

move from one side of the seeâer hydtaulic cylinder to the other.

-
7. DISPLAY-DEPTH Now that the control signal has been sent to the discer, the

controiier moves into the LCD depth display mutine. The depth error value is compared to
AppendIx 8: SoftwareRowchart

the soi1 suffice value, and the Merence is displayed on the LCD. The routine indudes a

subroutine that converts the depth number to inches or centimetres and tcnths of an inch or

millimetres. Once ail the numbm have k e n calculated, the LCD display routines are

c d e d to put each character on the screen. The unit preference c m be selected by the

operator.

-
8. SEND-DATA In order to subjectively test the performance of the controiler, a

serial communication data logging routine is utilized. Data read h m registen in the

controiler is sent to a laptop computer for saving in a log nle and later aaalysis.

Data is read nom the ERROR, CHANGEEINdERROR, and OUTPUT registers in

order that these calculations cm be checked. This data allows cross-checking the

controiler fuzzy decision with the expected output fiom previous simulations. Also, if any

changes are made in the field, the results of these changes can be recorded and monitored.

Sensor position information is important to ensuring that the ERROR and

CHANGE-IN-ERROR calculations are correct. By baving the raw %-bitAID converter


readings over t h e , the entire process of calculating ERROR CHANGE-IN-ERROR,the

fuvy inference process and finai output can be evaluated.

The sister PC routine operated by checking for valid (new)data king in the serial
buffer, reading the data, and sending an achowledge signal. Once received, the controIler

increments an index, and sends the next data byte. Both the coatroller and the PC are

synchronized to prevent data skew. In total, 10 bytes are sent per sampling instance. The

PC logging program automaticaiiy formats the data for saving into an ASCII file for easy

importing into a spreadsheet, mathematics or signal analysis program. As data is k i n g


Appendix B : Sofiware Fiowchart

coilected, a bar graph display on the PC alIows the operator to monitor the pmgrrss of the

logging and control operations, thus detecting obvious problems early.

The present system nuis fast enough to log data 23 times a second. This is

equivalent to one sample being taken every 7 cm (2 1R inches) at a speed of 10 km/hr (6

mph).
The SEND-DATA routine is commented out before compiling for normal. non-
logging operation. When the controiier has hished this routine, it loops back to

CHECK-KEYS to begin the main contrai loop over again.


FOR DEBOUNCE ROUTINE
Appendix B: Software Flowchart
B.2.2 M S E D - P O S . O N S m
This fuaction is initiaiized by hitting the "A" key on the keypad. It enters a menu
of three choices. in which the operator can select '7)" for setthg sensor modes (front

sensor only, rear ody, or both), "1" for setting the seeder raised position for hirris and

transporting, and "2'' for setthg the units to either impaial or meûic values.

s KEY PRESSED?
8.2.2 .a Settr'ng Disk Ruised Position

r -
DISPLAY PJSfRUCnONS CHOOSEMODES 1
Appendix B: Software Flowchart

b
KEY PRESSED?
Appendix B: Software Fiowchart
B.2.3 Mo ~ & u P Appendu B: Software Flowchart

This key comrnand is for raising the disks out of the ground for hims and

transporting. The discs are lowered when the "Fkey is hit, which resumes normal

controlier operation.
[3)i
KEY PRCSSED?
r7
MECK KEYS

b PRESSED?
Appendix B: Software Fiowchart

In this routine, the calculation, scahg and conversion factors are set for the
particular sensor/discer implement configuration in use. Once stmed by pressing the "E"

key, the operator is given thme calibration choices: 'Y)" for setting the position where the

sensor linkage is exady 90 between each a m , "1" for calibrating the disk sensor height,

and '2" for calibrating the front sensor.


Appendix B: Software Fiowchart

8.2.6 .a 90 Sensor Ann Position Set

v
1DISPLAY INSïRUCiiONS - POSITION SENSORS 90 SENSOR ARMS 1
-H~+KEYTOSTORE]
I

SïûRE VALUE FOR USE M CALIBRATION ROUTLNES 1


I
8.2.6 .b Disc Sensor Calibration

[ STORE VALUE FROM DLSK SENSOR 1


I

' CALCULATETHE SCALE FACllOR FOR DEPM


BY FIM)auG THE LENCM OFTHEHYPOTENUSE
FOR A RICWEANGLETRIANGLE
Appeadix B: Software Flowchart

8.2.6 .c Calibrate Front Sensot

C
I
* ACfOR FOR D m
BY FINDiNG THE LENGï€fOFTHE
Appendix B: Software Flowchart
8.2.7 MOVETO-DOW
This routine is used to Iower the disc to the fieId for use in no& controUer

operation. It is used in conjunction with the MOVETOOUProutine. M e n the "F' key is

hit on the keyboard. the discs retum to their set seeding depth.

+ '
F KEY RESSW

w
1 C O N T R O RESUMES
~
1
NORMAL OPE RATIO^
Appendix B: Software Ftowchart

B.2.8 Sample Depth Senson


Appendix B: Software Flowchart

B.2.9 ERROR-CONVERT
Routine to convea the error Born 1000's of an inch to tenths in hexadecirnal-This

converts it to a form compatible with the fuzzy inference engine and for display on the

LCD.
Appendix B: Software Flowchan

B.2.10 ERROR-BUFFER
Routine to calculate the change in enor fkom the 10th previous sample.

w
CAUlLltATECHANGE M ERROR -
ClfRRENT ERROR COMPARED 'ID
'I

IO SAMPLES eREVIOUS
B.2.11 FUZYïEST
NZZYTEST produces the fuPy decision, based on the inputs, ERROR and
B.Z.12 HYD-CONT
Routine to scale the hiuy output decision and send it to the hydrauiic valve

solenoids.

APPLY ANY NtZDEû SCAUNG FACTURS


fO COMPENSNE FOR VALVE TYPE
Appendix B : Software Fiowchart

8.2.13 DISPLAY-DEPTH
Routine to convert f3om 1000's of an inch to tens and inches, or centimetres and

milimetres, and display on the LCD screen.

DMDE ERROR (IPJ 1000'yINCH) BY DECMAi. 10


lNHE%FORMATmBRWCDOWNm~
OF 10
Appendix B: Software Fiowchart

B.2.14 S m - D A T A
Raw AM3 serwr nadings. error, change in emr and the output fiizzy sigal are
Appendix C: Controuer Source Code

This appendix contains the code usedin the Fuzzy Logic Seeding Depth Controuer

to sample bth sensors, determine the fiinv output and control the hydraulic valve

controllhg the seeder. The order in which they appear is (1) the make file for compiling.

(2) the fuay controiier code, (3) the table of equates for the register locations in the

MC68HC16, (4) the initialization routine for the reset vectors. and haUy (4) the
initialization routine for the intemipt vectors. Oaly one intempt is utilued in the

controiier code, the KEYPRESS i n t e ~ pused


t in the debounce routine.

Compile Make me: DEPTaROMAM


********************************************************************

INCLUDE 'EQUATESASM' *table of EQUates for common register addresses


INCLUDE 'ORGOOOOOASM' *initiaiize met vector
INCLUDE 'ORG00008.ASMt *initialize intempt vectors

IEJCLUDE 'field2,ASM' *Depth controllerequates table and main routine


*
BDM: BGND *EXCEPTION VECTORS POINT EERE
*ANDPUT THE MPU IN BACKGROUND MODE

*O -
FELD2ASM Fit field operational version, "
*O Version 2 logs data, and does not iniualize tbe"
*O calibration values-the SRAM is battery-backed. The "
*O values alteady exist in RAM before this version is "
O
*O NU.
Appendix C: Conaoller Source Code

*O This version series has a înd hypoteneuse "


a

*O and calibration routine forthe fiont sensor


*O Enor change is now in cange fion O to FE rather than
in the range b m O to 7F. as in FUZZYZASM O

Can provide Mo to flddatac on the serial port, "


*O

*
*O iacluding emr, change in enor, and fiiny control '
*O signai, once lhis fiinction is uncommented in MAIN.
*O O

*O Since the fiizzy engine goes in the opposh direction


*O the 25 GPM hydraulics move, the HYD-SIGNAL output of
*O the fuzy engine is inverted-ie- 80 is made 7E. O
This same place in the code is good for scaling the "
simal to fii the valve-it is diviaed bv 2 here to "
*O
*O

Changed "BLE" to %PL" in setd &pth setaag to


prevent code fiom jumping to mettic- Aiso. commented
out the inch conversion steps a few iines below this
code.
This way, the error d l be calculated in 1000's of
an inch, not something divided by 60
Set the variable "INPUTSwfor the emr, output to
the S C I routine to the PC logger- INPUTS is also set
to be cleared at the beginning of program execution
so an enoneous value is not sent for the lower byte,
The value of INPUTS is ais0 byte-flipped so it is
properly recorded by the logger.
t*ft***L*t*f*********L**&t**~*****ttf*f****ZLfitt*ti*f*f**
* -1nitialize the ports on the
* MC68HC16EVB board and nrn the main
* routine and keypad mutines
* ***Ports assigned:***
* Keypad- Port F
* N D converter- Port AD
* LCD- Pon GP (&ta) and S M (instnictions)
* Output- Port
*
..........................................................
ORG $200 *start at $200
include 'initsysasm' *set K registers, COP off, speed 16.78 MHz
include 'initram.asm* 'tuni on Standby RAM (SRAM)at $10000
include 'initsci.asm' *set sci baud rate to 9600*enable
*reCrtrans on sci

*Set up Port F for the keypad


*Write to PORTF to set up as U0:
Appeudix C: Conaoller Source Code

LDAB #$O0
STAB ADCMCR *for stoP/fieezelsupeNisormodes-setto normal
*LDE #!KM83 *10-bit resoluaon
LDE #$O003 *%-bitresolution and 8 AiD clock penods (fastest)
STE A D C I Z O *NDcoatrol register O-set up for &bit conversion
*STE ADCTLI *EXP-1. CONTROL REGISTER I

*Set up Port GP and S M for LCD


*
**********************************************************
LDD n$OOFF
STD CSPGRO *configurePMS CS3-CS5port C of S M FOR Il0
LDAA #$O0
STAA
- - - - - CSPDR *CLEAR BITS OF PORT C DATA REGISTER
LDD #&Foo
STD PDDR *Ensure GPT data direction register in output only
LDD #$O000
STD OClM *Ensure OC1 Action Mask Register can't affect pin
*Write to GFTPDR to output &ta

*
*Set up GPT PWMA for 128 HZ
*
**********************************************************
LDE #$O008 *256 hz
STE PWMC *n$0018=128hz, #$0028--64 hz, #$0038=32 hz

*Save initiai vaiues for seeder positionhg


*
- --.- - .---- - - - . - . .- .- . . . . . .... . - .... ... . . . . . . . .

LDAB #$O1
TBEK * point EK to bank O for i€AM access
LDAA a 0 9
S?AA CXRC-ERROR-BUFFER ;load $A into circdar cbg in error buffer
LDE #!§FFFF
STE m s
LDE #SIOFF %ex for 2.56 cmfinch, times 100
STE CM,COEN-FACTOR
CLRE
STE INPUTS
STE DEPïH-IOINCHES
STE OP,DISPLAYYON
STE SEEDDEPTEI-ERROR
STE PREVIOUS-ERROR
STE ERRORCHANGE
STE SIGN-FLAG
STE KEYCHECK
STE ADC-CHANNEL
LDE #ERROR,LABLE
XGEZ
Appendix C: Controller Source Code

LDE fi9999
STE HYDRAUL-TIMERI
LDE #$O004
STE HYDRAUt-TlhdER2
LDE
STE HALFEC-INlT
LDAB #!§ûF
TBEK * point EK to bank F for registeraccess
**********************************************************
* Initialize Calibration Factors
*
**********************************************************
* LDAB 4601
* TBEK point EK to bank O for RGM access
* LDE
* S E
* LDE
* STE
* STE
* LDE
* S E
* LDE
* STE
* LDE
* STE
* LDE
* STE
* CLRl
* STE CALIB DEPTH
* LDE #$1~00-
* STE EM'OTENEUSE,DISC
* STE HYPOTENEUSEJRONT
* LDE #$OODE
* STE FRONT-GROUNDUNDZERO
- -

* LDAB #%OF
* TBEK point EK to bank O for RAM access

*
*NTKALIZE THE LCD L C D - m configure font, cursor
*
**********************************************************
LCD-INIT LDAA #$38
STAA GPTPDR *CONFIGURE LCD AS &BIT D m LENGTH, 1 DISPLAY
*LINE, FONT 5 X 10 DOTS
JSR LCD-NST
LDAA 4601 *clear the display, pu& cursor at position O
STAA GPTPDR
JSR LCD-WST
LDAA #$OC *turns on display, cursor on and blinking
STAA GPTPDR
JSR LCD-INST
LDAA S80 *SETDDRAM ADDRESS
STAA GPTPDR
JSR LCD-INST
*Display initial LCD message
LDX MEETINGS *point to the appropriate ASCII string
JSR SEND-STRING *print string to Icd
Appendix C: Controiler Source Code

JSR ONESEC-DELAY
LDX UGREETINGS2 *point to the appropriate ASCII string
JSR SEND-STlUNG * p ~string
t to Icd
JSR ONESEC-DUY
LBRA MAIN

LCD-iNST
LDAA MO0 ~ ~ IN GPrPDR
*WRITE INSTRUCTIONSTO L C D - INST.
JSR LCD-DELAY *****EXPERIMENTAL-DUE
TO OC NOT WORKING ON DUT
LDAB #SM
STAB CSPDR *SETENABLE HIGH
JSR LCD-DELAY
STAA CSPDR *SET ENABLE LOW
RTS *GETO ü ï T A HERE
LCD-DELAY:
LDAB #$O1
TBEK
NOP
NOP
NOP
NOP
STE TEMP-DELAY2 *put previous data in here so you don? lose it
LDE #$OOFF
STE TEMP-DELAY
LCD DELAY-DEC:
-DECW --DELAY
BGT LCD-DELAY-DEC
LDE TEMP DELAY2
LDAB #$OF-
TBEK
RTS
CLEAR-DISPLAY: *resets display to prevent pmblems
LDAB #$OF
TBEK
LDAA #$O1 *caiiedjust before info is dsiplayed
STAA GPTPDR
JSR LCDJNST
LDAB 4601
TBEK
RTS
Appcndix C: Controller Source Code

* MAIN R O U T I N E 4 keypad scanner, sensor sampie


* subroutine, fiiay logic decision routine, hydraulic
* conuol output, depth and LCD display submutine,
* and sending data to the PC for logging resuIts-
* Uncomment JSR SEND-DAiA to start data logging.
*********************************************************************
MAIN:
JSR CHECK-KEYS ;set if a key has been pressed-if so, debounce
JSR SAMPLE ;simple the 2 sensors via A(DO and ND1
JSR ERROR-CONVERT ;convert emr h m 1000's inch to IO'Sin hex
JSR ERROR-BUFFER ;calculatechange in enor for fWzy mutine
JSR FUZZXEST ;calculate the fiizzy decisioa
JSR HYD-CONT ;output the signal to the hydaulics
JSR DISPLAY-Dm ;display depth and messages on LCD
JSR SEND-DKîA ;log error, error change, and fUsr decision on PC
BRA MAIN ;loop back for next round

* *
*KEY CHECKING ROUTINE: CHECK-KEYS read port F to see ifany keys hit *
* RETORN-DEBOUNCE program rems here fier debounce intemprs then *
* checks key fiinction e
* DEBOUNCE intempt 22 times thea recheck key for signal
* KEY-IRQ actions taken on each intempt-int disabled afier 22 times *
* READ-K.'Scheck key id. with READ-COLUMN,KEY-ID 1,KEYKEYID2, KEY-IDED, *
* HEXCONV (which retunis the key's id in KEY *
* *

CHECK-KEYS:
LDAB #$OF
TBEK
LDAA WbFO *Set al1 column lines low
STAA PORTFO
LDAB PORTEQ *Lod PO-
CBA *See if any keys are pressed-any high nibble bit is set
BNE DEBOüNCE *Sets up the GPT to intempt the CPU 6 times
*to allow for at least 20 ms for tbe key pressed
*to stop bouncing. On the 6th intemipt, the keypad
*is read to determine whicb. if any, key was actually
*pressed.
RTS
RETURNRETURNDEBOUNCE:
NOP *HAVING TROUBLE WfTH #SOL NOT GûING INTO acc B
NOP *WHEN RETURNING FROM INTERRUPT-SO ADDED NOPS
NOP
NOP
LDAB #O1
TBEK
TSTW KEYCHECK
BNE FINISHED KEYS *if you don? want to id the key yet, RTS
JSR HEXCONV-
LDAB a 0 1
TBEK
TSTW HEXKEYYrn
BEQ FINISHED-KNS
JSR CHECK-FUNCîïON
FINISHED-KEYS :
Appendix C: Conuoller Source Code

RTS
DEBOUNCE:
LDAB #$O1
TBEK * point EK to banEr O for RAM acccss
LDAA 6 1 6
STAA IRQICOUNT *Put the countdown amount for 22 IRQ's in standby ram
CLIU)
STD iR&DONE *initialite to prevent repeatkg IRQ in endiess loop
CLRW OP,DISPLAYYON
LDAB #$OF
TBEK
LDAA 6 7 3 *Enable the pulse accumulator counter to work, gated
STAA PACTL %de, so that it will count & intemupt cn demaod
CLRA
STAA PACNT *Set pulse açcwnulator counter to O
TPD * T d e r CCR to Acc. D
LDD #SûOAO *Set up D for clearing CCR and setting IRQ mask to 5
TDP *Tramfer D to CCR DDR is now ready to accept iat 5
*fiom the GPT timer overflow interrupt.
NOP *NOPS to add t h e for the 286 debugger to catch up
NOP
NOP
LDD HO086 *MCR DOESN'T EXST IN THE EQU-S TABLE!! ït's caiIed
*GPTMCR
STD GPïMCR *Store lRQ 6 for IMB to module configuration register
LDD #$4004 *Enable OC4 intempt in the QSM,and set timer
*rimer prescaler to 64-intempt every 64*$FF clocks
*equal to 0.98 ms-20ms delay, read on 22nd in^
STD TMSKI
LDD #$7660 *Set GPT intemipt pnority to OC4 (number 7),
STD ICR *intemipt level to IRQ 6, vector base address to 6
*6X, so 6* l6=% in decimal.
*so, IRQ vectot will be 67.
*The CPO decodes as 67*2 by
*lefi shifting the iRQ vector, using IRQ seMce routine
*label at location $134. Changed label BDM at '36"
*to KEYJRQ
BRA RE'ïüRN-DEBOUNCE *Now tbat the intempt is set,return
*and let the keyboard be read by the intempt routine
KEY-IRQ:
NOP
NOP
LDAB 4601
TBEK * point EK to bank O for RAM access
TSTW IRQ-DONE * set in HEXCONV
LBGT RETURN-DEBOUNCE * get out if keys akeady read afier RQ's
DEC IRQ-COUNT *Decrement the counter for each intempt request
LDAB #$OF
TBEK point EK to bank F for cegister access
LDD #$0000
STD TFLG1 *Clcar the GPT intcrrupt Bag so the CPU isn't
*internipteâ again immediately following Rn
LDAB #$O1
TBEK * point EK to bank O for RAM access
TST IRQ-COUNT *rtsetting
LBEQ READ-KEXS *Btaacb after 22 ints, to keyboard reading mutine.
LDAB #$OF +restoring of k registeroccurs afker br to READ-KEYS
TBEK
RTI
Appeodlx C: ControUer Source Code

READ-KEYS :
LDAB #$OF
TBEK
LDD na0000 *Disable OC4 intempt in the QSM, and Ieave timer
*prescaler at 64.
STD TMSKl *New, the intempt fiom the GPTis completely
*disabled-
LDD mOOOO *Set GPT uitemipt prbrity to OC4 (number 7).
STD ICR *intemiplevel to iRQ 6, vector base address to 6
LDAA MF0 *Set aii column lines low
STAA PORTFO
LDAB PORTFO *LoadPORTF
CBA *See if any keys are pressed-any bigh nibble bit is set
LBEQ NO-KEY-PRESSE.*leave if no indication of keypcess afta delay
LDAB S O L
TBEK
LDE #$FFFF
STE IRQIDûNE *set flag so program r e m to mutine pmperIy
STE KEYPRESSED *set KEYPRESSED Bag so other functions can use it
LDAB #$OF
TBEK
TPD Urransfer C a to Acc. D
LDD #$OOEO *Set up D for clearing CCR and setting IRQ mask to 7
TDP *Trader D to CCR DDR now wiU refuse int 6 & l e s
LDAA #$El
READ-COLUMN:
STAA PORTFO *Write to column 1
LDAB PORTFO
CBA *Sec if this column was pressed
BNE KEY-ID 1 *If this column was pressed, see which row it is
TDE
TPD
ORD
TDP
TED
RORA *ShB nght to check next colwnn (enters 1 on MS bit)
LBCC NO-KEY-PRESSED *Wkn carry is clear, leave mutine
LBRA READ-COLUMN *If it wasn't this column, go and check the next one
KEY-ID 1:
LDAA #$O 1
XGAB * TBEK onlv works with Acc B-so rcbange - BA
TBEK * point EK t6 badt O for RAMxccs
CLRW KEY * start key hex identity cegister at O
LDE #$O011
STE KEY-ERR-COUNTER * load $10 to count down each time a different
* key identity is tested-just in case the key
* byte in acc B doesa't match any in the
* table KEY-TABLE-this prevents an endless loop
KEY-ID2:
DECW KEY-ERR-COUNTER
LBEQ NO-KEYJRESSED
LDAB KEY+l
CLRW INDEX
STAB INDEX+l
LDE #KEY-TABLE
ADDE INDEX
STE INDEX
LDX iNDEX
Appendix C: ControUer Source Code

LDAB X
CBA
LBEQ KEYIS-iDED *if quai, btmch to HEXCOW and compare
NCW KEY *check to see ifit's the next nwnber higher
BNE KEY-ID2
KEYIS-IDED:
mAB HOF
TBEK
m
HEXCONV:
LDAB #$O1 %cc B is the number presseci-KEYis hex
TBEK
LDE #$O0
STE HlXEY-Hïi'
LDAB KEY+l
SUBB HOA *subuact A; if acc B is 9 or less, will be neg
LBGE HEICNUMHEICNUMCONV
*branch to HEXMTMHEXMTMC0NV below if A to F
LDAB KEY+l *at tbis point* so reload number and
ADDB #$30 * then add 4630 to make an ASCII
STAB KEYASCII code. Save to KEY for later use.
LDAB #%OF *reset to bank F so MPU wiU cal1 peripherals
TBEK *point EK to bank F for register access
RTS
HEXMiMHEXMiMCOMr: *convert numbers A to F to ASCII and implirnent
LDAB KEY+I * I d the number pressed to B
ADDB -0 *maice it an ASCII letter value
STAB KEYASCII *store it to KEY for later use
LDAA #$OA %ad acc A COsee if B is SOA
CBA *compare acc 0 to acc A (B-A=x)
LDE #$O001
STE HEXKEY-KiT
RTS

*CHECK-FUNCIIONis a subroutine cailed in RETURNRETURNDEBOUNCE


* CHECK-FUNCïiON checks the keys presseci to see if tfiey are for conirolier*
* settings. This calls the following functions:
* -RAISED-EWS-SET set the position of the discs when raised and detemine*
* whether 1 or 2 sensor mode is used. Also for dtermining whether metric
* or imperial units are used
* -MOVETûTOüPraise the disks
** -SET-OPER-DEPTH set seedingdepth
-FELD,O-POS-SET set field surface position
* -CALIBRATE is key to accurate operation. Sets the sensor positions
* 90 degrees to the connechg arm so a correction factor can be used
* as the am moves f b m the horizontal.
* -MOVETOVETODOWN nsume normal operation of the controller, from the
* raised position.
*
Appendix C: Controller Source Code

INCA *acc A is now $OB


CBA
LBEQ MOVETOVETOUP *raise the seeder to the up position-tUrrist etc
INCA *acc A is now $ûC
CBA
LBEQ SET,OPER-DEPïH *set the depth of seeding
INCA *WC A is now SOD
CBA
U E Q FiELDE;IELDOOPOS,SET
%et the zero" &ph position in the field
INCA *acc A is now SOE
CBA
LBEQ CALIB- *set the 6" depth position and zero posiaon
* on a level suffixe
INCA *acc A is now $OF
CBA
LBEQ MOVETOVETODOWN *put the seeder to the operating position
RAISEDJOS-SET: *Choose, and set, sensor modes and position of raised seeder
JSR ClEAR-DISPLAY
LDX #CHOOSESFüNCTiON,MSG *choose between modes or raised pas
JSR SEND-STRING *pint it to the lcd m e n
JSR TWOSEC-DELAY
LDX #PICK-MODE-OR-RAISE1
JSR Sm-STRING * p d t it to the lcd screen
JSR 'IWOSEC-DELAY
LDX #PIC K-MODE-OR-MSE2
JSR SEND-STRING * p ~ittto the lcd scceen
JSR 'IWOSEC-DELAY
LDX #PICK-MODE-OR-WSW
JSR SEND-STRiNG *print it to the lcd screen
JSR TWOSEC-DELAY
LDX #PICK-MODE-OR-RAISE4
JSR SEND-STRING *pint it to the lcd screen
JSR TWOSEC-DUY
LDX #PICK-MODE-OR-RAISES
JSR SEND-STRING *pint it to the lcd screen
JSR TWOSEC-D-Y
JSR WmR-KEYPRESS
JSR HEXCOW
LDAB #sol
TBEK
LDAB KEY+l *Ioad key number
SUBB 6 0 3 *subtract 3; if acc B is 2 or less, wiil be neg
LBGE =OR-PRESS *and be an emr
TSTW KEY
LBNE CHECKFERRl,OR-2
LDX #CHOOSE-MODE-MSG *point to the mode message
JSR Sm-STRING *print it to the lcd screen
JSR TWOSEC-DELAY
JSR CLEAR-DISPLAY
LDX #HIT'KEY-MSG
JSR Sm-STRING
JSR W-KEYPRESS
JSR CLEAR-DISPLAY
LDX #MODE-A
JSR SEND-STRING
JSR TWOSEC-DELAY
LDX #MODE-B
JSR SEND-STRING
JSR TWOSEC-DELAY
Appendix C: ConmUer Source Code

LDX #MODES
JSR SEM)-STRING
JSR TWOSEC-DELAY
JSR WNTFERKEY'PRESS
JSR HEXCOW
LDAB H O 1
TBEK
LDAB KEY+l *load key number
SUBB HO2 *subtract A; if acc B is I or less, will be neg
LBGE ERROR-PRESS *emr $2-F
CLRW ADC-CHANNEt Wear location of raiseci vaiue
LDAB EY+l *Io& key number
STAB ADC-CHANNEL
LDAB #WF
TBEK
RTS
CHECKFERKFERl,0R,2:
LDAB KEY+l
DECB
LBNE SET-UMTS
SET-RAISED-ms:
LDX #SEI-RAISE-MSG *point to Icd message for setting raised pos
-

JSR SENDISTRING *~rintit to the lcd screen


JSR TWOSEC-DWY
JSR CLEAR-DISPLAY
LDX RHlT-KEYMSG
$SR SEM)-STRING
JSR WAïïFER-KEYPRESS
JSR CLEAR-DISPLAY
LDX #ENTER-HEIGElT'
JSR SEND-STRING
JSR TWOSEC-DELAY
JSR W m - K E Y P R E S S
fSR HEXCONV
LDAB #$O1
TBEIC
LDAB KEY+l *load key number
SUBB #$OA *subtract A; if acc B is 9 or less, wiH be neg
LBGE ERROR-PRESS *enor if A-F
CLRW RNSED *clear location of raised vaiue
LDAB KEY+1 *load key number
ASLB
ASLB
ASLB
ASLB *put inch or cm in MSB position of 8 bit number
STAB RAISED+l
JSR CLEAR-DISPUY
LDX #EIWER-LOTHOTHHEIGHT
JSR SEM)-STRING
JSR TWOSEC-DUY
JSR W2UTFERKF;VDqCCS
JSR HEXCONV
LDAB #ml
TBEK
LDAB KEY+l *load key number
SüBB HOA *subtract A; ifacc B is 9 or les, will be neg
LBGE ERROR-PRESS *errer if A-F
LDAB KEY+1 *load key number
ADDB RAISED+l *add in or cm to tenths or mm
STAB RAISED+l *store as raised number
Appendix C: ConmUer Source Code

*LDAA UNITS *see ï€iaches or cm


Ylism
*LBEQ RAISED-METRIC
JSR UEAR-DISPLAY
LDX LN-CONVFACIOR2 *divide incbes & tenths by totai possible (60)
LDAB RAISEIN1 %ad actuai in and tcnths
FDIV *answer in M-MSB is sign bit
XGDX *tramfer IX to Dacc A is 2nd $3rd MSB's
LDAB M7F *correct for 6" depth by subtracting h m totai
SüBB CALiB-DEPTH *subtract the amt- for 6" depth
MUL
ADDA M7F *correct for king above -und
STGA RAISED+l *store remainder (in D-acc A is MSB of cernainder)
*LDE RAISED * C M TT-JUST USE DIRECT VAtUES FROM SAMPLE
*JSR ANGLE-CORRECïTON *convert to 1000's of an inch and adjust for angb
LDAB #$OF
TBEK
RTS
ms:
iR CLEAR-DISPLAY
DX #PICK-UNIT-MESSAGE 1 *point to the appropriate ASCII string
IR SEND-STRING *print string to lcd
IR TWOSEC-DELAY
IR CLEAR-DISPLAY
DX #PICK-üNïî-MESSAGE2 *point to the appmpnate ASCII string
IR SEND-STRING *print string to I d
IR TWOSEC-DELAY
IR WAITFF-RKEYPRESS
IR HEXCONV
3AB 4601
BEK
3AB W+1 *Ioad key number
JBB MO2
3GE ERROR-PRESS *errer ifabove 1
,TW KEY
YE SET-METRIC
DE #$FFFF
rE UMTS
rs
SET-METRIC:
CLRE
S E m s
RTS
MOVETOOUP:
JSR CLEAR-DISPLAY
LDX #RAISE,MESSAGEl *point to the appropriate ASCII string
JSR SEND-STRING *print string to Icd
JSR TWOSEC-DELAY
LDX #RAISE-MESSAGE2
JSR SEND-STRING *print string to lui
LDAB MO1
TBEK
LDAA RAISED+l * I d variable for rate of speed of üft
LDAB #!§OF
TBEK
S U PWMA %endthe value to the tiydrauiics
LDAB #$O1
TBEK
AppendIx C: Conuoller Source Code

D-wm
IR SAMPLE *sec what the height of the discs are
t**SUBTRACTACIUAL HEiGEîT FROM THE SET HEIGmAS LONG AS ITIS BELOW
*=T
[EE SET HEIGHT 1T WIU KEEP RAISING TEE IMPLIMENT
3AB #O1
BEK
3 A B RAISED+l *LOAD HEIGHT YOU WANT TO M S E TO
JBB DISC-READING+l *SUBTRACCTHE ACTUAL EIEIGHT
PL RAISED-Wm *BRANCESIF OVERnOW CLEAR-IE., STILL BIG NUMBER
*MIlWS SMALLER NLTMBER-V BiT SET WHEN HIGEER
*THAN THE RAISED SET POINT
M A #$7F *discs are up to the required height-stopdisc moment
>AB #OF
3EK
CAA PWMA *by Ioading neutral movement (7F) and store to PWMA
iR Wm-KEYPRESS
HEXCO~
3 A B 601
3EK
>AB -1
JBB #$OF
UE RAISED-wm
>AB #$OF
3EK
rs
SET,OPER,DEITH:
JSR CLEAR-DISPLAY
LDX #SR-OPER-MSG v i n t to Icd message for setting raised pos
JSR SEND-STRING *print it to the lcd çcreen
JSR TWOSEC-DELAY
JSR CLEGR-DISPLAY
LDX #HIT-KEY-MSG
JSR SEND-STmG
JSR WAITFER-KEYPRESS
JSR CLEAR-DISPCAY
LDX #ENTER-DEPTH
JSR SEND-STRING *pnnt it to the lcd screen
ISR TIKOSEC-DELAY
JSR W-R-KEYPRESS *first-inchesentry
JSR HEXCONV
LDAB #%O1
TBEK
LDAB KEY+1 *load key number
SUBB nâOA *subtract A; if acc B is 9 or Iess, will be neg
LBGE ERROR-PRESS *emr if A-F
LDAB 4601
TBEK
CLRW M I S E D L *clear location of r a i d value
LDAB KEY+l *load key nurnber
LDAA #$OA
MUL *inches times decimal 10
CLRW OPJZWUIIUGGDEPTEI
STAB OPEWWINGDEPTH+l
LDX #ENTER-IOTH-Dm
JSR SEND-STRiNG +print it to the lcd sacen
JSR TWOSEC-DELAY
JSR WAITFERKEY'PRFCS *second- tenth inch or mm entry
JSR HEXCONV
LDAB #Wl
Appendix C: Conmller Source Code

TBEK
LDAB ICEY+l *load key nurnber
SUBB #0A subaact A; if acc B is 9 or les, wül be neg
LBGE ERROR-PRESS *enor $A-F
LDAB KEY+1 *load icey numûer
ADDB OPERATINGDEPTH+I *add in or cm to tenths or mm
STAB O P ~ G G D E V I n +*store l as raiscd nurnber
LDE OPEMMNGGDWTH
LDD #$O64
EMUt
STD O P E R A T N G - D m *store as 1000's of an inch
LDAA UMTS *see if inches or cm
TSrn
BPL O P E R A T I N G - m C
JSR CLEAEt-DISPLAY
* LDX iN-CONVJACIOR2 *divide inches & tenths by total possible (60)
* LDAB RAISED2 *load actual in and tentbs
* IDN *remahder(in D-acc A is MSB of remainder)
* STAA OPERATING-DEPTH *store remainder (in D-acc A is MSB of remainder)
LDAB #$OF
TBEK
RTS
OPEMTINGGMETRIC:
NOP
NOP
NOP
NOP
Krs
FIELD-O-EWS-SET: *set the zero depth position in the field
JSR CLEAR-DISPLAY
LDX #FIELDO-SET-MSG *point to the appropriate ASCII smng
JSR SEND-STRING *print string to lcd
JSR TWOSEC-DELAY
JSR CLEAR-DISPLAY
LDX #HIT-KEY-MSG
JSR Sm-STRING
JSR WAITFERKEYPRESS
JSR ClEAR-DISPLAY
LDX #LOWER,GRND-LEVEL
JSR SEM)-STRING *print it to the lcd screen
JSR TWOSEC-DUY
JSR CLEAR-DISPLAY
LDX #HIT-'0-STORE
JSR SEM)-STRING
JSR W-R-KEYPRESS
JSR SAMPLE *sarnple the sensors again
LDAB #$O1 *set page-SAMPE leaves it as $OF
TBEK
LDE DISC-READING
JSR ANGLELECORRECïiON*correct for angle of sensor to linkage
*input to aigorithm is in acc E, with answer put in E
STE CORRECTEDCIW)FlELD,2ER0
LDE FRONT-READING
JSR ANGLE-CORRECTION *correct for angle of sensor to linkage
*input to aigorithm is in acc E, with answer put in E
STE FRONT-GROUND,ZERO
LDAB #!Hl1
TBEK
RTS
Appendix C: Controlier Source Code

CALIBRATE: *first, choosc mode-either (0) calibrate the sensorby setting


*to 9û &gree angle fhm the connccting rod, or (1) set the
+position for the level position on a hard. level srufare
*and then tbe position 6" above that(disc seasor)-(2) is
*for caübrating the fiont sensor, 6" above a levd surface
*first, choose the mode:
JSR CUALDISPLAY
LDX #CHOOSEOOFUNcTIONNMSG
%hoosebetween 90 deg caiib or 6" deep caiib
JSR SEND-STRING *pnnt it to the lcd sctcen
JSR TWOSEC-DELA'Y
LDX WICKdCALIB-9(ALIBORR~I
JSR Sm-STRING Vnnt it to the lcd screen
JSR TWOSEC-DUY
LDX #PICK-CALIB-90-0RR61N2
JSR SEND-STRING *print it to the lcd screen
JSR TWOSEC-DELAY
LDX #PICK,CALIB,90,0R,6IN3
JSR SEND-STRING *print it to the lcd screen
JSR TWOSEC-DELAY
LDX #PICK,CALIB-9O-OR0~4
JSR SEND-STRING *print it to the lcd screen
JSR IWOSEC-DELAY
LDX #PICKdCAtIB,90_0RAtIB~5
JSR SEND-STRING *pnnt it to the lcd screen
JSR TWOSEC-DELAY
JSR WGITFER-KEYPRESS
JSR HEXCONV
LDAB #.$O1
ïBEK
LDAB KEY+l *load key number
SUBB S03 * s u b a t 3; if acc B is 2 or les, will be neg
LBGE ERROR-PRESS *and be an emr
TSTW KEY
LBNE CHECKFERKFERI,0RKFER22FOROCALIB
*set the 90 deg position:
JSR CLEAR-~DISPLGY
LDX UCAWB-90,DEG 1 *point to the appropriate ASCII string
JSR SEND-STRING *@nt string to Icd
JSR TWOSEC-DELAY
JSR CLEAR-DISPLAY
LDX #CAJ5,90,DEG2 *point to the appropriate ASCII string
JSR SEND-STRING *print stting to Icd
JSR TWOSEC-DELAY
JSR CLEAR-DISPLAY
LDX #CALIB,90,DEG3 point to the appropriate ASCII string
JSR SEND-STRING *pint string to Icd
JSR TWOSEC-DELAY
JSR CLEARLEARDISPUY
LDX KALIB-9û-DEG4 *point to the appropriate ASCII string
JSR SEND-STRING *print string to Icd
JSR TWOsEcTWOSEC,DELAYDELAY
JSR CLEAR-DISPLAY
LDX #Hm-KEY-MSG
JSR SEND-STRiNG
JSR
JSR CLEAR-DISPLAY
LDX #SETETTOT09û90MSG
1
ISR SEND-STRING *print it to the lcd screen

-C-1s -
Appadix C: Controllet Source Code

JSR TWOSEC-DELA..
JSR CLEAR-DISPUY
LDX #SETETTOT09û-MSG2
JSR SEND-STRING *@nt it to the lcd screen
JSR TWOSEC-DELAY
JSR CLEARCLEARDISPtGY
LDX #SETETTOT090,MSG3
ISR SEND-STRING *@nt it to the lcd screen
JSR TWOSEC-DELAY
JSR CLEAR-DISPLAY
LDX 4tHI.T'-TOTOSTORE
JSR SEND-STRING
JSR WAITFER,KEYPRESS
JSR SAMPLE
LDAB Mi01
TBEK
LDE DISC-READING
STE DISC-MNETY-DEG-POS
LDE FRONT-READING
STE FRONT-90-READING
RTS
CHECKFER,l~OR,2~FORCHECKFER,i,oR,2,FoR,CAtrie:CALtB:
ïDAB KEY+1
DECB
LBNE CALIB-FRONT-SENSOR
CU-BACK-SENSOR:
fSR CLEAR-DISPUY
LDX #LEYEïO-SET,MSG *point to the appmpriate ASCII string
JSR Sm-STRING *print string to lcd
ISR TWOSEC-DELAY
SSR CLEARLEARDISPLAY
LDX #LEVELtFvEf.SURFURFCALIB
JSR SEND-STRING
JSR TWOSEC-DELAY
JSR CLEARLEARDISPLAY
LDX #KiT-KEY-MSG
JSR S m - S m G
$SR WAITFER-KEYPRESS
JSR CLEAR-DISPUY
LDX #DISC-tr;Vm,tr;vm,ZERO,MSG
JSR SEPIJD-STRING *print it to the lcd screen
ISR TWOSEC-DELAY
JSR CLEAR-DISPLAY
LDX #HIT-TO-STORE
JSR SEPID-STRING
JSR TWOSEC-DELAY
JSR W-KEYPRESS
$SR SAMPLE
LDAB #$O1
TBEK
LDE DISC-READING *use disk readinn onlv for this

****now, calibra6 disc sensoc for 6" deep+***


JSR CLEAR-DISPLAY
LDX #SfXJN-CALIBO
JSR Sm-STRING
JSR TWOSEC-DELAY
ISR CLEAR-DISPLAY
LDX #SIX-IN-CALIB 1
Appendix C: Controllec Source Code

JSR SEND-STRING
JSR TWOSEC-DELAY
JSR UEAR-DISPUY
LDX #HIT"KEYMSG
JSR SEND-STRING
JSR TIKOSEC-DELAY
JSR W m - m
JSR UEAR-DISPLAY
LDX #HIT-TOTOSTORE
JSR SEND-STRING
JSR W O S E C - D U Y
JSR WAITFER-KEYPRESS
JSR SAMPLE
CLRD
LDAB #$O1
TBEK
LDE DISC-READING
SUBE DISC~MNETY-DEG-POS
BPL LOAD-DISC-SINE
NEGE
LOAD,DISC,Sm
XGEX
LDY #SINE-T'LE *now we have the sine of the sensor angle at 6"
XGEY
CLRA
CLRW C A L I B - D m
LDAB E X *sine of sensor position at 6"
STAB CALIB-DEPTH+L EX^^'-CHANGE THIS VARIABLE NAME
LDE DISC-LEVEL-ZERO
SüBE DISC-NINETY-DEG-POS *now, get the sine of the angle between ground and 90 deg pos
TSTE
BMI NEGATIVEATIVECALIB
XGEX
LDY #SINEINETABLE *now we bave the sine of the sewor angle at 6
XGEY
CLRA
LDAB E X *sine of sensor position at 6'
CLRW TRUE-O-DEPTH
STAB T R U E - O - D m
LDD C A L I B - D m
SUBD TRUEUEOODEPTH *subuact the sine of the difference between
*DISCJEVELLnrELZERO and DISCONINETYNiNETYDEG,POS from the difference
*between the 6" point and DISC-NINETY-DEG-PûS
FINISH-CALIB :
XGDX
CLRE
LDD #SI770 *asis 6000 thousandths of an inch in hex
EDIV *divide the sine into the length of the opposite
*side-this gives the hypoteaeuse in thousandths of an inch
XGDX fmultiply by 256-you had DIVIDED by a whole number
ASLD *(muitipiied by sine 256)
ASLD *(ah-179 for vertical bar!)
ASLD * \
ASLD * 6'depth is \ hypotencuse
ASLD * equal to the \
ASLD * opposite side-> \
ASLD * ( \ <-sine of this angle
XGDE
STE HYPOTENmJSE-DISC *sine of angie * opposite = HYPOTENEUSE,DISC
LDAB #$OF *INTHOUSANDSTHOF AN INCH
TBEK
Appendix C: Controller Source Code

NEGATïVE-CALIB :
NEGE
XGEX
*now we have the sine of the sensor angle at 6"
LDY #SINEINETABLE
XGEY
CLRA
LDAB EX *sine of sensor position at 6"
ADDD CALIB-DEPTH *subtract the sine of the merence betwecn
DISCJEVEL-ZERO and DISCLFvET_NiNETY'DEGJûS h m the difference
*between the 6" point and DISC-NlNETY-DEG-POS
BRA FINISH-WIB
CALIB-FRONT-SENSOR.
JSR CLEAR-DISPLAY
LDX nLEVEtF-SET,MSG *point to the appropripriate
ASCIf smog
JSR SEM)-STIUNG *print string to lcd
JSR TWOSEC-DELAY
JSR CtEAR-DISPLAY
LDX RLEVEL-SURFURFCALfB
JSR SEND-STRING
JSR IWOSEC-DELAY
JSR CLEARCLcEARDISPLAY
LDX #HIT-KEY-MSG
JSR SEM)-STRING
JSR W m - K E Y P R E S S
JSR CLEAR-DISPLAY
LDX #DISCLEvmZERO-MSG
JSR SEND-STRING ?rint it to the Icd screen
JSR TWOSEC-DELAY
JSR CLEAR-DISPLAY
LDX RIiIcr-TO-STORE
JSR SEM)-STRING
JSR TWOSEC-DELAY
JSR W m - K E Y P R E S S
JSR SAMPLE
LDAB #$O1
TBEK
LDE FRONT-READING *use disk reading oaly for this
STE FRONT-LEW3.-ZERO
****now, calibrate for 6"deep8***
JSR CLEAR-DISPLAY
LDX #SIX-IN-CALIBO
JSR SEMI-STRING
JSR TWOSEC-DELAY
ISR CLEAR-DISPLAY
LDX #SiXTXiNINCALIB 1
ISR SEND-STRING
JSR TWOSEC-DELAY
JSR CLEAR-DSPLAY
LDX Rrn-KEYMSG
JSR SENDSEND,STRINGSTRING
JSR TWOSEC-DEtAY
JSR w--KEYPRESS
JSR CLEAFt-DISPLAY
LDX #m-TOdsTORE
JSR SEMI-STRING
JSR TWOSEC,DJ?LAY
JSR w--KEYPRESS
$SR SAMPLE
Appendix C: Controller Source Code

CLRD
LDAB 6 û L
TBEK
LDE FRONT,-READING
SUBE FRONT'-READING
BPL LOAD-FRONT-SINE
NEGE
LOADLOAD,FRONT,SINE:FRONTM:sINE:
XGEX
LDY #SINECTABLE *now we have the sine o f the sensor angle at 6"
XGN
CLRA
CLRW CALIS-DEPTH
LDAB EX *sine of sensor position at 6"
STAB CALIB-DEPTH+l
LDE FRONT---ZERO
SUBE FRONT-9û-READING *now, get the sine of the angle between ground and 90 deg pos
TSTE
LBMI NEGAïnE-CALJB
XGEX
LDY #SINEINETABLE*now we have the sine o f the sensor angle at 6"
XGEY
CLRA
LDAB E s *sine of sensor position at 6"
CLRW TRWEUEOODEPTH
STAB TRUEUEOODEP'ï'H
LDD Cm-DEPCH
SUBD TRUEEOODEPXX*subtract the sine of the difference between
*FRONT,LEVEL-ZERO and FRONT-MNETY-DEG-POS fiom the difference
*between the 6" point and FRONT-NINETY-DEG-WS
FINISH-CALIBB:
XGDX
CLRE
LDD #SI770 *this is 6000 thousandths of an inch in hex
EDIV *divide the sine into the Iength of the opposite
*side-this @es the HYPOTENEUSE in thousandths of an inch
XGDX *multiply by 256-you had DMDED by a whole number
ASLD *(multiplied by sine * 256)
ASLD *(ait- 179 for vertical bar!)
ASLD * \ *
ASLD 6" depth is \ hypoteneuse
ASLD *equal to the \
ASLD opposite side-> \
ASLD ( \ <-sine of thïs aogle
XGDE
STE HYPOTENEUSEJRONT *sine of angle opposite = hypoteneuse
LDAB n%oF *IN THOUSANDSTH OF AN INCH
TBEK
ms
NEGAïMZJXLIBB:
NEGE
XGEX
LDY #SINEINETABLE*now we have the sine of the sensor angle at 6"
XGEY
CLRA
LDAB EX *sine of sensor position at 6"
ADDD CALIB-DEPTH * s u b a t the sine of the ciifference between
*DISC---ZERO and DISC-NINETY-DEG-PûS h m the Merence
*between the 6" point and DISC~NINETY-DEGJOS
BRA FtMSH-CALIBB
Appendix C: ControllerSource Code

MOVETOODOWN--
JSR CLEAR-DISPLAY
LDX nL0WER-MESSAGE *point to the appropriate ASCII string
JSR SEND-STRING *pcint string to lui
JSR TWOSEC-DELAY
LDAB S O I
TBEK
LDE UOPERATING-DEPTH
sTË OUTPUT *&nd the value to the hydraulic conîrol mutine
LDE UHM)RAULULTIMERl*loiid the nmber to count down
STE c0UNTDOWN1
LDE HYDRALJL-TIMERL *load the number of times the number will be
STE COONTDOWN2 * counted dowu
JSR HYD-CONT *niove the hydraulics
LDAB #$OF
TBEK
RTS
********************************************************************
* *
* KEYPRESS AND DELAY UTIUTY ROUTINES: W m - K E Y P R E S S loop for waiting for
* a key to be pressed for calibrationand setting routines *
* ERROR-PRESS kicks in when the m n g key is pressecl *
* HAtFSEC-COWNT a timing loop for putting messages on the LCD screen *
* ONESEC-DELAY and TWOSEC-DELAY cails HALFSEC-COUNT several rimes. *
* NOKEYPRESSED clears key jpressed flag if noue pressed.
* *
*
*********************************************************************
WAITFERAITFERKEYPRESS:
LDAB #$O1
TBEK
LDE #$O001
STE KEYCHECK *set Bag-no key id, only check for press
LDAB #$OF
TBEK
JSR CHECK-KEYS
LDAB #$O1
TBEK
T S W KEYPRESSED *see if a key had been pressed
LBEQ W-R-EYETtESS
LDE # S m
STE KEYPRESSED
LDE #$O000
STE KEYCHECK
RTS
ERROR-PRESS:
JSR CLJ5A.R-DISPLAY
LDX IERR-PRESS-MSGO
JSR SEND-STRING *print string to lcd
JSR TWOSEC-DELAY
JSR CLEGR,DISPLAY
LDX #ERR-PRESS-MSGL *enor if A-F
JSR SEN'-STRING*print stnng to lcd
JSR TWOSEC-DELAY
LDAB #$O1
TBEK
RTS
Appcadix C: Coatroller Source Code

LDAB MOI
TBEK
MOVW HALFSEC-INlT.COUNTDOWN2
HALFSEC,LOOP
LDAB m1
TBEK
DECW COUNTDOWN2 *decrement the main countdown
LDAB #$OF
TBEK
LDAB a 0 1
TBEK
TSTW COUNTDOWN2 *when done dcount, test "largev*main count
BNE HALFSEC-LûûP *bop back until done
LDAB #$OF
TBEK
RTS *say, "Bye Bye" "(mailwave)
ONESEC-DELAY:
JSR HALFSEC-COUNT
JSR HALFSEC-COUNT
RTS
TWOSEC-DELAY:
JSR HALFSEC-COUNT
JSR HALFSEC-COUNT
*JSR HAtFSEC,COWNî *cou( out these since it TAKES SO LONG!!!
*BR HALFSEC-COUNT
RTS
NOKEYPRESSED:
LDD #!$O000
TBEK
STD KEYPRESSED *clex kerpressed flag, since noue hit
LDAB #$OF
TBEK
RTS *return-this should be oniy RTS besides one in CHECK-KEYS

* SAMPLE DEPTH SENSORS -Sampling subroutines for the A D *


* Raw data goes into DISC-READING (for the discs) and the fiont *
* sensor into FRONT-READING. These are then translated into
* 1000's of an inch, and correcteci for the angle from 90 degrees.*
* This is stored as SEED-DEPTH-ERROR, which is the error in (tnie)
* 1000's of an inch h m ground levcl. SIGN-FLAG is set whcn the
* error is above ground level, deared if below. *
***************88+********8**t******&**&*****8*****#******8****

SAMPLE:
LDAB
TBEK
LDE Mo0
STE ADCMCR *for stop/fieeze/supe~sormodes-set to normal
LDE Mo003
STE ADCTU) *8-bit, 8 ADC clock cycles
LDE #Sm0*&bit rcsolution (mode 2) (mode2:4 inputs-0020)
*this does conversions on 4 inputs, starting wiih
*the one specified in bits CA-CD. So, ADû in RlURRO,
*and AD1 supposai to be in FüüRRl.
STE ADCTL 1 *Set port F data registers. niis starts conversion.
NOP *süght dclay to allow conversion to complete
Appendix C: Connoller Source Code

*speed of the AIX:is 118 of cbip clock speed (set in


*the STS bits of ADCIZO)-It takes L6 ADC cycles to
*complete an &bit conversion, or 16*8=128 16.7 MHZ clocks
IDE W$OOOA
ADC-DELAY-LOOP: *for about 150 c1wk cycles, to alIow for the ADC to finish
SUBE #SlW1
BNE ADC-DELAY-LOOP
LDE RJURRO *ri@ justifid result register O-mult in 8 LSB's
LDAB #$O1
TBEK
STE DISC-READING
TSTW ADC-CHANNEL
BNE ONENE-
LDAB #$OF
TBEK
LDE RTURRl *ri@ justifieci result register 1-result in 8 LSB's
LDAB #$O1 *REGISTERFOR ADC INPUT#l
T8EK
STE FRONT-READING *store &nt sensor reading, no angle correction
JSR ANGLE-CORRECTION-FRONT *correct for angle of sensor to 90 degrees
*input to algorithm is in acc E,with answer put in E
S E coRRECIEDJRomJ3EADING
*LDE COREECTEDJEtONcr'ZERO
*SU% CORRECTED-FROM:M:READING
***ASRE *SHIFT RIGHT TO INC. ACCURACY
*STE CORRECIEDJRONTJEADING *angle of sensor now compensated for
LDE DISC-READING
JSR ANGLE,CORRECIION *correct for angle of sensor to 90 degrees
*input to algorithm is in acc E, with answer put in E
STEi CORRECTID-DISC-READING *angle now compensated for
SUBE COREtECTJ33-FRONT-READING
ONE-CHANNEZ:
STE CORRECCEDCCEDDEPTH-READING
*store the raw depth data
LDE CORRECTED-FIELD-ZERO *load the zero point data (seed depth setting)
SUBE CORRECTED-DEPTH-READING *field,zem - depth-~ading= depth in hex
*SUBE C O R R E ~ - F I E t D - Z E R O
S E SEEDDEPTH-=OR *store dif5erence (depth)
*in thousanths/inch, (in hex) so cm be converted dkctly
TSTE
LBMI ABOVE-GROUND *if above zero point, jump to abovesound
CLRD
STD SIGN-FLAG *if seed depth is above the ground, clear sign-flag
LDAB #$OF
TBEK
RTS *go back to MAIN prograai loop

ANGLE-CORRECTION: *tbe origional ADC readings remain in DISC-READING and


*FRONT-READING, nie cortected readings are for displaying
*on the LCD and for the fimy routine, to ensurc corrections
*arc made basal on the depth, not just the seasor position
*(as are the routines for calibration).
CLRW SIGN-FLAG
SüBE DISC~NINETYDEG-mS *subtract zero position from reading
TSTE *see if answet was negaavt
BPL POS-ANGLE *hanch here if answer is positive
NEGE *2's complement E
RESUMEUMEANGLELECORRECTION:
XGEX
LDY USINE-T-LE now we have the sine of the sensor angle at 6"
Appendix C: ControIier Source Code

XGEY
CLRA
LDA0 EX
LDE HYPOTENEUSEJXSC *multiply by the hypoteneuse
EMUL
TEDM
ASRM *divide by 256, since sine is a 6action
ASRM
ASRM
ASRM
ASRM
ASRM
ASRM
ASLM *now, shift AM left 16 places for transfemng to E
ASLM *The TME.=Tand TMER commands only uansfet the
ASLM *upper 16 bits of AM to E,so tfre answer has to be
ASLM *thece.
ASLM
ASLM
AStM
ASLM
ASLM
AStM
ASLM
ASLM
ASLM
ASLM
ASLM
ASLM
T'MET
TSW
BEQ
CLRW
RTS
BELOW-GRNDRM)ADJUST:
NEGE - -
*2's comp E (0000 E,not FFFF E as in COME)
îLRW SIGN-FLAG
RTS *later.
POS-ANGLE:
LDD #!§FFFF
STD SIGN-FLAG
BRA RESUME-ANGLELECORRECTION
ANGLE,CORRECïiONOFROm ****SETUP FOR THE FRONT-READING FOR MORE
ACCuRACY***
*the origionai ADC d n g s remain in DISC-READING and
*FRONT-READING. The comted readings are for displayhg
*on the LCD and for the fiiay mutine, to enswc corrections
*are made based on the depth, not just the sensor position
*(as are the routines for calibration).
CLRW SIGN-FLAG
SUBE FRONT-90-READING *subtract zen, position fimm reading
TSTE ce if answer was negative
BPL POS-ANGLE1 *branch bere if answer is positive
NEGE '2's complement E
~UMEUMEANGLE,CO~ONNFRONT:
XGEX
LDY #SINEINETABLE*now we have the sine of the sensor mgïe at 6"
XGEY
CLRA
Appendix C: ControUer Source Code

LDAB EX
LDE KYPOTENEUSETENEUFRONT
%nultiplyby the hypotcneuse
EMUL
TEDM
ASRM *divide by 256,since sine is a fraction
ASRM
ASRM
ASRM
ASRM
ASRM
ASRM
ASLM *now, shift AM lefi 16 places for traosfemng to E
ASLM Q e TMET and TMER commands only transfer the
ASLM *upper 16 bits of A M to E, so the a m e r has to be
ASLM *there.
ASLM
ASLM
ASLM
ASLM
ASLM
ASLM
ASLM
ASLM
ASLM
ASLM
ASLM
ASLM
TMET
TSTW
BEQ
CLRW
RTS
B EL0W-GW-ADJUST 1:
NEGE *2's comp E (0000 - E, not FFFF - E as in COME)
CLRW SIGN-FLAG
RTS *later.
POS-ANGLE 1:
LDD 6FFFF
STD SIGN-FLAG
BRA RESm-GNGLE-CORREmON-FRONT

ABOVE-GROUND:
NEGE
STE SEED-DEITH-ERROR *save this negative number
LDD #$FFFF
STD SIGN-FLAG *set the sign flag to indicate a negative number
RTS ***(ABOVE GROUND)

DISPLAY-DEPTH:
***convert to decimal output***
LDAB 4601
Appendix C: Controllet Source Code

TBEK
LDD SEED-DEPTH-ERROR *l& D with divisor
TSTW UNITS *determine whetber i n c h or centimetres
LBEQ CENTIMETRES
DECIMAL-CONVO: *convert the MSB to decimal
LDX #$000A
IDIV
STD DEPTH-1000TH *reminder fiom moduio division is 1/1ûûû
XGDX
LDX nâmA
IDIV
STD DEPTH-l(NYïH *remahder h m modulo division is 11100
XGDX
LDX #sOOOA
DIV
STD DEPTH-1OTH *temainder h m rnodulo division is 1/10
XGDX
LDX W%mA
IDIV
STD DEPTH-INCHES *says inches, but shouId read "integers"
XGDX
LDX ~OOoA
IDIV
STD * 10's position integer
DEPTHPTHIOiNCHES
ISR DECIMALCIMALCONVl
LBRA WRlTE-DEPTH
DECIMAL-CONV 1: *convert the second digit of the hex frac to decimai
LDE DEPTH lOOOTH
SUBE n%0005-
B PL ADD-TO-DEPTHIOOTH
LDE DEPTH-100TH
SUBE #$O5
BPL ADD-TO-DEPTHlOTH
RTS
ADD,TO_DEPTHlOOTH:
mcw D m - 1 0 0 T H
LDE DEPTH 1-
SUBE 60005-
BPL ADD-TO-DEPTH1ûTH
RTS
ADD-TO-DEPTHlOTH:
INCW D m - L O T H
LDE Dm-IûTH
SUBE WâOOOA
BPL ADD-TO-INCHES
RTS
ADDADD,TO,INCHES:TOOINcHES:
am
STE DEPTH-1OTH
INCW D m - I N C H E S
LDE DEPTH-INCHES
SUBE 6ûûûA
BPL ADD-TO-1OUNITS
RTS
Appendix C: ControllerSource Code

WRITE-Dm: *send dcpth numbets to thc LCD


LDAB #SOI
TBEK
TSTW OP,DISPtAYYON
BNE DISPtAYYISdON
T S W üME3
LBEQ METRIC
LDX W O P ~ G G S C R E E N J N C H E S*point to kd message for settiag raised pos
\KRITE\KRITEOPERATiNGGSCREEN:
JSR SEM) STRING *print it to the lcd screen
LDAB #$or
TBEK
LDE #$FFFF
STE OP-DISPLAY-ON
DISPUYYISSON:
TSTW DEPTH-IOINCHES *see if there is a 10 inches number
LBEQ WNTE-CLEAR *if zero,branch to write inches
LDAB #$OF
TBEK
LDAA #SB7 *Location for the 7th Icd display position
STAA GPTPDR
SSR LCD-INST
LDAB #$O1
TBEK
LDAA DEPTH-IOINCHES+l *write 10 inches to L m
ADDA #$30 *convert to ascii
LDAB ##$OF
TBEK
LDAB GPTPDR
CBA
BEQ WRlTE-ïNCH *donVtwrite to screen unless it's changed
STAA GPTPDR
JSR LCD-DATA *put it on the screen
WFüTE-INCH:
LDAB
TBEK
LDAA #$CO *Locaaon for ihe 8th Icd display position
STAA GPTPDR
JSR LCD-INST
LDAB 6 0 1
TBEK
LDAA
TSTA
LBGT METRIC *if bit is not set, use the metnc units
LDAA DEPTH-INCHES+l *write inches to LCD
GDDA #$30 *convert to ascii
LDAB #$OF
TBEK
LDAB
CBA
BEQ CHECK-PERIOD *don? wrik to screen uniess it's changed
STAA GPTPDR
JSR L C D - D m *put it on the screen
CHECKCHECK,PERIOD:PERIOD:
LDAA #$Cl *Location for the 9th lcd display position
S m GPrPDR
Appendix C: Conttoller Source Code

JSR LCDJNST
LDAA H2E *write a periodto the scrcen
LDAB GPTE'DR
CBA
BEQ CHECK-TENTfL
STAA GPrPDR
JSR LCD-DATA
CHECKCHECK,TENTH:TENTH:
LDAA #$C2 *Location for the 10th lcd display position
STAA GPrPDR
JSR LCDJNST
LDAB #sol
TBEK
LDAA DEPTHEPTHIOïH+l *write 1/10 inches to LCD
ADDA 6 3 0 *convert to ascii
LDAB #$OF
TBEK
LDAB GPTPDR
CBA
BEQ CHECLSIGN
STAA GPTPDR
JSR LCD-DATA
CHECK-SIGN:
LDAB 6 0 1
TBEK
*determine whether the numbers are negative or positive
LDAB SIGN-FL,AG+l *check sign flag for negative
TSTB
BEQ BELOW-GRND fif positive (not afmve ground) branch here
TSlW DEETH-IOINCHES
LBNE S E V E N T H E V E N T H P L U S ~ P O S ~ ~
LDAA #$87 *Location for the 7th Icd display position
LDAB USOF
TBEK
STAA GPTPDR
JSR LCD-INST
LDAA #SB *load a plus sign
LDAB GPTPDR
CBA
BEQ PLUS,IS_THERE
STAA GPTPDR
JSR LCD DATA *put it on the screen
PLUS-IS-THEIRE:
LDAB #SOL
TBEK
TSW DEPTHEPTHIOINCHES
LBEQ SEVENTH-PLUS-PûS-CLR
CLRW SIGN-FLAG
RTS *go back to the M A N submutine

SEVENTHVENTHPLUS,POSpWRITE:
LDAA #$86 *Location for the 7th lai display position
LDAB #$OF
TBEK
STAA GVrPDR
JSR LCDJNST
LDAA # S a *loiad a ~ l u sim
s"
LDAB GPTPDR
CBA
BEQ PLUS-1s-THERE2
STAA GPTPDR
Appendu C: Controller Source Code

JSR LCD-DAX4 *put it on the scnen


PLUSJSJHERE2:
LDAB WSO1
TBEK
CLRW SEN-FLAG
RIS *go back to iùe MAIN submutine
BELOWBELOW,GRNDrGRND:
CLRW SIGN-FLAG
TSTW DEPTH-IOINCHES
iBEQ SEVENTES-PLUS-EQS-CLR
LDAA a 8 7 *Location for the 7th Icd display position
LDAB #OF
TBEK
STAA GPTPDR
JSR LCD-iNST
LDAA S 2 0 *load a space
STAA GPTPDR
JSR L C D - D m *put it on the screen
RTS
SEVENTHVENTHPLUS-PûS-CLR
LDAA #$86 *Location for the 7th I d display position
LDAB #$OF
TBEK
STAA GPTPDR
JSR LCD-iNST
LDAA a 2 0 *load a space
STAA GETPDR
JSR LCD-Dm *put it on the screen
LDAB #$O1
TBEK
CLRW SIGN-FLAC
LDAB #$OF
TBEK
RTS
WRlTE-CLEAR:
LDAB #$OF
TBEK
LDAA #$87 *Location for the 9th Icd display position
STAA GPTPDR
JSR LCD-INST
LDAA 4620 *&te a space to the screen
LDAB G m D R
CBA
LBEQ WRïTE-INCH *if already a space, no need to write one
LDAB #$O1
TBEK
TSTW SIGN-EXAG
LBNE WRITE-INCH
LDAB #$OF
TBEK
STAA GPTPDR
JSR LCD-Dm
LBRA WRITE-INCH *write the inch position
CENTIMETRES: *calculate the depth in centimetres-depthin acc D in inches (in hex)
LDE WSlûû
EimL -
LDX SOû64
Appcndix C: Controllet Source Code

EDIV depth is now in hunddtbsrmch


XGDX *deph in l,OOûbs/cm (nanometers!!) in acc E
LBRA DEQMAt-CONVO *divide by 1,000, conven to decimal, write to screen
METRIC:
WX point to lcd message for setting raised pos
UOPERATINGGSCREENCREENCM
LBRA WRiTE-OPEIWMNG-SCREEN

SEND,STRLNG: *subroutine to send out tbe e n t h ASCIL saùig


LDAB nâOF
TBEK
LDAA M80 *SETDDRAM ADDRESS
STAA GPTfDR
JSR LCD-INST
STRING-PREP:
LDE #$O008
SEM)-NEXT:
LDAB O X *get next byte in string as pointed to by TX
*Io& 7 into E to impliment decrement counter for
*display position on Icd
LBEQ STRING DONE *if B=ûû, thea goto delay between messages
STAB G I T F D ~ *transmit one ASCiI character to the screen
JSR LCD-DAIA
AIX #$O1 *inmement iX to point to the next byte
SUBE #%CW 1
LBEQ NEXT-8-LCD
LBRA SENDEM)NEICT
NEXT-8-LCD:
LDAA #$CO *Location for the 9th lcd display position
STAA G W D R
JSR LCDJNST
LBRA STRING-PREP
STRING-Dom:
LDAA #$O2 *turus on display, cursor on and blinking
STAA GPTPDR
JSR LCDJNST
RTS

* *
*ERROR CONVERSION ROUTWE convert SEEDDEPTH-ERROR (in 1000's of an iach for LCD *
* to a fom compatible with the fuzsr routine (8 bit format). *
* display)
OPERATING-DEPTH (in 1000's inch) is also converteci by the sarne factor.*
* niese are thea added or subtracted to rcfiect the error h m the operating*
* deph
* Convert so $OA = 1 inch in difference. This can *
cbanged (ie, to
* $14 = 1 in) in order to provide scaling down for thebe32 gallon pcr *
* minute hydraulic valve spool. Tbis requitts dividing ihe error in
* 1000's of an inch into e m r in l/lM inch or so- This is thtn added*
* or subtracted fiom the O error value to provide the appropriate FRONT.*
* The answer is put into INPUTS and the RAISE-DEFïH-FLAG is set or cleared*
* to reflect whether the discs have to be taised or lowered (this is for *
* the correction factor for the PWMA signal to reflcct the transfer *
* function of the hydraulic valve.
*
*
******************************************************************************
ERROR-CONVERT: *change e m r in 1000's inch to IO'S ia hex-
LDAB #!§O 1 *add or subtract h m 3F (O e m r position) to
Appendix Cr Controller Source Code

TBEK put in f o m fuztV cnginc understands (range O-7E)


LDD SEEDDEPTW-ERROR
LDX 4664 *LOAD RC Wiï'El dechai 100 (100 SINCE RANGE IS 0-7FNOT FE)
IDN *integer divide the error in 1000's of an inch
XGDX p u t answcr in D
S ï D ERROR-CONV-FOW
LDD OP-G-DEPTH *load operaiing depth in 1000's of an inch
LDX n$64 *LOAD IX WM'H decimal 100 (100 SINCE RANGE IS 0-7F NOT FF)
IDIV *integer divide the error in 1000's of an inch
XGDX %O dividecl by the same factor as SEEDDEPTEI--OR
STD OPERATiNG DEPTEr-CONV-FORMAT *operating ckpth now converted
*****BMI FINIS< *branch if it's negative (iedepth below set point)
*****LDX #$C8 *LOAD IX WlTH deciunai 200 (200 SINCE RANGE IS O-7F NOT FF)
*****LDX fi190 *LOAD IX WITHQcimal4ûû (400SINCE RANGE IS 0-7F NOT FF)
*****LDX #$ IF4 *LOAD LX WITH decimal 500 (500 SINCE RANGE IS 0-7FNOT FF)
TSTW SIGN-FLAG *see if disks are above p u n d or not
BMI SUBTRACT *ifnegative, branch to subtract (discs are above gnid)
****(disks below ground:)****
LDD ERROR-CONV-FOW *sub. c m r (fi ground level) fi operating depth
NEGD faeg since below ground
ADDD OPERATING-DEITH-CONV-FORMAT
BMI FINISH *go here ifdepth below grounâ, and below set point
ADDD #007F *add to O e m r (0 emw3F) to make it bigger than 3F
STAB INPUTS *store for ERROR in hzzy decision
LDE #$FFFF *clex flag since the discs have to be lowered
STE RAISE-Dm-FLAG *clear flag since discs are shallower than
RTS *they should be
FINISH:
ADDD #$07F *adding a negative number makes error less than 3F
STAB INPUTS *store for ERROR in fiizzy decision
CLRE *set flag since the discs have to be raised
STE RAISE-DEPTH-FLAG *set flag since discs are deeper than they should be
RTS
SUBTRACE ****(disks above ground:)****
LDD EFIRORRCOWNVFORMAT *sub. error (fr ground level) fr operating depth
ADDD O P E R A T I N G - D m - C O W - F O W
ADDD 6 0 7 F *to rnake it 10's inch in hex-ans in M:
STAB INPUTS *put error in 10's inch in ERROR for fuzzy decision
LDE #$FFFF
STE RAISE-DEITH-FLAG *clear flagdiscs are above ground and need to
RTS *be lowered

ERROR-BUFFER. ;each input/output will be 10 counts h m each other


LDAB 4601
TBEK
TBZK
LDE #ERROR-TABLE
XGEZ
CLRE
CLRD
;load present emr b a e r index

-C-30-
Appendix C: Conttoller Source Code

LDAB INPUTS ;load prescnt emr (10's inch) h m set point


SlXE EX ;put in circular cmr buffet-10 bytes capacity
*AU #$O 1 ;increment Z to next position
DEC CIRC-ERROR-BUFFER ;dccrement index
BEQ ZERO-?-AND-BUFF ;if 10 locations covcced, start at O again
JSR ERROLCALC
LDAB rYOO
TBZK
RTS ;done-location to I d as chg in cmr is Z + $A
ZER0-Z-AND-Brn
W)AAso9
STAA CIRCJRROR-BUFFER ;reset h&x counter
LDE ERRORRTABLE
XGEZ
JSR ERROR CALC
LDAB n$oo-
TBZK
RTS
ERROR-CALC: ;calculate the cbange in error
LDAB #SOL
TBEK
CLRD
LDAB CIRCCERROR,BUFFER
JSR ZERO-CHECK *see if buffet is 1
m
TDE
LDAA E,Z
LDAB INPUTS ;load current error
SBA ;subtract e m r fkom 10 sampies ago
ADDA a 3 F *SETERROR IN RELATION TO O
STAA ERROR-CHANGE ;store answer as the change in e m r
RTS
ZERO-CHECK:
DECB
BEQ ZERO-FIX
Eus
ZERO-FIX:
ADDB W$û9
RTS

ORG l
lMFPTR
FDB h
FDB n
FDB h
FDB h
FDB h
FDB h
FDB 11
FDB b
FDB h
Appenâii C: Coanoller S o m Code

rnB MF10
FDB MF11
FDB MF12
FDB MF13
FDB MF14
FDB MF15
MF1
FCB $02
FCB $OF
FCB $00
FCB $00
FCB $FF
FCB S2F
FCB 57c
FCB $FF
FCB $50
FCB $00
FCB $00
FCB $FA
FCB $00
FCB $00
FCB $Fi?
MF2
FCB $04
FCB $IF
FCB $00
FCB $00
FCB $00
FCB $2F
FCB $45
FCB $00
FCB $6A
FCB $BI
FCB $Fi?
FCB $81
FCB $00
F a 3 $00
FCB $FA
FCB $00
FCB $00
FCB $FF
MF3
FCB $04
FCB $1F
FCB $00
FCB $00
FCB $00
FCB $41
FCB 542
FCB $00
FCB $7F
FCB $44
FCB $FF
FCB SBB
FCB $00
FCB $00
FCB SFA
FCB $00
FCB $00
FCB $FF
MF4
Appendix C: Controiier Source Code

FCB $04
FCB $IF
FCB $00
FCB $00
FCB $00
FCB S7E

FCB SA1
FCB $55
FCB SFF
FCB $Dl
FCB $00
FCB $00
FCB $FA
FCB $00
FCB $00
FCB EFF
MF5
FCB $08
FCB $17
FCB $00
FCB $00
FCB S00
FCB $AF
FCB $SD
FCB $00
FCB $DB
FCB $00
FCB $FF
FCB $F9
FCB $FF
FCB $FF
FCB $FA
FCB $ 0
FCB $00
FCB $FF
MF6
FCB $02
FCB $OF
FCB $00
FCB $00
FCB $FF
FCB 51A
FCB SB1
FCB SFF
FCB $31
FCB $ûû
FCB 600
FCB $80
FCB $00
FCB $00
FCB fFF
MF7
FCB $04
FCB $IF
FCB $00
FCB $00
FCB $00
FCB SlA
FCB $CC
Appendix C: Contrder Source Code

FCB $00
FCB S2E
FCB Sm
FCB $FF
FCB S3F
FCB $00
F a $00
F a $80
F a $00
FCB $00
FCE $FF
MF8
FCB $04
FCB $ID
FCB $00
FCB $00
FCB $00
FCB S2E
FCB $11
FCB $00
FCB $3D
FCB $89
FCB SFF
F a $53
FCB $00
FCB $00
FCB $80
FCB $00
FCB $00
FCB $FF
MF9
FCB $04
FCB $IF
FCB $00
FCB $00
FCB $00
FCB $3F
FCB $CC
FCB $00
FCB $53
FCE $D7
FCE $FF
FCB $66
FCB %O0
FCB $00
FCB $80
FCB $00
FCB $00
FCB SFF
MF10
FCB $00
FCB $OF
FCB $00
FCB $00
FCB $00
F a $51
FCI3 SC2
FCB $00
FCB $66
FCB $00
FCB $FF
Appendix C: Conuoller Source Code

FCB $80
FCB Soo
FCB $FF
FCB SFF
MF1 1
FCB Soo
FCB Sot
FCB $38
FCB $00
FCB SFF
FCB $FF
MF12
FCB $00
FCB $01
FCB Sm
FCB $00
FCB SFF
FCB $FF
MF13
FCB $00
FCB $01
FCB $7F
FCB $00
FCB $FF
FCB $FF
MF14
FCB $00
FCB $01
FCB %Al
FCB $00
FCB %FF
FCB $FF
MF15
FCB $00
FCB $01
FCB SC3
FCB $00
FCB $Fi?
FCB $FF
EVEN
FUZZYTEST:
JSR INlT
LDAA ïNPüTS+$ûû
STAA iN-BUF
LDAB #$O1
JSR MF,SUB
STAA TVLST+$OO
LDAB #$O2
JSR MF,SUB
STAA TVLST+$Ol
LDAB MO3
JSR MF,SUB
STAA TVLST+$02
LDAB #$W
JSR MF-SUB
S'CAA TVLST+$03
LDAB n$05
JSR MF,SUB
S m TVLST+$OQ
LDAA ERROR CHANGE *Lod emr change
S T U IN-BUF-
Appendix C: ControUer Source Code

LDAB n$06
JSR MF-SUB
STAA TVLST+SOS
LDAB -7
JSR MF-SUB
STAA TVLST+â06
LDAB 6 0 8
JSR MF-SUB
STAA TVtST+$07
LDABm9
JSR MF,SUB
STAA TVLST+$OS
LDAB W A
JSR MF-SUB
STAA TVLST+$û9
LDAA TVLST+$04
STAA AND-REG
LDAA TVLST+$O!3
JSR MINI-OP
LDAA ANDANDREG
STAA OR-RJ2G
LDAA TVLST+$04
STAA AND-REG
LDAA TVtST+$OS
JSR MiNl-OP
JSR MAXZ-OP
LDAA TVLST+$W
STAA ANDANDREG
LDAA TVLST+$07
JSR MINI-OP
JSR MAX2-0P
LDAA TVLST+W3
STAA ANDANDREG
LDAA TVLST+$û9
JSR MIN1,OP
JSR MAX2-OP
LDAA TVLST+$û2
STAA AND-REG
LDAA TVLST+$O9
JSR MIN1,OP
JSR MAX2-OP
LDAB #$3B
JSR DF2-C
LDAA TVLST+$04
STAA ANDANDREG
LDAA TVLST+âOo
JSR MIN1,OP
LDAA AM)-REG
STAA OR-REG
LDAA TVLST+â03
STAA AND-REG
LDAA 'iVLST+$OS
JSR MIN1,OP
JSR MAX2-OP
LDAA TVLST+$03
STAA AND-REG
LDAA TVLST+$û7
JSR MIN1,OP
JSR MAX2-OP
LDAA TVLST+$02
STAA AND-REG
Appendix C: Controuer Source Code

LDAA TVLST+WS
JSR MINI-OP
JSR MAXî-OP
LDAB #Sm
JSR DF2-C
LDAA TVLST+W
STAA AND-REG
LDAA WLST+WS
JSR MINI-OP
LDAA ANDANDREG
SïXAORJEG
LDAA TVCST+$û3
STAA AND-REG
LDAA TvLST+W
JSR MINI-OP
JSR NAX2-0P
LDAA TVLST+$03
STAA AND-REG
LDAA TVLST+$OS
JSR MIN1,OP
JSR MAX2-OP
LDAA TM,ST+$OZ
STAA AM)-REG
LDAA TVLST+$07
JSR MIN1,OP
JSR MAX2-OP
LDAA TVLST+%O1
STAA AND-REG
LDAA TVLST+$OS
JSR MINI-OP
JSR MAX2-OP
LDAA TVLST+$O
STAA AND-REG
LDAA TVLST+$OS
JSR MIN1,OP
JSR MAX2-OP
LDAB #$7l?
JSR DE-C
LDAA *ST+$O~
STAA AND-REG
LDAA TVLST+$Oo
JSR MINI-OP
LDAA AND-REG
STAA OR-REG
LDAA ïVLST+$ûl
STAA ANDANDREG
LDAA TVLST+$û8
JSR MINI-OP
JSR NAX2-0P
LDAA TVLST+$ûl
STAA AND-REG
LDAA TVLST+â07
JSR MINI-OP
JSR MAX2-OP
LDAA TVtST+$ûl
STAA AND-REG
LDAA TVtST+$û6
JSR MIPII-OP
JSR MAXî-OP
LDAA TVLST+W
STAA AM,-REG
Appendix C: Conmller Source Code

LDAA TVLST+âOS
JSR MIN1,OP
JSR MAXZ-OP
LDAB #$A1
JSR DFZ,C
WAA W T + â 0 2
S W AND-REG
LDAA TVIiST+âOS
JSR MINI-OP
LDAA AM)-REG
STAA OR-REG
LDAA TVLST+âO1
S U ANDJZEG
LDAA TVLST+âoS
JSR MIN1,OP
JSR MAX2-OP
LDAA TVLST+$OO
STAA AND-REG
LDAA TVLST+$O7
JSR MINl-OP
JSR MAX2-OP
LDAA TVLST+$OO
STAA ANDANDREG
LDAA TVLST+$06
JSR MIN1,OP
JSR MAX2,OP
LDAA TVLST+$OO
STAA AND-REG
LDAA TVLST+$OS
JSR MIN1,OP
ISR MAX2-OP
LDAB #$C3
JSR Dm-C
JSR DIV-SUB
LDX #$O0
LDAA OUTUTREG *load A
CLRW HYD-SIGNAL *clex E to ensure MSB is clear
STAA HYD,SIGNAL+l *store hydraulic sigoal value to LSB (=no change)
RTS
MIN1,OP CMPA AND-REG
BCC MINI-E
STGA AND-REG
MINI-E RTS
MAXî-OP LDAA AND-REG
CMPA OR-MG
BCS MAX2-E
S W OR REG
MAXZ-E RTS-
D u LDAAOR-REG
MUL
TAB
CLRA
ADDD TUH-EUX
S m TUH-REG
CLRA
LDAB OR-REG
ADDD SUH-REG
STD Sm-REG
RTS
DN-SUB LDD TUH REG
LDX sUH-REG-
Appcndix C: Controller Source Code

BCS DIV-1
XGDX
S'ïAA OUT'REG
RTS
DIv-1 CLROUT-REG
ms
INiT CLRTUL-REG
CLR TUH-REG
CLR SUL-REG
CLR Sm-REG
RTS
MF,SUE ASLB
SUBB #$2
CLRA
ADDD #MF-OFF
XGDX
LDX $OX
LDAA $ 0 3
STAA MF1,REG
LNX
LDAA $ 0 3
STAA MF2-REG
LSL MFt-REG
LSL MF2-REG
LNX
MFJ XGDX
GDDD 6 3
XGDX
LDAA $OX
LSR MF1,REG
LSR ME;2-REG
CMPA IN-BUF
BLO MFJ
LSR MF1,REG
BCS MF-2
JSR MF32
ADDB MFI-REG
BCC MF-4
LDAB #$FF
M E 4 TBA
RTS
M F 3 2 DEX
LDAA $OX
STAA MFl-REG
LSR MF2-REG
BCC MF-3
ISR MF,S 1
LSRD
LSRD
LSRD
LSRD
TSTA
BEQ MF-7
LDAB # S E
MF-7 RTS
MF-3 JSR MF,S I
TSTA
BEQ MF-5
LDAB #$FF
MF-5 RI'S
Appendix C: Controlkr Source Code

-1 DEX
LDAA m x
S U MF2-REG
LDAA IN-BUF
DEX
SUBA S O X
LDAB MF2-REG
MUL
RTS
MF-2 JSRMF-SZ
STAB MF2-REG
LDAA MFI-REG
SUBA MF2-REG
BCC MF-6
LDAA 460
MF-6 RTS

******************************************************************************
* *
* SEND OUT SIGNAL TO HYDRAULIC CONTROL signals are adjusted to compensate *
* for the nansfer fiinction of the hydraulic valve
* *
******************************************************************************
HYD-CONT:
LDAB #$O1
TBEK ****FIRST--inven the hyd signal to reflect valve action
* s u s lifting at $77-max at $68
* s u s lowering at S8F-max at S9B
LDAA HM)-SIGNAL+l *Io& output h m fuzzy engine
LDAB #$7F * b d midpoint between O and FE
SBA *get the dïerence h m tbe "mitidle"
BMI NEG-RESULT *beginning of control gain scaling-if negative, skip
****scaling for positive result of HYD-SIGNAL less than 7F
LSRA *scaling factor-divide by 2
NEGA *invert this difference
ABA *add it, to give equai magnitude in opposite direction
BRA SCALING-DONE *branch here when done the scaling
NEG-RESULT: *scaling for negative result of )IYD-SIGNAL less than 7F
NEGA *invert ihis difference
LSRA *scaling factor-divide by 2
ABA *add it, to give equal magnitude in opposite direction
SCALING-DONE:
STAA HYD,SIGNAL+l
T S W RAISE,DEPTHEPTHFLAG *if set, discs must be lowered
BMI SUBTRACT-2 *IF FLAG N E G N ï ï E (discs mut be lowered) BRANCH
****(disis need to be raised-below set point)****
LDE HYD-SIGNAL
SUBE #$OOOC *subnact 9 to b ~ O signalg h m 7F to 77
LDAB #$OF *since hyd valve won't move at less than 89
TBEK
TED
STAB PWMA
RTS
****(disks necd to be lowered-above set point)****
SUBTRACT,2:
LDE EiYD-SIGNAL
ADDE #S000D *add C to bring O signal from 7F to 8D
LDAB #$OF *since hyd valve won't move at more tbat 71
Appendix C: ControUer Source Code

TBEK
TED
STAB PWMA
rn

SEND-Dm:
LDAB 6 0 1
TBEK
LDX #DATA -END ;point to the beginning of data to send
LDE #$OOOA- ;load data uansmit index for 10data points
STE DAIA-INDEX ;Save locaaon index
CLRE
STE DMX-TOTOSEND ;put in temp array
STE DATAATOOSEND+2;cIearword
LDD INPUTS ;Io& error h m seeding set point
STAA DFiIAFiIATOTOSEMh1 ;put &bit data in proper order
LDD ERROR-CHANGE ;get change in e m r h m 10 readings previous
STAA DMX-TOTOSEND+3;put &bit data in proper order
LDE KYD-SIGNAL ;get fiuq decision output
STE DAïA TO,SEM)+4 ;put in temp amy
LDAB WSOF-
TBEK
LDE EUURRl ;get fiont sensor 8-bit a/d vdue
LDAB #$O1
TBEK
STE DATA TO,SEM)+6 ;put in temp array
LDAB WF-
TBEK
LDE RJURRO ;get &SC sensor &bit a/d value
LDAB #$O1
TBEK
STE DATA TO,SEND+8 ;put in temp array
LDAB #$OF-
TBEK
PC-READY 1:
LDAB SCSR+1 ;check "Receive Data Register Full" flag-should bave
BITB #$4û ;START signal h m PC in buffer
BEQ PC-READY 1 ;if not, go back aod check again
LDAB SCDR+l ; l d receive cegister into B
SUBB #$OF ;see if if has received an $F (this is the START sig)
BNE PC-READYl
SEMl,STRR?JG2: ;subroutine to send out tbe entire ASCa string
LDAB #$OF
TBEK
LDAB #$O1
TBXK
LDAB OX ;get next byte in string as pointed to by IX
TBA ;data byte now is transfened to acc A
LDAB
TBXK
JSR SEND-CH ;go send out the byte
AIX #$O1 ;increment IX to point to the next byte
LDAB #$O1
AppendU C: Controller Source Code

TBEK
DECW DMAJNDEX ;decrementtransmit counter
TSTW D H ' I N D E X if6 samples haci b e n taken
BNE SEND STRING2 ;loop back and do nea byte in soing
LDAB #$OF
TBEK
KI'S
SEND-CH: ;subroutine to send out one byte to SC1
LDAB SCSR ;check 'TcitllSmitData Rcgister Enable" bit, $0, means
AM)B #SOI ;register TDR sàll bas data to be sent to a seriai s W f
BEQ SEM)-CH S T D R is not empty, go back to check it again
TAB ;&ta byte ttansferred to B-had to do tbis since ody acc B &ers to K
LDAA #!§O0 ;cl= A to send a fiiil w o d to SCDR (SFFCOE)
STD SCDR ;transmit one ASCII character to the PC
TC-LOOP:
LDAB SCSR+l
ANDB #$80 ;test the TC bit (transfer complete)
BEQ TC-LûûP ;continue to wait until TC is set
LDAB SCSR ;test transmit buffet empty
ANDB #!SOL
BEQ TC-LOOP
LDAB #$OF
TBEK
ET-READYZ:
LDAB SCSR+1
BITB #$40 ;check for "CONTINUE" h m PC
BEQ PCPCREADY2 ;if not, go back and check again
LDAB SCDR+l ;load receive register into B
SUBB #$OE ;see if if has received an $E
BNE PC-READY2 ;if not, go back and check again
LDAB #$O1
TBEK
RTS ;finish sending out byte

* LCD MESSAGES *
* *

EVEN
RAiSE-MESSAGE 1 DC ' L m IMP- ',m
EVEN
RAISE-MESSAGE2 DC 'IMPL- RAISED',$OO
EVEN
LOWER-MESSAGE DC "TO SEED DEITH ',â00
E V ~
SET-RAISEJMSG DC 'SET RAISED POSN ',$W
EVEN
HIT-KEY-MSG DC 'IITT ANY KEY ',â00
EVEEl
ENTER-JiEIGHT DC 'ENTER INCHES: ',$O0

EVEN
ERR-PRESS-MSGO DC 'OH S m ,ERROR; ',$O0
EVEN
Appendùt C: Conttoiier Source Code

ERR-PRESS-MSG~ DC TME FOR A BEER *,s00


EVEN

ENTER-DEPTH DC 'ENTERïNCHES: '$00


E3EN
ENTERJm-Dm DC 'ENTER TENTH INCH',m
EVEN
-Dû-SET-MSG DC 'SETSOIL SURFACE',$OO
EVEN

HIT,TO-STORE DC 'HTT KEY TO STOE',$O


EVEN
LEVH.0-SET-MSG DC 'DiSC SENSOR CAL',$ûû
EVEN
LEVELF-SET-MSG DC 'FRONT SENSOR W , $ O O
EVEN
LEVEiEVEtSURF'CALIB DC 'ON LEVEL SURFACE',SOO
EVEN
DISC-LJ3ELtEVEL,2EROMSGDC 'LOWER TO SURFACE',$OO
EVEN
SIX-IN-CALIBO MJ 'RAISE DISKS UP ',$O0
EVEN
SIX-IN-CALIB 1 DC 'SIX INCHES ',$O0
EVEN

GREETINGS2 DC 'Depth Controller',$ûû


EVEN
CHOOSE-MODE-MSG DC 'Choose Scan Mode',$OO
EVEN
MODE-A DC 'Ress O for duai*,$ûû
EVEN
MODE-B DC 'sensors. 1 for '$00
EVEN
MODE-C DC 'single sensor *,$O0
EVEN
CHOOSE-FUNÇ1lONNMSG DC 'Choose Funcaon:',$OO
EVEN
PICK-MODE-OLRAISEl DC 'Press O to pick ',$O0
EVEN
PICK-MODE-OR-RAISE DC 'sensor modes, 1 ',$O0
EVEN
PICK-MODE-OR-RAiSE3 DC 'to set &er ',$ûû
EVEN
PICK-MODE-OR-RAiSE4 DC ' r a i d position,*,$OO
EVEN
PICK-MODE-OR-RAISES DC '2 to set units ',$O
EVEN
PICK-tJNIT-MESSAGE1 DC 'O for imperial, ',$O0
EVEN
PICK-üNïï-MESSAGE2 DC 'hic 1 for METRlC',$ûû
EVEN
PICK-CALIB-9û-ORJ5TNl DC 'Ress O to set ',â00
EVEN
DC 'sensrs 90 &g to*,$OO
PICK,CALIBALIB9û-ORJIN2
EVEN
PICK,CAtIB,90_0R,GIN3 DC 'iinkages, I to ',$O0
EVEN
PICK-CALIB,90_0R,6IN4 DC 'cal disk sensor,',$OO
Appendix C: Controlfer Source Code

EVEN
PICK,CALIBSO,OR,oINS DC ' 2 4 b n t sew*,$ûû
EVEN
CALIB-9û DEGl DC 'PROCEDORE TO 'JXlû
EVEN-
CALIB-90 DEG2 DC 'STORE THE SENSOR'SHI
EVmi-
CALIB-90 DEG3 DC 'POSITION 90 DEG ',$(Ml
Evmi-
CALIB-90 DEG4 DC 'TODISK LINKAGE ',$Ml
EVEN-
SET~TO~~O-MSG1 DC 'Position disk so*,$ûû
EVEN
SETETTOT09û90MSG2DC 'sensor a m is W,$ûû
EVEN
SETETTOTO9O-MSG3 DC 'deg to disk arm ',$O0
EVEN

*
* TABLE FOR KEY IDENTIFlCATION
* *

KEY-TABLE:
DC,B $EE *O
DCB $DE *1
DC.B $BE *2
DCB $7E *3
DC.B SED *4
DCB $DD *5
DC.BSBD *6
DC.B$7D *7
DC.B$EB 8
DCB $DB *9
DC.B SBB *A

EVEN
SINE-TGBLE:
FCB %00,$01,$03,b05,$06,~8,W,$0~
FCB $OD,SOE,$OE,$11,$12,$14,$16$17
FCB $ 19.âl&$lC,$ IE,$IF,$20,$22.$23
FCB $Sv$
26,$28,$29,$2B,b2C,$ZE,S2F
FCB $30,$32.$33.$35.$36.$38.$39.$3A
Appendur C: Conmller SourceCode

ORG $10000 *Equates stanat $1000


MF,OFF EQUS1600
INPUTS RMB $02
TVLST RMB $OF
IN-BUF RMB 1
MFI-REG RMB 1
MF2-REG RMB 1
AND-REG RMB 1
OR-REG RMB 1
TUH-REG RMB 1
TUL-REG RMB 1
SUH-REG RMB 1
SUL-REG RMB 1
OUT-REG RMB 1
BüF-REG RMB I
IRQ-COUNT R M B $02 *IO002 *Location of number of IRQ's for debounce
KEY RMB $û2 * 10008 *Hexvalue of the key being pressed
KEY-ERR-COONTER RMB $02 * l W A *Couter to prevent non-table key id fÏom
*causing an endless loop
INDEX RMB $02 *1000C %ern location for keypaci values for cornparison
*to acc A on each loop
RAISED RMB $02 * 1000E *raised position setting
RAISED2 RUB $02 *terne location used in SET,OPERATING-DEFTEI
DISC-LEVEL-ZERO RMB $02 * 10010 *zero position on a Bat surface-used in cdibration
CALIB-DEITH RMB $02 *10014 *6" depth position-obtained in calibratïon
OPEXUTXNG-DEPTEI RMB $02 *IO016 *operatkg depth-seed deptti set by operator
SEEnDEPTH-ERROR RMB $02 * lûûl8 * c m n t e m r Born operating depth set point
PREMOUS-ERROR RMB $02 * 1001A *previous emr value
ERROR-CHANGE RMB $02 *1001C *Merence between present and previous emr
CM-CONV-FA0 R RMB $02 * 10026 *" " " " cm-remainder derived h m
*ND-zero point / calib distance (ie, 6 inches)
CONV-TEMP RMB $û2 *10MC *temp for first step in conv hex k t i o n a l to decimal
SIGN-FLAG RMB SM * 1- *location for the negative flag (set when above gmd)
W S RMB $02 *10030 *wkn set, uses inches (dehult). Zero,uses centimetres
HYDRAUL-TIMERI RMB $02 * LOO32 *nuxnber to count down during HYDRALJL delay
HYDRAUL-TIMER2 RMB $02 * lOOM *2nd timcr vaiuemo. times to count d o m
COUNTDOWNl RMB $û2 * 10036 *mem location for counting ualities-1/4 second
COUNTDOWN2 RMB $û2 *lm38 *memlocation for 2nd counthg location-ln second
KEYPRESSED RMB SI2 * lW3A *flag to show that a key has been pressai lqressed
IN-CONV-FACTOR2 RMB $02 1003C *inch conversion factor for raised height setting
OUTPUT
TEM~-CONV RMB $02
TEMP-DELAY
- --
RMB $02 *1003E *output value to the D/A conversion routine
*- rn TEMP in lcdmdasm
RMB $02 *10046 *ump variable for delays
TEMP-DUY2 RMB $02 * 1 W *temp variable for delay-acc E contents
HALFSEC DIIT RMB $02 'l004C " " " halfsecond
KEYASCIÏ RMB 502 lOO4E *location for ueü identity for LCD pdnting
IRQIDONE RMB $02 *10050 *0ag ïndicating keypad RQ done ( h m HEXCONV)
KEYCHECK RMB $02 * l m 2 *flag indichg checking for any key pressed only (not id of key)
HEXKEYHEXKEYHIT RMB $02 *IO054 *flag indicaiing a key fom A-F was hit
TEMP-CONVO RMB $02 10056 *temporary variable location for decimal conversion
DEPTH-INCHES RMB $02 * IO066 *location for the decimai inches for lcd
DEITH-LOTH RMB $02 *1005C *location for l/lûth inch decimal for lcd
DEPTHJKITH RMB $02 * 100SE *location for l/lûth Uich decimal for lcd
Appendix C: Controller Source Code

DEPTHEPTHIûWSXRMB $02 * 10060 *X-on for 11100th inch decimal for lcd roundoff
OP-DISPLAY-ON IMB $02 * L W 2 *tlag showing that tbe operathg display is on
ADC-CHANNEL RMB $02 *Idon for telhg which A/D to rcad firnn
DISC-READING RMB !5û2 *location for @th readiagh m &CS
DEPTH-1OINCHES RMB a02 *location for 10 incbes numeral
HYD-SIGNAL RMB $02 *locationfor output
DISCJW%iYJEGJOS RMû $02 *location for output
CORRECFEn-FIELD-ZERO RMB $02 *10012 *zero position set by operator
CORRECIED-DISC-READING RMB $02 * I d o n for depch reading h m discs
CORPECFEnDEPTEI-READDG RMB $02 *location for depth reaàing b r n discs
FRONT-READING RMB $02 *locationfm AID 1 for second sensor
CORPE~JRONï'ZERO RMB $02 *location for FRONT zero reading
COREECïEDJRONT-READiNG RMB Sû2 *l-on for b n t seasor corrccted reading
FRONT-iEV'EL-ZERO RMB â02 *GROUND POSITION FOR CALIBRATIONOF FRONT SENSOR
FRONT-%-READING RMB $02 *90 DEG POSITION OF FRONT SENSOR
FRONT,GROUNDUNDZERORMB $02 *GROIMD READING FOR THE FIEW)
EIYPOTENEUSESFRONT RMB $02 *hypotenuese for front, is hypot * a factor
TRUE-O-DEITH RMB $02 *ternp Iocation for diffetence between zero and 90,deg
HYPOTENEUSE-DISC RMB Sû2 *constant value fm angle correction factor
ERROR-TNLE RMB S 14 *&ange in error circular buffer
Da-TO-SEM) RMB $OA
DATA-INDEX RMB $02
RAISE-DEPTH-FLAG RMB $02 *when set. means the discs are too deep-raise discs
ERROR-CONVNVFORMAI:RMB SM *errer fiom sutface in 1000's inch divided by 200
OPERATING-DEITH-CONVNVFOURMB $02 *operathg depth (in 1000's in) /factor
CIRCCERROR,BUFFER RMB $02 *cucutar error b a e r index

Table of EQUATES for register locations:

*DESCRIPTION :THIS IS A TABLE OF EQUATES FOR ALL OF THE


* REGISTERS IN THE MC68HC16Zl.
**********8******+*8*****2************8*************88*S********8*******8**

***** SIM MODULE REGISTERS *****


SIMMCR EQU $FA00 ;SM MODULE CONFIGURAI1ON REGISTER
SIMTR EQU $FA02 SYSTEM INTEGRATION TEST REGISTER
SYNCR EQU $FA04 ;CLûCK SYNTHESIZER CONTROL REGISTER
RSR EQU $FA07 ;RESETSTkT'üS REGISTER
SIMTRE EQU SFAO8 ;SYSTEMINTEGRATION TEST REGISTER (EUûCK)
PORTE0 EQU $FA11 ;PORTE DATA REGISTER ( S A M ' DATA AS PORTE1)
PORTE1 EQU $FA13 ;PORTEDATA REGISTER (SAME D m AS POKïEO)
DDRE EQU $FA15 ;PORTE DAfA DIRECITON REGISTER
PEPAR EQU $FA17 ;PORTE PIN ASSIGNMENT REGISTER
PûRTFO EQU $FA19 ;PORT F D m REGISTER (SAME D m AS PORTFI)
PORTFL EQU $FAIS ;PORT F DiUA REGISTER ( S A M E D m AS PORTFO)
DDRF EQU SFAlD ;PORT F DATA DIRECTION REGISTER
PFPAR EQU SFAlF ;PORT F PIN ASSIGNMENT REGISTER
SYPCR EQU SA21 ;SYSTEMPROTECTION CONTROL REGISTER
PICR EQU $FA22 ;PERIODIC INTERRWï CONTROL REGISTER
PïïR EQU $FA24 ;PERIODICINTERRUPTTIMING REGISTER
SWSR EQU $FA27 ;SOFiW"RESERVICE REGISTER
TSTMSRA EQU $FA30 ;MASTER SHIFT REGISTER A
TSTMSRB EQU $FA32 ;MASTER SHJFï REGISTER B
TSTSC EQU $FA34 ;TESTMODULE SMFT COUNT
TSTRC EQU $FA36 ;TESTMODULE REPEïïTiON COüNT
C E G EQU $FA38 ;TEST SUBMODULECONTROL REGISTER
DREG EQU SFMA ;DISTRiBUTÊDREGISTER
Appendix C: Controuer Source Code

CSPDR EQU =A41 ;PORT C DAïk REGISTER


CSPARO EQU WA44 ;CHIPSELECl' PIN ASSIGNMENT REGISTER O
CSPARl €QU SA46 ;CHIPSELECT PIN ASSIGNMENT REGISTER 1
CSBARBT EQU WA48 ;Cm-SELECT BOOT BASE ADDRESS REGISTER
CSORBT EQU $FA4A ;CHP-SELECT BOOT OPTION REGISTER
CSBARO EQU WA4C ;CEIIP-SELECT O BASE ADDRESS REGISTER
CSORO EQU $FA4E ;CHIP SELECï O OPTION REGISTER
CSBARl EQU â F ' ;CHIP-SELECX' 1 BASE ADDRESS REGISTER
CSORl EQU $FA52 ;CHIP-SELECï 1OPTION REGISTER
CSBAR2 EQU WAS4 ;CHIP-SELECT 2 BASE ADDRESS REGISTER
CSOR2 EQU $FA56 ;CHIP-SELECï 2 OPTION REGISTER
CSBAR3 EQU $FA58 ;CHIP-SELECT 3 BASE ADDRESS REGISTER
CSOR3 EQU SFMA ;CHIP-SELECï 3 OPTtON REGISTER
CSBAR4 EQIJ $FAX ;W - S E L E C T4 BASE ADDRESS REGISTER
CSOR4 EQU $FASE ;CHIP-SELECT 4 OPTION REGISTER
CSBARS EQU $FA60 ;CHIP-SELECT5 BASE ADDRESS REGISTER
CSORS EQU $FA62 ;CHP-SELECï 5 OPïXON REGISTER
CSBAR6 EQU *A64 ;CHIE'-SELECI'6BASE ADDRESS REGISTER
CSOR6 EQU $FA66 ;CHIP-SELECX 6 OPTION REGISTER
CSBAR7 EQU $FA68 ;CHIPSELECT 7 BASE ADDRESS REGISTER
CSOR7 EQU SFA6A ;CHIP-SELECT 7 OPTION REGISTER
CSBAR8 EQU $FA= ;CHlP-SELECT 8 BASE ADDRESS REGISTER
CSORS EQU SFA6E ;CHE-SELECX' 8 OPTION REGISTER
CSBAR9 EQU $FA70 ;CHIP-SELECI' 9 BASE ADDRESS REGISTER
CSOR9 EQU SA72 ;Cm-SELECT9 OPTION REGISTER
CSBARIO EQU $FA74 ;CHIP-SELECT 10 BASE ADDRESS REGISTER
CSOR10 EQU $FA76 ;CHIP-SELECT 10 OPTION REGISTER
***** SRAM MODULE REGISTERS *****
RAMMCR EQU $FBûû ;W MODULE CONFiGURNION REGISTER
RAMTST EQU Sm02 ;RAM TEST REGISTER
RAMBAH EQU $BO4 ;RAM BASE ADDRESS HIGH REGISTER
RAMBAL EQU âFB06 ;RAM BASE ADDRESS LOW REGISTER
***** QSM ADDRESS MAP *****
QMCR EQU $FCOO ;QSM MODULE CONFIGUFUTiON REGISTER
QTEST EQU SFCM ;QSM TEST REGISTER
QILR EQU $FCW ;QSM INTERRUPT LEVELS REGISTER
QNR EQU SFCOS ;QSM iNTERRUPT V E W R REGISTER
SCCRO EQU SFCO8 ;SC1CONTROL REGISTER O
SCCRl EQU SFCOA ;SC1 CONTROL REGISTER 1
SCSR EQU $FCK ; S a S'CATUS REGISTER
SCDR EQU SFCOE ;SC1 DATA REGISTER (FULLWORD, NOT LAST 8 BITS)
QPDR EQU SFClS ;QSM PORT D m REGISTER
QPAR EQU âFC16 ;QSM PIN ASSIGNMENT REGISTER
QDDR EQU SFC17 ;QSM DAIA DIRECTION REGISTER
SPCRO EQU SFC18 ;QSPI CONTROL REGISTER O
SPCRl EQU SFCIA ;QSPI CONTROL REGISTER 1
SPCR2 EQU $FClC ;QSPI CONTROL REGISTER 2
S E M EQU SFClE ;QSPI CONTROL REGISTER 3
SPSR EQU SFClF ;QSPI SïXïüS REGISTER
RRO EQU $FMI0 ;SPI REC.RAM O
RR1 EQU SFDû2 ;SPI REC.RAM 1
RR2 EQU $FDû4 ;SPI REC.RAM 2
RR3 EQU $FMI6 ;SPI REC.RAM 3
RR4 EQUSFDO8 ;SPIREC.RAM4
RE# EQU SFMIA ;SPI REC.RAM 5
'

RR6 EQU ;SPIREC-RA.6


RR7 EQU $FMIE ;SPI REC.RAM 7
RR8 EQUSFDOO ;SPIREC.RAM8
RR9 EQU S m 2 ;SPI REC.RAM 9
RRA EQU $FDOL) ;SPIREC-RAMA
RRB EQU âFD06 ;SPI REC.RAM B
Appendix C: Conmller Source Code

RRC EQU SFDû8 ;SPIREC_RAMC


RRD EQU SFDOA ;SPI REC.RAM D
RRE EQUSFDOC ;SPI R E C M E
RRF EQU SFDOE ;SPI R E C M F
TRO EQU$FD20 ;SPIïXDcRAMO
TR1 EQU S m 2 2 ;SPI T X D U 1
TR2 EQUSFD24 ;SPITXDJUM2
TR3 EQUaFD26 ;SPITXD.RAM 3
TR4 EQUSFD28 ;SPITXD-RAM4
TR5 EQUSFD2A ;SPITXD-RAM5
TR6 EQU$FD2C ;SPITM).RAM6
TR7 EQUSFDîE SPITXD.RAM7
TR8 EQU$FD30 ;SPITXD.RAM 8
TR9 EQU $FD32 ;SPI T%D.RAM 9
TRA EQUSFD34 ;SPITM).RAMA
TRB EQU EFD36 ;SPI TXD.RAM B
TRC EQU S m 3 8 ;SPITXD.RAMC
TRD EQUâFD3A ;SPITM)cRAMD
TRE EQU $FD3C ;SPI TXD.RAM E
TRF EQU $FD3E ;SPI TXD-RAMF
CR0 EQU $FM0 ;SPI CMD-RAMO
CRI EQU$FD41 ;SPICMD-RAM 1
CR2 EQU $FD42 ;SPICMDcRAM2
CR3 EQU $Fi343 ;SPI CMD,RAM 3
CR4 EQU SFD44 ;SPI CMD-RAM 4
CRS EQU $FD45 ;SPI CMD-RAM 5
CR6 EQU $Fil46 ;SPI CMD.RAM 6
CR7 EQU $FD47 ;SPLC M D M 7
CR8 EQU $FD48 ;SPI CMD.RAM 8
CR9 EQU $Fi349 ;SPI C M D M 9
CRA EQUSFD4A ;SPICMD..RAMA
CRB EQU $FD4B ;SPI CMD.RAM B
CRC EQU $FD4C ;SPI CMD.RAM C
CRD EQU SFD4D ;SPI C M D M D
CRE EQU WiME ;SPI CMD-RAME
CRF EQU $FD4F ;SPI CMD.RAM F
***** GPT MODULE REGISTERS *****
GPTMCR EQU âF900 ;GPT MODULE CONFIGURATfON REGISTER
GPTMTR EQU SF902 ;GPT MODUtE TEST REGISTER (RESERVED)
ICR EQU $F904 ;GPT INTERRUPT CONFIGüRKîION REGISTER
PDDR EQU $F906 ; P U E L DMA DIRECTION REGISTER
GPTPDR EQU âF907 ;PARAiLELDACA REGISTER
ûClM €QU$F908 ;OC1ACTION MASK REGISTER
ûClD EQU $F909 ;OC1 ACTION DAIIA REGISTER
TCNT EQO $ M A ;TIMERCOUNTER REGISTER
PACTL EQU $E;90C ;PULSEACCUMULASOR CONTROL REGISTER
PACNT EQU $F90D ;PULSE ACCUMULAIIY)R COUNTER
TIC1 EQU EF9ûE ;INPUTCAPlURE REGISTER 1
TIC2 EQU SF910 ;INPUTCAPTURE REGISTER 2
Tic3 EQU SF912 ;INPUT CAPTUE REGISTER 3
TOC1 EQU $F914 ;OUTPUT COMPARE REGISTER 1
TOC2 EQU SF916 ;OUTPUT COMPARE REGISTER 2
TOC3 EQU SE918 ;OUTPUT COMPARE REGISTER 3
TOC4 EQU SF9 1A ;OUTPUTCOMPARE REGISTER 4
Ti405 EQU W91C ;INPUTCAPTüRE 4 OR OUTPUTCOMPARE 5
TCTLL EQU SF91E ;TIMER CONTROL REGISTER 1
TCIL2 EQU SF91F ;TIMERCONTROL REGISTER 2
TMSKI EQU SF920 ;'ïIMER INTERRUPT MASK REGISTER 1
TMSK2 EQU $F921 ;TIMERINTERRüPT MASK REGISTER 2
TFLGl EQU âF922 ;TIMER INTERRüPTFLAG REGISTER 1
TFLG2 EQU W923 ;TIMERINTERRüP'ï' FiAG REGISTER 2
Appendix C: ControllerSource Code

CFORC EQU W924 ;COMPAREFORCE REGISTER


PWMC EQU SB24 ;PWMCONTROL REGISTER
PWMA EQU -6 ; P mREGISTER A
PWMB EQU SB27 ;PWM REGISTER B
PWMCNT EQU SF928 ;PWMCOUNTER REGISTER
PWMBUFA EQU SF92A ;PWM BüFFEEk REGISTER A
PWMEUFB EQU$F92B ;PWMB- REGISTER B
PRESCL EQU SE92C ;GPT PRESCALER
**8** ADC M O D W REGIS- 888f 8

ADCMCR EQU $FI00 ;AM3MODULE CONFIGURAIIONREGiSTER


ADTEST EQU W702 ;ADCTESTREGISTER
ADCPDR EQU W706 ;ADC PORT D m REGISTER
ADCCLO EQU W70A ;NDCONTROL REGISTER O
1 EQU SF70C ;A/' CONTROC REGISTER 1
A D S W EQU SFIOE ;ADC S'IXKJS REGISTER
RJURRO EQU $FI10 ;RIGHT JüSTiFiED UNSIGNED RESUtT REGISTER O
RJURRl EQU $FI12 ;RIGHT JüSTIFED ONSIGNED RESULT REGISTER 1
RJLJRR2 EQU SF714 ;l?IGHT JUSTiFiED UNSIGNED RESUtT REGISTER 2
RJLJRR3 EQU $FI16 ;RIGHT NSTiFiED UNSIGNED RESULT REGISTER 3
RlURR4 EQU $Fi18 ;RIGH"I'JUSTiFIED UNSIGNED RESUtT REGISTER 4
iUURR5 EQU W 1 A ;RIGHI' NSTLFlED UNSIGNED RESULT REGISTER 5
RJURR6 EQU SF71C ;RIGHT' JUSTEIED UNSIGNED RESULT REGISTER 6
RnmR7 EQU $F71E ;RIGHT NSTiFiED UNSIGNED RESULT REGISTER 7
USRRO EQU SE720 ZEFï JUSTiFiED SIGNED RESULT REGISTER O
WSRRl EQU fF722 ;LEFT JUSTJFJED SIG- RESULT REGISTER 1
WSRR2 EQU f -24 UFI'JUSTlFIED SIGNED RESULT REGISTER 2
WSRR.3 EQU $F726 &EFï JUSlu;in> SIGNED RESOtT REGISTER 3
LJSRR4 EQU W 2 8 ; L WniSTiFlEI3 SIGNED RESOtT REGISTER 4
W S W EQU SF72A &EFi' JUSTIFET) SIGNED RESULT REGISTER 5
LJSRR6 EQU SF72C ; L mNS'I1FLED SIGNED RESULT REGISTER 6
USRR7 EQU SF72E ;LEETJUSTIFiED SIGNED RESULT REGISTER 7
WURRO EQU $F730 ;LEFTNSTiFIED UNSIGNED RESULT REGISTER O
WURRl EQU $F732 &EFT NS'IIFIED UNSIGNED RESULT REGISTER f
LJüRR2 EQU Sm34 ;LEFT NSTiFIED UNSIGNED RESULT REGISTER 2
WURlU EQU $F736 ;LEFI. JUSTEED UNSIGNED RESULT REGISTER 3
iJüRR4 EQW SR38 ;= JUSTEED UNSIGNED RESULT REGISTER 4
UURRS EQU $r/3A ;LEFI' JUSTIFED UNSIGNED RESULT REGISTER 5
LJ'üRR6 EQU SR3C ;mJUSTMED UNSIGNED RESUtT REGISTER 6
LNRR7 EQU SF73E ;LEFi' JUS'[1FIED UNSIGNED RESULT REGISTER 7

Initialization of the Reset Vectors: ORCOOOOOASM

ORG Sûûûû ;put the foiiowing reset vector information


;at address SOOOOO of the memory map
DC.w $0010 ;zk=o* s k l , p M
DC.W
M3.W
$0200
$03FE ;@3fe
--
;pc=200 initial programcounter
initial stack pointer
DC.W $0000 -
; i d direct page pointer
Appendix C: Controller SourceCode

Titie :ORG00008
Description :Tbis Me inïtiaIUes the iatcmiptl
-
exception vectm ( $ 0 8 $01fe).
If an inrempt OCCUIS tequiring ihe use of
any of these vectors, program flow wiU
continue at the iabct "Wm" wbich must be
added by the programmer to bisiher code to
put tht program into backgrounddebug made
or some otber appropriate rouùnc.

ORG $0008 ;put th foilowing code in memory


;starti*ngat address $0008 of the map
;@fierthe reset vector).
;thete is a total of 252 of these
;"DC.W BDM" tines
;Vector Numbef (in base 10)
;and Vector Description
DC.W BDM ;4 Breakpoint (BKPT)
DC.W BDM 5 Bus Error (BERR)
DC.W BDM ;6 Software Intempt (SWI)
DC.W BDM ;7 ïilegaf Instruction
DC-W BDM ;8 Divide by Zero
DC.W BDM ;9 (Unassigned Reserved)
DC-W BDM ;10 (Unassigned Reserved)
DC-W BDM ;11 (Unassigned Reserved)
DC.W BDM ;12 (Unassignecl Reserved)
DC.W BDM ;13 (Unassigned Reserved)
DC.W BDM ;14 (Unassigned Reserved)
DC.W BDM ;15 Uninitialized Intempt
DC.W BDM ;16 (Unassigned Resewed)
DC.W BDM ;17 Level 1 Intempt Autovector
DC.W BDM ;18 Level2 Intemipt Autovector
DC.W BDM ;19 Level3 Intempt Autovector
DC.W BDM ;20 Levef 4 Intempt Autovector
DC.W BDM ;21 Level 5 Intempt Autovector
DC.W BDM ;22 Level6 Intempt Autovector
DC.W BDM ;23 Level7 Interrupt Autovector
DC.W BDM ;24 Spurious h t e m p t
DC-W BDM ;25 (Unassigned Reserved)
DC.W BDM ;26 (Unassigned Resewed)
DC.W BDM ;27 (Unassigned Reserved)
DC.W BDM ;28 (Unassigned Reserved)
DC.W BDM ;29 (Unassigned Resewed)
DC.W BDM ;30 (Unassigned Reserved)
DC.W BDM ;31 (Unassigned Rcserved)
DC.W %DM ;32 (ünassigned Reserved)
DC.W BDM ;33 (Unassigned Rcscrved)
DC.W BDM ;34 (Unassigned Reserved)
DC.W BDM ;35 (Unassignal Reserved)
DC.W BDM ;36 (Unassigned Resewcd)
DC.W BDM ;37 (Unassigned Reserved)
K . W %DM ;38 (Unassigned Reserved)
DC.W BDM ;39 (Unassigned Rescrved)
DC.W BDM ;40 (Unassigned Rescrvcd)
DC.W BDM ;41 (Unassigned Reserved)
DC.W BDM ;42 (Unassigned Reserved)
DC.W BDM ;43 (Unassigned Reserved)
Appeadix C: Controller Source Code

DCW BDM med Rcservad)


DCW BDM mcd Resewd)
DC-WBDM dReservod)
DC-WBDM meci Reserved)
DCW BDM mcd Resewd)
DCW BDM m aiReserved)
DC-WBDM
DCW BDM mcd Reserved)
DC-WBDM aed Reserved)
DC-WBDM mcdReserved)
DC-WBDM Red Rtscwed)
DCW BDM aed Resewed)
DC-WBDM iaed Intemipt Vector 1
DC-WBDM ined Interrupt Vitor 2
DC-WBDM incd Intempt Vector 3
DC-WBDM! 5 9 User De ined htemipt Vector 4
DC.W BDM[ ;6û User De ined hterrupt Vector 5
DC.W BDM ;61 User De ined fntempt Vector 6
DC-WBDM: ;62 User De ined Intempt Vector 7
DCW BDM: ;63 User De ined Interrupt Vëctor 8
DC.W BDM: $54 User De ined Interrupt Véctor 9
DCW BDM: ;65 User De ured hterrupt Vector 10
DC-WBDM: ;66 User De uied ïnterrupt Vitor 11
DC-WBDM: ;67 UserDe ined Intemipt Vector 12
DC-WBDM: ;68 User De ured Intempt Vector 13
DCW BDM: ;69 User De ured Intempt Vector 14
DC-WBDM: ;70 User De ined Intempt Vector 15
DC.W BDM1 ;71 User De ined Intempt Vector 16
DC,W BDM: ;72 User De ined Intempt Vector 17
DC-WBDM: ;73 User De ined Intempt Vector 18
DC.W BDM: ;74 User De lned I n t m p t Vector 19
DC.W BDM: ;75 User De ned Intempt Vector 20
DC.W BDM: ;76 User De ned Intempt Vitor 21
DC-WBDM: ;77 User De ned Intempt Vector 22
DC-WBDM: ;78 User De ned Intempt Vector 23
DC-WBDM: ;79 User De ned Intempt Vector 24
DC.W BDM: ;80 User De ned Interrupt Vector 25
DC.W BDM: $1 UserDe ned Intempt Vector 26
DC-WBDM: $2 User De m d Intempt Vector 27
DC.W BDM: $3 User De ncd Intempt Vector 28
M3.W BDM: ;84 User De ned ïntempt Vector 29
DC.W BDM: $5 User De ned hterrupt Vector 30
DC.W BDM1 ;86 UserDe ned ïntecxupt Vector 31
DC.W BDM: $7 UserDe ned Interrupt Vitor 32
DC.W BDM. $8 UserDe ned Interrupt Vector 33
DC.W BDM: $9 User De ned Intempt Vector 34
DC.W BDM: $0 User De ned Interrupt Vector 35
DC.W BDM ;91 User De ned Intempt Vitor 36
DC.W BDM ;92 User De ned Intcmpt Vitor 37
M3.W BDM ;93 User De ned Intcmpt Vector 38
DC.W BDM ;94 user De ned Iatcmpt Vector 39
DC.W BDM: ;95 User De ned Intcmpt Vector 40
DC.W KEY.,IRQ;96 Uscrl icfined htempt Vcctor 41
DC.W BDM1 ;97 User De ncd Intemipt Vector 42
DC.W BDM1 ;98 User De ned Intempt Vector 43
DC.W BDM $9 User De ncd Intempt Vector 44
M3.W BDM ;100 User Dc ined Intempt Vcctor 45
DC.W BDM ;101 User Dc ined ïntcmipt Vcctor 46
M3.W BDM ;102 User Dc ined ïntempt Vector 47
DC.W BDM ;103 User Dc ined i'ntempt Vkctor 48
DC.W BDM ;104 User Dc incd intempt Vector 49
Appendix C: Controller Source Code

DC.W BDM ;105 User Defined Intempt Vectot 50


DC.W BDM ;106 User Defincd htenupt Vector 51
DC.W BDM ;107 User Defincd h t e m p t Vector 52
DC.W BDM ;LOS User Defined Intempt Vector 53
DC.W BDM ;109 User Defined h t e m p t Vector 54
DC.W BDM ;100 User Defincd Intcrnipt Vector 55
DC.W BDM ;111 User Defineci Intcnupt Vector 56
DC.W BDM ;II2 UscrDcfincdhtcmtptVcctot57
DC.W BDM ;1 13 User Defhed Intemipt Vector 58
DC-WBDM ;114 User Defined Intemipt Vector 59
DC.W BDM ;Il5 User Defined htemipt Vitor 60
DC.W %DM ;1 16 User Defined Intcmipt Vitor 61
DC.W BDM ;1 17 User Defined Intcmipt Vector 62
DC.W %DM ;Il8 User Defined Intempt Vector 63
DC.W BDM ;119 User Defined Intempt Véctor 64
DCW BDM ;120 User Defined Intempt Vector 65
DC.W BDM ;121 UserDefinedIntemiptVector66
DC.W BDM ;122 User Defined Intempt Vector 67
DC.W BDM ;123 User Defineci Intemipt Vector 68
DCW BDM ;124 User Defined Intempt Vector 69
DC-WBDM ;125 User Defined Intempt Vector 70
DC.W BDM ;126 User Defined Intempt Vector 71
DC.W BDM ;127 User Defined Intempt Vector 72
DC-W BDM ;128 User Defined Intemipt Vector 73
DC.W BDM ;129 User Defined Intempt Vector 74
DC.W BDM ;130 User Defined Intempt Vector 75
DC.W BDM ;131 User Defined Intempt Vector 76
DC.W BDM ;132 User Defined Intempt Vector 77
DC.W BDM ;133 User Defined Intempt Vector 78
DC.W BDM ;134 User Defined Intempt Vector 79
DC.W BDM ;135 User Defineci Intempt Vector 80
DC.W BDM ;136 User Defined Intempt Vector 8I
DC.W BDM ;137 User Defined Intempt Vector 82
DC.W BDM ;138 User Defined h t e m p t Vector 83
DC.W BDM ;139 User Defined Intempt Vector 84
M3.W BDM ;140 User Defined Intempt Vector 85
DCW BDM ;141 User Defined Intempt Vector 86
M3.W BDM ;142 User Defined Intempt Vector 87
DC.W BDM ;143 User Defined Intemipt Vector 88
DCW BDM ;144 User Defined Intempt Vector 89
DC.W BDM ;145 User Defined Intempt Vector 90
DC-WBDM ;146 User Defined Intemipt Vector 91
DC.W BDM ;147 User Defined h t e m p t Vector 92
DC.W BDM ;148 User Defined Intempt Vector 93
DC.W BDM ;149 User Defined Intempt Vcctor 94
DC.W BDM ;150 User Defineci Intempt Vector 95
DC.W BDM ;151 User Defined Intcmpt Vector 96
DC.W BDM ;152 User Deh e d h t e m p t V'tor 97
DC.W BDM ;153 User Defined Intempt Vector 98
DCW BDM ;154 User Defined h t e m p t Vectot 99
DC.W BDM ;155 User Defined Intempt Vector 100
DC.W BDM ;156 User b6ned Intemipt Vector 101
DC.W BDM ;157 User Defined Intempt Vector 102
DC.W BDM ;158 User Defined lntempt Vector 103
DC.W BDM ;159 User Defined latcmpt Vitor 104
DC.W BDM ;160 User Defin4 Intempt Vector 105
DC.W BDM ;161 User Defined Intemipt Vector 106
DC.W BDM ;162 User Defined h t c m p t Vector 107
DC.W BDM ;163 User Defîned Intempt Vator 108
DC.W BDM ;164 User ï>efiacdIntempt Vector 109
DC.W BDM ;165 User Defined Intermpt Vector 110
Appendix C: Controlier Source Code

DC-WBDM ;166 User Defined Intempt Véctor 111


DC.W BDM ;167 User Defined Intermpt Vector 112
DC-WBDM ;168 User Defined Intemrpt Vwor 113
DC-WBDM ;169 User Definai Interrupt Vector 114
DC-WBDM ;170 User Defineci Interrupt Vector 115
DC-WBDM ;171 User Defined Intempt V a o r 116
DC.W BDM ;172 User Defineci Intcrmpt Vkctor 117
DC-WBDM ;173 User Deûned Intempt Vcctor 118
DC-WBDM ;174 User Defineci Interrupt Véctor 119
DC.W BDM ;175 User Defined Intempt Vector 120
DC.W BDM ;176 User Defincd Intemipt Véctor 121
DC-WBDM ;177 User Defincd Intcmrpt Vector 122
DC-WBDM ;17%User Denned Intempt Vector 123
DC-WBDM ;179 User Defined Intempt Vector 124
DC.W BDM ;180 User Defincd Intempt Vector 125
DC-WBDM ;18L User Defined Intempt Vector 126
JX,W BDM ;182 User Defined htempt Vector 127
DC,W BDM ;183 User Defined Intempt Vitor 128
DC-WBDM ;184 User Defined htempt Vector 129
DC-WBDM ;185 User Defined Intempt Vitor 130
DC-WBDM ;186 User Defined Intemipt Vector 131
DC.W BDM ;183 User Detined Intempt Vector 132
JX-WBDM ;188 User Defmed Intempt Vector 133
DC.W BDM ;189 User Defined Intempt Vector 134
DC.W BDM ;190 User Defined Intempt Vector 135
DC.W BDM ;191 User Defined Intempt Vector 136
DC-WBDM ;192 User Defined Intemipt Vector 137
DC.W BDM ;193 User Defined Intempt Vector 138
DC-WBDM ;194 User Defined htempt Vector 139
DC.W BDM ;195 User Defined Intempt Vector 140
DC-W BDM ;196 User Defined Intempt Vector 141
DC-WBDM ;197 User Defined Intempt Vector 142
DC.W BDM ;198 User Defined Intempt Vector 143
DC.W BDM ;199 User Defined Intempt Vector 144
DC.W BDM ;200 User Defined htempt Vector 145
DC.W BDM 2 0 1 User Defined Intemps Vector 146
DC.W BDM ;202 User Definai Intemipt Vector 147
DCW BDM ;203 User Defined Iatemipt Vector 148
DC.W BDM ;204 User Defined Iatempt Vector 149
DC.W BDM ;205 User Defined Intempt Vector 150
DC.W BDM ;206 User Defined htempt Véctor 151
DC.W BDM ;207 User Defined Intempt Véctor 152
DC.W BDM ;208 User DefinedIntempt Vector 153
DC-WBDM ;209 User Defined Intempt Vector 154
DC.W BDM ;210 User Defined Intempt Vector 155
DC.W BDM ;211 User Defined Intempt Vector 156
DC-W%DM ;212 User Defincd htemipt Vector 157
DC.W BDM ;213 User Defined Intempt Vector 158
DC-WBDM 214 User Defincd ùitempt Véctor 159
DC-WBDM ;215 User Dcfined intempt Véctor 160
DC.W BDM ;216 User Defineci Intempt Véctor 161
DC-WBDM ;217 User Defined Intempt V'tor 162
DC.W BDM ;218 User Defined Iatempt Vector 163
DC.W BDM ;219 User Defincd Intempt Vector 164
DC.W BDM 220 User Defined Intempt V i f 165
DC.W BDM 221 User Defincd htempt Vector 166
DC.W BDM 222 User Dehed Intemipt Vector 167
DC.W BDM 223 User Defined Intempt Vector 168
DC.W BDM ;224 User Defincd Intempt Vector 169
DC-WBDM 225 User Defined Intempt Vector 170
DC.W BDM 226 User Defined htempt Victor 171
Appendix C: Controller Source Code

DC-WBDM -327 User Defineci Intcmipt Vèctor 172


DC-W BDM ;228 User Defined Intemipt Vector 173
DC.W BDM ;229 User Defincd Intcrmpt Vcctor 174
DC.W BDM $230 User Defincd fntempt Vitor 175
DC.W BDM ;23 1 User Defined Intemipt Vitor 176
DC-W BDM ;232 User Defined Intempt Vitor 177
DC.W BDM 233 User Defined Internipt Vitor 178
DC-W BDM ;234 User Dched Intempt Vitor 179
DC.W BDM ;235 User Defiaed Intempt Véctor 180
DC.W BDM ;236 User Defincd Iatemipt Vitar 181
DCW BDM ;237 User Detined Intemipt Vector 182
DC,W BDM ;238 User Defineci Intempt Vector 183
DC-W BDM ;239 User Detined fntemipt Vector 184
DCW BDM 240 User Defined Intemipt Vector 185
DC.W BDM ;24 1 User Defined Iatempt Vector 186
DC.W BDM ;242 User Defined Intcmpt Vector 187
DC-WBDM $243 User Defined Intempt Vector 188
DC.W BDM 344 User Defined Interrupt Vector 189
DC-WBDM 345 User Defined Intempt Vector 190
DC-WBDM ;246 User Defined Intempt Vitor 191
DC-WBDM ;247 User Defined Interrupt Vector 192
DC-W BDM ;248 User Defined intermpt Vector 193
DC.W BDM 249 User Defincd interrupt Vector 194
DC.W BDM ;250 User Defined Intemipt Vector 195
DC-W BDM ;251 User Defined Interrupt Vector 1%
DC-W BDM ;232 User Defined Xntemipt Vector 197
DC-W BDM ;2!53 User Defined Intempt Vector 198
DC.W BDM ;254 User Defined Interrupt Vector 199
DC-W BDM ;255 User Defined Intempt Vector 200
* This is the end of the otg00008.asm file.
Appendix D: PC Logger Source Code

This appendix contains the source code used for the PC logging program. This

program is designed to nui on a laptop computer, and communicate with the

MC68HC16EVB or the tractor cab controller that was built for this research. Data fiom
the controller was displayed on the screen as liws proportionai in length to the signal

received. This proved to be very helpful while field testing, where no representation of the

control actions was available using the LCD-only equipped controller. It was written in

Borland Turbo C, and nins under DOS using the DOS graphic commands available under

Turbo C. Although the logger program interface could have been improved and extra

features easily added if it was written in Visual C for Windows. the program was wrîtten

for DOS in order to maximize portability and minimize incompatibility problerns. It was

designed to nin on a laptop PC with or without a hard disk, many of which have

monochrome screens and do not run MS Windows.

The controller data logged hcluded the enor from the set point, the change in

error, and the fuay decision output. ND hexadecimal values from the sensors was dso
logged. This data, fkom the front and rear sensors, came directly fkom the registers for the

A/D converters.
Appendix D: PC Logger Source Code

Source Code: LOGGER4.C


/* DAX4TEST.C DIqlay and store the seaur emx, change in emr, and */
/* hiny deasion ou u t T a the u x t formatangr /
/* d a second hi*^ ~ o o pw SIARI" d m d t keep getting sent */

unsigned char in, *filein, mip;


unsjgned int '%-out;
int i~,outfile,wating;

int regster in, status;


FILE..outale, *filestor;
jnt xtitle ytitle;
&ter, mode, COMl;
!%kit, top, &le, bottom;
xtitIe = 130;
ytitle = JO;
printff.'Hit O for COM 1, 1 for COM2: ");
scanf %c,&COM1);

if ((filein = (unsigned char *)malloc(l28*sizeof(unsigned char))) =NULL )


I
memory: malloc failed-W');

/*********OPEN OUTPUT FILE, FOR SA= DATA AT END OF GRAPHICAL ROUTINE4***/


if ( outfile = fopen("fûzdataout'*,"wt9*)) /* open WFïA.OUT */
-
- h l
r
fprintf(s&m, "Cannot open output fde.W);
1
bioscom(0, SElTiNGS, COM1); /* O = initialize the corn port */
if ((fopen("fïlestor","w"))=NULL) If open output file */
I
Appendix D: PC Logget Source Code

Fat sensor Dsk Se


on tht boatom of the */
to the lcf< of the
to the ngbt of the paph */

/* set cobut to yellow */


P draw in the new Iine 274 =4Ol-l27 */
/* center for no change in e-mr*/
P center for stable hydtaulic output */
P max for sensor position */
P max for sensor posjtjon */
P half for sensor posruon */
P M f for sensor position */
r**lt***t**tt*+rt*/
/* initialuc memory location */
/* stact the main mutine */
/* clear hics t r i p Ba
' bioscom(1. START. COM / send s%&ansmit(~F)toHC16 */
delay(1);

' statu = biorcom(3.0. COMl); l* get scatus of corn port */


deiayQ;
/ eep checkin for it-sencihg S'CGRT a ain causes overflow in HC16*/
if(stanis
t & DATA-&Y) Y wiîh *f
P A N ~ D ~ A - R E A D ($8)
1
in = bioscpm(2.0. COMI) ); /* get data h m r e c e i v e p
hem\0{; ln; f* assign value of "in*' to loc i of em
:;
delay 1
bioscom(1, CONTïNUE, COM 1); /* send rcv ack ($E)to HC16 */
delay(1);
for(i= 1;i<lO;i=i)
C

delay( 1); /* delay 1 millisecond */


if(status & DATA-READY) P AM) DMA-READY ($8) with */
/* status-see if its "Rcady" */
Liay !)-
g. = kiokom(2. O, COM!)); /* get datg h m pni*/
lein[i] = in* /* as= vaIue of "in" to loc 1 of filein */
bioscom(1. ~oNTINUE,&ML); /* send rcv ack ($E)to HC16 */
i++;
1
1
1
/* incremcnt mcmory location index */
j=l;
1 /* m e t index to O */
/* and set gra bics trigger fia */
/* hi: is usecf no! i. nnce i d a t start */
if (lcbhito) /* if a key ISlut on the keyboatd *I
&( (in = getcho) ='klB') /* set in to key hi&ifitss-ESC.it*s
( P tune to sJop program exa"non angi c d * /
closc&rap#~ /* disenable the ~ I C Smucine */
fclose ou 6); r c ! the file */
1
nwb; /* exit program execution */
bioscom(1. in. COMI); I* if it yasu:t ESC. send the char */
/* out on the senal h e (ISonly */
= 1)
for(i=O;i<lO;i+=2) /* exchange the data in adjacent */
Apptndix D: PC Logger S o u e Code

-- P locations */

to fonn 16 bit */
1
P combine 8-bit
.P put b p m filem into words */
fileout = (unsignai rn *)filein; I* in Gleout */

1
setcolor(0); /* set coIow to black */
F(i= 1)
bne0efk 0, left, bottom); /* draw black tine over old one */

setcolor(l4); /* set colow to yeiiow Y


IineOeft, top, lefi, bottom); /* draw In the new line *I
1
f"r(i=û; id; i*)
Appendix E: Mathcad simulation

The simulations done in mathcad were prduced inVersion 4.0 at the outset of this
research. With the release of Version 6.4 this work was expanded by using the

capabilities to program in if-then loops and other iterations. Otheraise, it would have

been necessary to produce a l l code in C or CU.


y vector with dimension 1 row x 21 columns is the range of the crisp Inputs:
y : ( 100 90 80 70 60 50 40 30 20 10 O 10 20 30 40 50 60 70 80 90 I W )

z vector with dimension 21 rows x 1 cotumn is the riumber of tirnes vector y is repeated:

x 4s the 21 row x 21 column matrix,


made up of 23 rows of vector y
divided by 5 for this example:

nie input membership function ERROR


is made up of vector K:
Input: ERROR : = x

The 27 x 21 rnatrix x is the basis for the


example functions in thls example.
ERROR 1s defined as n, whil8
CHANGE-IN-EFIROR is defineâ as
x transpose.:
Section A: ERROR Membership Function Parameter Definitions: lndicies for ERROR lnpul vectors:
NBM: 10 NSL: - IO 2% : 5 PSL: O PBL: 5 n 0,,20
N B R : 5 NSM: - 5 Z M : O PSM: 5 P B M : 10 m 0,,20
NSR:-O ZR:-5 PSR:-10
Definitions for the slopes for the symmetrical triangular rnembership funclions: I
I POS-BIG,SLOPE := 1
MG-BIG-SLOPE := PBM - PBL
NBM - NBR
I
I POS-SMALL-SLOP@ :=
NEO-SMALL-SLOPE := PSR - PSM
NSL- NSM

Calculation Loops for fuuifying crisp inputs in each membership tunctlon:

if ERROR,, ,-P.
if @RRORm,,sZR
1[(ZL- @RROR)~,,]ZE!RO~MBMB~SLOPE~ if ERROR,, ,,<ZM
I
[[(ZR -
O oihcrwisc
ERROR),,~]*Z~RO-MEMB-SLOP@] othcrwisc

10 aihcrwisc
Section 6: CHANGEJN-ERROR Membership Function Parameter Definilions, similar to ERROR in
shape:
CNBM : - IOCNSL 10 CZL : 5 CPSL : O CPBL : 5
CNBR :=- 5 CNSM : = - 5 CZM :=O CPSM : = 5 CPBM := 10
CNSR:=O CZR:=5CPSR:=IO
The inputsfor CHANGE-IN-ERROR are rnatrix x, but are transpose& CHG-ERROR : = xT

Definitions for the symmetrical triangular membership tunctions for CHANGE-IN-ERROR:


I 1
I CJ?BRO,MEMB,SLOPE := C-POS-BIG-SLOPE :=
C-WG-BIG-SLOPE := CZR - CZM CPBM - CPBL
CNBM - CNBR
1
1 C-POS-SMALL-SLOPI? ;=
C-NEG-SMALL-SLOPE := CPSM - CPSL
CNSL - CNSM
Catculation Loops for fuuityicig crisp inputs in each membership function:

othewise
if CHO-ERROR,, ,X N S L
if CHO-ERROR,,,SCNSR
1(CNSL - CHO-ERRoR,, ,. )~C-NEG-SMALL-SLOPEI
l
if CHO-ERROR,,,, $NSM
1(CHG-ERRoR~, ,- NSR) C-NE!O-SMALL-SLOPE~ ohemisc
O othewise
O othewise

if CHG-ERROR,, ,>CiIL
if CHO-ERROR,, , X Z R
( (CZL - CHO-ERROR,,, ,$ OC-ZERO-MEMB-SLOPE~ ,,
l
if CHO-ERROR,,, , SCZM

[[CZR - (cHo@RRoR,,,)]~!-Z@RO-M@MB-SLOPE] dhcmir


.O oihcrwisc
O uiherwisc
la-
:3
a a a a
g g g g
K a a a
W L U W L U
Section E: OUTPUT Singleton Function Oefinitions:

You might also like