diy robotics and sensors on the commodore computer

133
8/6/2019 DIY Robotics and Sensors on the Commodore Computer http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 1/133

Upload: cubemanpdx

Post on 08-Apr-2018

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 1/133

Page 2: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 2/133

:; , .• , j

DIY robo t ics n nd se nsors on the co mmodote compute t

prQcticQIprojects for control QpplicQtion

john billingsle y

Page 3: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 3/133

First published 1984 by: Sunshine Books <an imprint of Scot Pr ess Ltd .) 12-13 Little New port Street, Lond on WC2R 3LD

Copyright © John Billingsley, 1984

All ri ght s reserved. No part o j this publication may be reproduced, storedin a retr ieval syste m, or transmitted in any form or by any means, elec troni c, m echani ca l, photocopying, recording and/or otherwise, withoutthe prior wrill en permission o j the Publisher s.

Br itish Librar y Cata loguing in Publicat io n Da taBillingsley, John

DIY roboti cs and sensors on the Comm odore compute r.I . Robotics 2 . Commo dore computersI . Title629.8'92 TJ211

ISBN 0 946408 30 0

Cover design by Graphic Design Ltd. Illu stration by Stuart H ughes. Typeset and printed in England by Commerci al Colour Pr ess, London E7.

I I

\ .

Page 4: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 4/133

1

2

3

4

5

6

7

8

9

10

11

CONTENTS

Page

Getting Started 1

Signal Inputs 7

Graphic Design with a Joystick 19

Logic In and Out 33

Analogue Input for the PET and 64 43

Stepper Motors and Their Use 55

A Simple Turtle 69

Interfacing a Robot 81

Analogue Output and Position Servos 99

Simple Robot Vision 115

Whatever Next? 123

iii

Page 5: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 5/133

Contents in detail

CHAPTER IGetting Started

Basic equipment, construction methods, a simple power supp ly.

CHAPTER 2 Signal Input s Using the analogue port , contro l knob input s and a simple joystick, a light-pen with a music program.

CHAPTER 3Graphic De sign with a Joystick

Graphics and sprites, se tting up graphics mode, shape filler , joy stickroutine, sprite editor.

CHAPTER 4 Logic In and Out

What's what on the user port, address decoding , data direction regis

ters, a random mains light sw itch .

CHAPTER 5 Analogue Input for the PE T and 64

Usin g t he u se r port to encode a joystick with BAS I C and machine-code so ftware, acir cuit for more precise analogue input for lab ora tory in st rumentation.

CHAPTER 6Stepper Motor s and Their Use

Makin g a simple tutorial motor, circuit for driving a stepper.

CHAPTER 7A Simple Turtle

Mechanical design, control strategies and software.

v

Page 6: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 6/133

DI Y Robotics and Sensors Of! the Commodore Compuler

CHAPTER 8Interf ac in g a Robot

Buildin g the robot language, teach mode , robot anatomy, six-ax is co n trol c ir c uit.

CHAPTER 9Analogue Output and Position ServosFeedback and st ability , circuits, analogue output from CB2 (PET only),interrupts, radio-control servos.

CHAPTER 10

Simple Robot VisionAdding a vision syste m to a robot, two vision strategies. ra ster scan

to scree n, edge-fo llowin g s trate gy_

CHAPTER 11

Whatever Nex t? Robot evo luti on , intelligence, robot ping-pong contest.

vi

Page 7: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 7/133

CHAPTER 1Getting Started

As the proud possessor of a Commodore microcomputer, you have moreco mputing power at your disposal than served the whole of CambridgeUniversity in 1953. You have no doubt p layed endless games, written programs of your own and explored many of the mysteries of the machineitself. Now wha t?

Until now, your machine has been dependent on keyed inputs for itsperformance - numbers on whicb to perform ca lculations or keystrokesto cont rol games manoeuvres. Why not now let it get its own data? Wb ynot add a muscle or two in the form of motors and relays, so that it canrespond to the outside world? A new world of possibilities opens up, starting with turtles and robots, ending only at the bounds of imagination .

The simplest sensor channe l uses one of the analogue-to-digital conver

ter ports of tbe 64. Even on the PET, however, it is possible to measure aninput voltage with no more than a resistor, a capacitor and the use of onebit of tbe user port - plus some cunning machine -code. Switches aresimple to sense, and solid-state relays are little problem. Only when youwant a variab le output voltage do you have t o consider adding more than aresistor or two - and even here it is possible to 'cheat' and obtain 256output levels with two more resistors and another capacitor.

A lot ca n be achieved without a very deep technical knowledge of

computer architecture, although I hope that you will learn about the fun

damentals as you work through the book. As any new term is introduced itis put in quotes, and an attempt made to explain it. Now and again, quotesmay be used for a 'buzz-word', for which an explanation is not reallynecessary.

The first few chapters may seem very simple and obvious. Often,however, it is the most trivial point, such as 'which way up does theconnector go', wh ich will ca tch you in tbe back of the neck. The robot chapter mayseem rather spec ific to one brand of robot : in fact, it addresses the generalproblem of comma nding a multitude of cbannels through a limited u ser

port.As eac h chapter was written, the designs and programs were tried andtested, and for this [ am very gratefu l for the collaboration of my son,Richard, and of Timothy Dadd. Anything which ha s reached print shouldhave worked at least once! Good luck.

Page 8: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 8/133

DI Y RoboJics and Sensors on the Commodor e Computer

Basic eq uipmenlThe components required for the construction of interfaces an d syste msar e described in each chap ter . In addition you will need a small so ld eringiron an d some mult icore solder. Reliable soldering is a n ar t which can takeyears to perfect. On e essential is to ' tin' both wires to be joined by meltingfresh solder against each one separ ately. Never carry a blob of moltenso ld er on the iron - in just a few seconds it can form a crust which willdisguise a 'dry joint' an d cause hours of troubleshooting.

You will also need a test meter. Buy a simple moving -coil multi meter,no t a digital meter. You will be more in terested in the rough value of asignal, whether it is ground or logic high, rather than its value to threeplaces of decimals. Moreover, it is more convinc ing to see a needle move,requiring tens of microamps, than to see digits flicker wltich can be influenced by a small charge of static. The purpo se of the meter is to eliminateuncertainty when something unexpected is happening, and it is little help ifyou must first wonder if the meter is showing a true story.

Although an attempt has been made to detail th e components down tothe last piece of wire, some extra wire will certainly come in usefu l - ametre o r t wo o f eve ry co lour you ca n find. Single strand 0.61nm eq uipmentwire will probably be eas iest to use.

Construction methodsYou will note on flicking through the pages that there is no t a printedcircuit in sight. When you have developed an d proved a device, be it turtleor simple smoothing circuit, you may wish to cons truct a permanentvers ion of the circuitry, laid out with great neatness. Howe ver this book isno t concerned with knitting patterns. Instead it tries to establish the princip les of interfacing gadgetry to a computer with a minimum of fuss. Athree-dimensional rat's nest of components hanging on a connector str ip

may look untidy, but if carefully soldered the chances of error can beslight. Start with a lash-up which works, an d only then transfer it to a moreelegant form. Then when yo u find that the circuit no longer works, you willlook for dry joints, hair-line cracks in the printed circuit tracks, orwhiskers of cop per bridging track s which you thought yo u ha d cu t.

Power supply unitSome of th e la t er designs cal l fo r a power supply capable of driving smal lmoto rs . I t is inadvisable t o dra w more than 100 milliamps from th ecomputer, an d so you will have to use a separate sup ply.

Th e components co n sis t of a transformer with tw o 6V outputs, a diodebridge an d two reservoir capacitors. This will give outputs of + 7V an d- 7 V, which can alternat ively be used as a single 14V supply. You will also

2

..

Page 9: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 9/133

Chapter J Getting Started

need mains cab le, at least o ne and preferably three fu ses , three screw terminals or three ways of connector strip, and a suitable box to mount it all in.

A 50 VA transformer will give plenty of margin against over load; theRS207 - 245 should cost not much more than £5 .00. A suitable 4 amp diodebridge is the RS 262 - 113 costing a pound or so, whilst 2,200 microfaradl 6V RS 103-373 capacitors are about fifty pence each . For the applications here, there is no need to smooth the supplies, but a single-packagestabilizer can easi ly be added later. The mains supply should be fused at 0.5amp, and there shou ld preferably be 3 amp fuses in the outputs.

What about the Vic 20?The book is aimed principally at the Commodore 64 and the more recentPET series, and the programs are carefully detailed to take care of thediffer ences between these machines. Many of the programs will runequally well on the VIC 20, and also on the ancient 200 1PET. To list everyversion of the programs in full would make them tedious , but, by substituting numbers from the tables below, you should be ab le to ada pt the programs without too much trouble.

Terms such as 'port address' and 'data direction register' are dealt with

in some detai l in Chapter 4. For now, the important thing is to rememberthat this information is here , so that you can turn back to it when you needit.

User port address:

AJI PETs: 59471 : SE84F CBM 64: 56577: SOOOI VIC 20: 37136 : $9110

Data dire ction register:

All PETs: 59459: $E843 CBM64: 56579 : $0003 VIC2 0: 37138: $9112

Pointer s to 'start of BASIC' and 'start of variables':

PET 30x>,40xx,80xx: s.o.BASIC: 40, 41 : $28, $29 s.o.vars: 42, 4 3: $2A, $2BPET 2001: s.o.BASIC: 122,123: $7A, $78 S.O.vars: 124,125 : $7C, $7 0CBM64: s.o.B ASIC : 43, 4 4 : $28, $2C s.o.va r s : 45, 4 6 : $20, $2EVIC 20: s.o. DASIC: 43, 44:$2B, $2C s.o.va r s: 45 , 46 : $20, $2E

3

Page 10: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 10/133

DIY Robot ics and Sensors on (he Commodore Computer

bv .. bv'O ·5A +......

~ : ,a

>A~ < -

ml

'R,Sl.07-24-5 L,__ """"2,2.0g....F

~f ) 0 ~

- I v 0 " ../ v

0 " t-I't-v

sAf . < ~

Co"",,-ct <LS

o y o . ~

F igure 1.1 Simple power supply

4

Page 11: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 11/133

Ch.apter 1 Gelling Started

BASIC program area start s at:

All PET s: 1025 ~ S040 J CB M 64: 2049 ~ S080 J VJC20: 4097 ~ $ J O O J

IRQ interrupt vector:

PET 30xx,40xx.80xx: J44, 145 ~ $ 90, $ 91

PET2001: 537, 538 ~ $219, $21ACBM 64: 788, 789 ~ $ 3 1 4 , $315VJC20: 788, 789 ~ $ 3 1 4 , $3 15

Program listingsThe program listings given at the en d of most of the chapters in this bookdraw together all the lines and routines listed in the course of each chapter.

They are intended as a checklist, leaving out the REM stateme nts .

5

Page 12: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 12/133

CHAPTER 2Signal Inputs

The computer thrives on a diet of numbers, stored in memory as binarydi gits or 'bit s ', and manipulated by the proces sor to form results which arealso number s . Within the computer electrical signals are either close to 5V,repre senting a logic 'one', or are clos e to ground and represent 'zero'.Fr om combination s of such signals the numerical valu es are built up in thescale of two; one eight-bit byte can represent number s from 0 ro 255, twotaken rogether can be interpreted as numbers from 0 to 65535, or alternatively from - 3276 8 to + 32767.

The o ut sid e world is not oft en like that. Keys o n the keyboard d o takebinary value s , either 'pressed' or ' not pre ssed ' , but other quantities such asposition s of robot s, speeds of motors or voltage s on control knobs can varyco ntinuou sly over their range . Somehow these 'analogue' value s must beturn ed into numb ers, so that the computer can di gest them.

In thi s chapter, you will meet the interface already built into the Commodor e 64 which allows you to connect up to four analogue signals. Thesignal s are designed to take the form of variable resistances, but it i s not toodifficult to read voltages too. You can build a simple cable and connectorstrip, which will come in useful time and time again for trying ou t inputschemes with a minimum of effort; and you can add a joystick which willenable you to dri ve the graphics program of the n ext chapter. You will alsofind out h ow to add a 'light-pen' to your comput er, enabling you to selectan item from the sc reen simply by poin t ing at it.

Connectors for the analogue ports (64 only)The 64 is equipp ed with two connector s to be us ed with joysti cks and gamespaddl es . In addition to reading lo gic signals, each port ha s two analogueinput s to ser vice an analogue joysti ck , and a simple POKE command willswitch th e circuitry from r eading th e pin s of one connector to reading thos e

of th e other. One of the connectors al so has a light-pen conn ection, whichcertainly merit s later investigation.A good confidence-builder is the construction and use of a home-grown

joystick. Later, this can be regarded as a simple piece of test equipment totro ubl e-shoot analogue inputs in general. Ev en w itb a device a s simple as

7

Page 13: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 13/133

D ry Robotics and Sensors on the Commo dor e Compuler

th is, conta inin g only two pot en tiome ters, the cha nces of non-working arelegio n . The imp orta nt thing is to proceed step by step, elimin ati nguncertainty as you gO.

Fir st m a ke uP a connector to one of the games sockets, con trol port 1.You will need a 9-pin D -type male plug, such as Farnell 140 - 820 o r RS466 - 179, a 9-way (or more) length of 'c ho colate block' connector stripand enough wire to join them - eith er 30 em or so of ribbon cab le or anequivalen t assort ment of co loured wires. In thi s way, th e co nnections wi llbe brou ght to a co nve nient co nne c to r bes id e th e keyboard, so that yo u ca ntrouble-shoot hardware and software together .

I t is wo rt h 'unsc ram b ling' th e p in s, so that the sig nals on the co nnectorst rip a re in a se nsi ble order. The wiring order th en b ecomes:

Connector strip:Signal: PotX PotY + 5V ov l oyO Jo y J J oy2 Jo y3 But/LPen

Plug:Pin N a: 9 l 7 8 2 3 4 6

After wirin g th e connector strip , plug it in an d che ck it. Th e secr et ofsuccessf ul electro nic development is no t to trust anything. I f you are con

vinced that there is a s ignal at one e nd of a w ire, check th at it really appearsat the ot her - ot herwi se yo ur faith in the wire an d its so ldering ma y cos tyo u h ours of searc hing for a bug.

Fir st use a simple multimeter (6V D C range, - ve to the OV line) to c hecko ut the + 5V a nd OV con nect ion s. Also chec k J oyO, Joyl , Joy2 a nd Jo y3,whi ch wi ll be between 4 and 5V. The use of a simp le needle-and- sca le meterdoe s mu ch more to inspir e confidence than a flickering reading on a digitalmeter, espec iall y w hen in spec tin g s ignal s w hich ar e cha nging.

Now it is time to c heck th e analog ue input co nn ectio ns. Ente r the fo llowing program into th e mi cro:

10 PRINT PEEK( 5429 7), PEEK( 54298 )20 GOTO 10

a nd run it. The scree n sho uld fill with tw o co lumn s of values of 255 . Nowco nn ec t a wire to + 5V via a 100 ohm re sist o r , an d touch th e end o n to th eanalog ue inputs in turn . You will see th e appropr iat e co lumn of lhe scr eend isp lay a value close to zero as ea ch c ha nne l is tou ched - your conf idenceis growing.

Finally chec k o ut the (switch-type) joysti ck input bits JoyO to Joy3 , andthe 'Fi re-button' bi t Bu t/ LP en . Enter the program:

10 PRINTPEEK(56321) AND 3 120 GOTO 10

8

Page 14: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 14/133

Ch apter 2 Signol Inputs

_ - - : r o y 3_ - : r o y 2

"Pot y =:1 I r f : ~ : ; d

~ - - 6 [ )'Pot X~ - f - r - E 1 > u t l L ~

Ov +5v /'

0 e @ 6e<1D@e9

Potx t6v 30)0 :Jer2 'But/LPen..

1'oty Ov '307' :roy) ·

Figure 2.1 Analogue / ga me s port con nection s

9

Page 15: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 15/133

DI Y Robotics alld Sensors on the Commodore Computer

Remove the test wire from + 5V and connect it instead to OV (leaving outthe resistor). Whil e the program is running , touch the wire to each of theJoy pin s and the But pin in turn. The value shown on the screen should

change from its usual value of 31 to 30,29,27,23 and 15 respectively. Inother words, each bit will read' I ' until it i s connected to ground.

How does the analogue input work?The principle of operation is very similar to the PE T input which will bedescribed in Chapter 5, but in the 64 the 'SID' sound chip doe s all the hardwork. I t has two input bits designed to read two analogue pad dles, and the64 has a separate sw itch to change over the connections from one pair of

paddles to another. Each input channel works as follows:

The input bit is first connected to ground by the chip, discharging a capacitor. The capacitor is then allowed to charge up through the p ~ d d l e' s variable resistor, whilst the chip counts the time taken for the capacitor voltageto reach the trigger level. This count value is then transferred into anotherregister inside the chip where it can be read with a simple PEEK. At switchon, port I should be automatically selected. To make sure, you can

POKE 56322,PEEK(56322) OR 192

to set up the data direction register (see Chapter 4 for explanation) . Then

POKE 56320,64

to selectthe paddle connections on port 1. Ifinstead yo u want to select port2, then you must

POKE 56320, 128

- although this is not as straightforward as it seems. The chip tests theinput several tirruos per millisecond. Even so, if you change the switchwithin a program there should be a slight delay before the value is read. Thevalues of the X and Y conversions are given by:

X ~ PEEK(54297)Y ~ PEEK(54298)

The address which selects the sw itch position is also involved in reading theswitch-joystick bits. Unfortunately it is also used as part of the keyboardreading system. This mean s that some fifty times per second an 'interruptroutine' will come blitzing through whatever else is happening, and will

10

Page 16: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 16/133

Chapter 2 Sig na l Inputs

leave the sw itch pointing to port I even if yo u really want port 2. Forread ing po rt I on its own there should be no problem s in using BASIC , but ,if you want to r ead both ports (ie all four channels), you mu st write aroutine in mac hine co d e w hich inhibits interrupts fo r the vital moment.

You can now check ou t th e po rt 2 conn ectio ns by unplugging your testconnector f rom one port and plugging it into the other. Now the Joy bitswill appear at a different add ress, 56320. The test pr og ram is:

10 PRINT PEEK(S6320) AND 3120 GO TO 10

To tes t th e analogue signals, use the followin g program. Lin es 10 and 40

are simple two-instruction mach ine code pro grams . Th e instruction SEI isplant ed at 1024, w hich appears at the top le ft of the sc reen. This inhibitsinterrupts - wh ich co uld be fata l if not corrected in line 40 by C LI. Bothlines plantthe co de for a subroutine return at 1025, to bring contro l ba ck tothe BASIC program:

10 POKE 1024,7 *16+8 :POKEI025,6*16 :SYS 1024 :RE M SE I RTS20 POKE 56320, 12830 PRINT PEEK(54297),PEEK(54298)

40 POKE 1024,5*16+ 8: POKEI025,6 *16 :SY S 1024:REM C LI RTS50 GOTO 10

Constructing a joystickNow, how about the jo ystick. For this yo u will need two potentiometers ofvalue 500 kohms. RS 161 - 8 3 0 would be suitable, but a lmo st anythinggoes. Even th e res istance val ue is not particularly critical; a value which istoo low will restrict th e range of resultin g numbers, whilst if it is too hi ghIhe useful region will be bunched up at one e nd of the rotation. Start

simply . The potent iom eter co nsi sts of a resistive track, connec ted to theouter so lder tags. The middle solder tag is connecte d to the 'w iper', whichslides along the track as th e sh aft is rotated and picks of f a resist ance valuecorresponding to its posit ion . Conne ct one of the outer tags of onepotentiometer t o + SV. Co nnect the middle t ag to P otX, then enter andrun the first of the programs above. As you rotate th e s haft to and fro, youwill see the numbers in the first column vary from near 0 to 255.

They didn't? Then check t he voltage on the potentiometer wiper using

the multi meter. None there? Then take ou t the potentiometer and mea sureits resistance, and the resistan ce betwe en the wip er and each end as theknob is rotated. Lo oks OK? Then pu t it back and try again; check the valueof + SV. All looks OK, but still no changing numb ers? Then check ou tPot X again as above; go to bed; try again in the morning.

11

Page 17: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 17/133

Z

.UU~lll

UpSNA

Page 18: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 18/133

Chapter 2 Signal Inputs

Now co nnect o ne of the second potentiom eter outer tags also to + 5V, andits wiper to PotY. When the test program i s run , yo u should b e ab le toco ntr o l the numbers in both co lumn s. Your electronic problem s ar e at an

end, and you are faced with the task of combining the mecha nicalmovement s into that of ajoystick. One possibility is sketc hed in Fig ure 2.3 .

I f all else fails, a comme rcial joystick can be bo ught for under £10 .00 you might even prefer to buy an obsolete TV game and murder it to ob taina pair of joysticks.

So far, this chapter must have been most frustrating for owners of aPET. Even though the PET has no analo gue input ports, it is st ill possibleto attach a joystick - using a certain amount of sku lduggery as describedin Chapter 5. Before that ca n be done, it is necessary to understand the

machinations of the user port, and the intricacies of the Versatile InterfaceAdaptor or VIA .

Adding a light-penBefore we move on , remember that tempting light -pen con nection whichdoubled as port I ' s 'fire' button? What is a light-pen, and what can it d o?

Th e television display is, of course , built up from a s ingle spot whichscans across the picture 15,000 times per second, working from top to

boltom 50 times per second . I f a pen containing a phototransistor is heldagainst the screen, then as the spot passes beneath it, the phototransistorwill give a pulse of output current. From the timing of this pulse, it i sposs ible to work ou t the position on the scree n which is being selected.

With the right int e rf a ce, it should be possible to put a set of options onthe scree n - perhaps ' up ', 'down' 'left', 'r ight' for robot co mmand s

and to select an option merely b y pointing to the word on the sc reen with apen connected by a wire to the computer.

The 'official' light-pen interface costs £20.00 or so. Can you get away

with anythi ng simpler? A circuit consisting of one phototransistor OP500,tbree resis tor s and a n NPN transistor 2N3705 is a ll you need - total costunder £I.OO! I f you turn up the TV brightness, you can make do with justthe phototransistor and a single resistor.

The LP en connectio n leads to the VIC Video In terface Chip . This is anindustrious device which turns a collection of numbers in memory into anappropriate picture o n the scree n. Suppose t hat the first line of text toappea r o n the scree n is ' the quick brown fox'. The chip first look s at thememory locat ion to be represented at the sta rt of the line - here it holds the

code for th e letter ' t ' . From another part of memory it mu st now look upthe shape of the l etter ' t ' , or especially it mu st look up the pattern for thetopscan-line of the ' t ' . As this is being used to modulate the tube' s electronbeam, the chip picks up the code fo r 'h ' and looks up the pattern for its topline, and so on to the end of the row of letters . When the scan lin e is

13

Page 19: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 19/133

P

.USJA

Page 21: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 21/133

DI Y Roboficsand Sensors oil /h e Co mmodore Computer

com plete, the chip look s at the ' t ' a second tim e, now look ing up th e pattern for its second line, and so on until eight sca n lin es ha ve been output.Th e address of the letter being proce ssed is held in a sixteen-bit registerwit hin the c hip, and thi s is automatica lly in cre ment ed to follo w the tex tdown the page .

Up to thi s point, the description ofthe chip co uld fit th e VI C ch ip or theCRT contro ller chip used in 8000 series and 'Fat 40' PETs. Th e CRT controller also has a light -pen co nn ec tion, but it s connect ion is brough t out 10pin 21 of conn ector J4 via a 7404 inverter with a 1 kohm pu ll-u p. Thisco nnector is the memory-expansio n forest of pins at the righthand side o ft he computer - yo u wi ll have to be rather adventur ous to use it. Whene verthe LPen pin of the CRT controller cha nges from logic level 0 to I. theaddress of the character be ing display ed at that instant is snap ped by twoS-bit reg iste rs within the chi p. From their value, it is possible to work outwher e the char ac ter appeared on the screen, and hen ce react appropriately.The chip is one of tho se awkward ones which try to co nse rve addressingspace ( see C hapt er 4) b y hav ing to be prodded with the regi ster numb er atone address, a nd partin g with th e answer at a seco nd. Don ' t wo rr y t oo

much if th e fo llowing program seems to bemumbo jumbo; iI' s short and itwo rk s:

10 REM SIMPLE LIGHT -PEN DEMO FOR 8000 OR FA T40 PET20 REM FILL SC REEN WITH WHITE (GREEN)30 FOR I = 32768 TO 34768: POKE 1,160:NEX T40 AO = 32768 : REM OLD HIT

Here comes the mumbo j umbo:

50 CR = 14*16 -3 + 8*16-2 + 8*16:REM ADDRE SS OF CHIP IS $E880100 POKE C R, 17:A = PEEK(CR + I): REM READ R EG ISTE R 17110 POKE CR,16:A = PEEK(CR + 1)+256*A: REM R EG ISTER 16[20 B = A - 32768: REM B IS NOW CHARACTER NUMBER ON

SCREEN130 IFB < OOR B> 1999 THEN IOO:REM MISSED SCREEN ! (999 FOR

FAT40)

No w let's use the res ult to mo ve a screen blob:

140 POK E AO, 160 : REM RUB OU T OLD B LOB150 POKE A,32: REM PLAN T N EW BLACK BLOB160 A O = A : RE M REMEMBER WHER E IT IS170 GOTO 100: REM AND DO [T AGAIN

16

Page 22: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 22/133

Chapter 2 Signal In puts

Now let' s ge t back to the 64 and its VIC ch ip . Thi s chip is not con tent withhandling colours, bit-mapped g raphics and eight sprites, it also insists ongiving the light- pen hit accurate to the nearest pair of pixels. There are nowtwo registers at 53267 and 53268 which hold the X and Y values of theli ght -pen hit. The Y -va lue gives the exact scan- line number , whilst theX-value points to a pair of pixel positions. Since these are measured fromthe edge of the picture, behind the border, it is necessary to subtract 46from eac h number to hit the display area. These values are stro bed justonce per frame sca n, so you should n't move too fast.

Th e following program is just a rough-and-ready indication that thetechnique works. It doesn't take much imagination to extend it to drawinglines just two pixels thick, but for now let's be content with moving blobs.

10 REM SIMPLE LIGHT-PEN DEMO FOR COMMODORE 6420 REM FILL SCREEN WITH WHITE30 SC= 1024:CO=55296: REM SCREEN START, COLOUR40 FOR 1=0 TO 999 : POKE 1+ SC,I6050 POKE I+ CO,I :NEXT: REM CO LOUR WHITE

60 AO = O:REMOLDHIT70 PX = 53267:PY = 53268: REM ADDRESSES OF HIT REGISTERS

100 X = PEEK(PX) - 46:Y = PEEK (PY) - 46:REM READ REGISTERS

110 A = INT(X /4)+

40*INT(Y/8): REMWHICH

CHARACTER?120 IF A< 0 OR A> 999 THEN 100: REM MISSED TH E SCREEN!

Now let's plant a red blob:

140 POKECO+AO,I: REM RUB OUT OLD BLOB - MAKEWHITE

150 POKECO+A,2: REM PLANT NEW RED BLOB160 AO=A: REM REMEMBER WHERE IT IS170 GOTO 100: REM AND DO IT AGAIN

This is a good simple program, however Tim and Richard felt that youwould like something more entertainin g. Below i s their answer t o theStylophone. Doh, Re, Mi, etc., will appear on the screen, with a col umn of blobsto the left. Point the light-pen at a note, and that note wiD start to play; thecolumn to the left gives blessed silence. Have pity on the neighbours.

Light-pen Demo

10 0 INPUT"SPEED t 100) ISH"; SP

11 0 GOTOIOOOO200 N=INT( tPEEKtVY)-26) /16 )210 IF N<O OR PEEKtVX) < 8 0 THEN N=0:GOT0200220 POKEPH,PHtN):POKEPL,PLtN)230 POKEW,O:POKEW,WW

17

Page 23: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 23/133

Dr y Robofics and Sensors on the Commodo re Com pu ter

240 FOR 1= 1 TO 2000 STEP SP:NEX T 250 GOTO 200 10000 RV$=CHR$(lB):RO$=CHRS(146):REM REVERSE,OFF 10010 NNS="DO RE MIFA SO LA TIDO" 10020 PRINTCHR$(147)CHRS(5); 10030 FOR 1=1 TO 13: PRINT : PRINT" "RVS"

,,1 0 0 4 0 P R I N T " "RVS" lORDS" ,10050 IFI=20RI=40RI=70RI=90RI = 11THENPRINT" " ,

,,- ,0060 PRINTRVS" " M I D $ ( N N S , 2 * I - l , 2 ) ; "10070 NEXT

10100 DIMPH(16) ,PL(16)10110 P=2 A (1 / 12 ) :PO=400010120 FOR 1=1 TO 13

101 3 0 PH(I )= INT(PO/256) :PL( I )=PO AND 25510140 PO=PO*P:NEXT10200 POKE 54296,15:POKE54277,7:W=54276:WW = 1710210 PH=54273:PL=5427210220 VX=13*16 A 3+19:VY=VX+l10230 PO KE532B1,O:GOT0200

18

Page 24: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 24/133

CHAPTER 3Graphic Design with a Joystick

I am married to a graphic designer. One day my wife, Ro s, want ed to findout more about co mputer graphi cs, and to design some screen displays.

Graphic su broutines are all bu t non-existent on the Commodore, and,

although the64 has some powerful hardware graphics capabilities, the taskof writin g a full co lour grap hics packa ge for it is not a trivial one. Unlessyou buy (or write) a machine- co de packa ge, th e routine s will be s low toexecute. Mu ch of the mer it of the pro gram developed here is in the clues itgives you fo r wri ti ng your own routine s . All the same , I hope yo u w ill agreethat it provides a use ful set of fun ctions, an d is fun to drive. I t makes agood excuse to use a joystick , and eve n includes a tou ch of di gital filteringto remove th e joystick 's jitter. Alt ernativ ely, you ca n drive it from theti ght-pe n developed in the previou s chapter. Unfor tunately graphics on

the PET are only supported by an add-on boa rd , a nd so this chap ter isdevoted to the 64.

Graphics and spritesThe VIC chip which controls the 64's display ca n ope r ate in normal mode,displaying 1000 locations of memory, in the form of characters looked upin a table of shape s. Alt ernat ive ly, it can displ ay a 320 by 200 bit-imagepiclur e of 4000 memory locatio ns. In both case s, a se parate area of 1000bytes of memory hold s the foreground an d backgro und co lo ur specificat ion of each 'characte rs-wonh' of disp lay, organis ed as 40 cells acros sby 25 deep.

In add ition, the chip will handle eig ht 's prite s ' . T hese are bit-imageshapes which can be sup erimposed on text or grap hics, and can be movedbodily by changing o nly two locations each . Each sprite is defined by asequence of 63 memory locatio ns, giving a re solution of 24 bits across by 21down - the sprites are link ed to the shape d efinitions by pointers, andseveral or a ll of the spri tes ca n be linked to the same shape. Th e followingprog ram is a bout as simp le as yo u can get, and allow s yo u to move a sprit earo und tb e scree n by mean s of the joy stic k. I t will estab lish a rew principles, but need s a lot of embellishment to m ake it m o re interestin g.

19

Page 25: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 25/133

DI Y RoboJia on d Sensors on th e Commodore Computer

10 VV=13*16 "3: REM VIC CHIP [S AT $000020 POKE VV+21,1: REM TURN ON SPR ITE 0 (BIT 0)30 POKE 2040,13: REM POINT SPRITE 0 TO

ADDRESS 64*1340 POKE VY , I60 : REMXOF SP RITEO50 POKE VV + 1,100: REM Y OF SPRITE 060 FOR I = 832 TO 832+62 : POKE I ,255:NEXT70 REM FILL SHAPE WITH SOLID COLOUR

I f you enter and run the program so far, you will see the sprite appear andfill up with colou r. Now you will want to move it around the scree n:

100 POKE VV,PEEK(54297): REM JOY ST ICK X110 POKE VV + 1,PEEK(54298): REM JOYSTICK Y120 GOTO 100

A nd th at 's it! Other sprites are turned on by the rema in ing bits of VV + 21,and the shape pointer fo r sprite N is at 2040 + N . The co lour o f sprite N ischanged by poking VV + 39 + N with a numb er from 0 to 15; whilst th e Xand Y va lues are at VV + 2*N and VV + 2*N + 1 - with bit N of VV + 16giving a boost of 256 to the X co ordinate. Bits N of VV + 23 and VV + 29will double the wid th and height of each co rr espond ing sprite.

To design a sprite 'can be a tediou s ta sk. At th e e nd of th e chap ter a 's priteeditor' is given which enab les you to dri ve a pixel cursor arou nd the sprite ,sett ing and clearing b its at will.

No w let us attac k th e mu ch more dauntin g ta sk of building a g rap hicspackage to sim pli fy th e design of a co mplete scr eenful of co loured linesand sh apes .

Program specificationThe functions wh ich the program pro vides are Point , Line and Ar ea,whilst ink and pap er colo ur can be set by pressing C . As th e joystick ismoved, a fle eting dot moves ab out the screen. Pre ssing P mark s a fixed doton to the screen, and also memori ses the coordinates of the point.

If th e jo ystick i s mo ved and L is pres sed , a line i s dr aw n fro m the lastrecorded point. Another move and another L dr aws a second line from theend of the first , and so on. I f the L key i s held down, line seg me nts wil l bedrawn ill swift succession, forming a smoot h curve drawn by the joystickmo ve m e nt.

Areas are filled by shadi ng them horizontally. A sets the bo undary in thesame way that L draws a lin e. I f a boundary is already se t at that ve rti calcoo rdin a te, th en the line between th e old boundary and the new is filled inwit h colour. If you bold down A and tra ce o ut a 'U' with the joystick, you

20

Page 26: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 26/133

Chapter 3 Graphic Design with a Joysfick

will see the downstroke drawn as a curve on the screen. 00 the up stroke,the cur ve will 'fi ll up ' like a wineglass. Whenever P is pressed, the oldboundary will be forgotten.

To avoid accidental ly erasing this work of art, Ole 'clear' command is anexclamation mark, requiring you to hold 'shift' at the same time.

Pressing C wi ll return the screen to normal mode, a nd you will be askedfor the new foreground and background co lours. After you have enteredthem, the screen will change back to graphics mode, with your pictureintact.

Setting up graphics mode

Specifying the program requirements is a good start, but how do we obtain

high-resoluti on graph ics mode on the 64? (I am af raid that PET owners arecompletely lef t out ohhis chapter.) We must send a few bytes of data to theVIC chip which contro ls the display, and we must also change a byte inCIA2. The next chapter atte mpts to explain so me of the magic, but for nowjust take it on trust.

You may prefer to skip this paragraph the first time you read the book, an d

return to it later.Bit image mode is set by poking register 17 of the VIC chip w ith a va lue

which is ORed wit.h 32. CIA2 at address $DDOOsets the 'bank address' forthe VIC chip's display and colour memory, using the least significa nt bits.Theseare inverted, so that if their va lue is 3, the bank starts at $0000 , 2 gives$4000, I gives $8000 and 0 gives $COOO.Register 24 of the VI C ch ip definesthe rest of the address with value 16' (colour offset) + (screen offset).These offsets are multiplied b y 1024 t o give the actual addition to theaddress. Thu s, by selecting bank I, an d by poking VIC register 24 withvalue 16'7 + 8, we define the screen map to run from $6000 to $7FFF andthe colou r map to run from $5COO to $5FFF. (Of cou rse this restricts the

RAM available for programs. The machine would alternatively work wellusing the 'RAM underneath the ROM', with screen at $EOOOand colour atSCOOO : select bank 3, and POKE register 24 to va lue 8. All is well as youwrite to the display, but, as soon as you want to PEEK it, you will see theROM instead . It's an easy problem to bypass in machine code, but cannotbe done in BASIC - hence the use of bank I. )

Now read on. Start building the program in testable modules. Enter thefollowing program an d run it. The 'h o usekeeping' is parked out of the wayat 10000onwards, whil st subroutines at 9000 and 9 100 respectively se t andreset graphics mode. I f all is weU, you wi ll be asked for 'colour, pattern'.Try 33 , 15 for a star t. The screen will flip into high-reso lution mode, an dthe colours will rapidly be set to black-and-white. The program will thennibble a pattern of strip es, taking quite a few seconds to cover the entire

21

Page 27: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 27/133

Dry Robotics an d Sensors of/the Commodore Computer

screen, finally flipping back to normal mode. I f you break the program,typing GOSUB 9100 might bring rescue - otherwise try RESTORE.

5 POKE 56,64:CLR: REM PROTECT GRAPHIC MEMORYAREA

10 GOTO 10000

10000 REM10020 SC=I*16384+8*1024: REM SCREEN STARTS BANK I,

SECTO R810025 CC=I*16384+7*1024: REM COLOUR MAP=BANK I ,

SECTOR 7

10030 VV = 13*4096:CI=VV + 13*256: REM VIDEO CHIP=$DOOO,CIA2=$DDOO10040 GF= VV + 17:CM= PEEK(GF):GM=CM OR 32

10045 REM GRAPHICS FLAG, CHAR. MODE, GRAPHICS MODE.10200 GOTO 100

100 INPUT"COLOUR , PATTERN";CL,CH110 GOSUB 9000: REM SET GRAPHICS MODE120 FOR I=CC TO CC+lOOO:POKE I,CL:NEXT :REM SET

COLOUR130 FOR I = SeTO SC + 8000:POKE I ,C H:NEXT:REM PATTERN140 GOSUB 9100: REM RESET TO CHARACTER MODE190 STOP

9000 POKE CI,PEEK(CI)AND(255 - I):REM SET BANK I9010 POKE VV +24,8+ 16*7:REM SCREEN SECTOR =8, COLOUR

=7 9020 POKE GF,GM:REM GRAPHICS MODE 9030

RETURN 9100 POKE CI ,PEE K(CI)OR 3:REM BANK 0 9110 POKE VV + 24,20:REM NORMAL SCREEN 9120 POKE GF,CM:REM CHARACTER MODE 9130 RETURN

As you will have guessed, the strange numbering will fit in with lateradditions.

Setting a pointThe arrangement of the screen display memory is not altogether straightforward, and it requires careful planning to translate an X, Y coordinate

22

Page 28: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 28/133

Chapter 3 Graphic Design with a Joystick

into the byte address an d pattern to oulput. The first eight bytes form therows of the first character po sitio n on the screen - they are displayed onebelow the other. The next byte is back at the top of the screen in the second

character position, and so on. At the end of the top text line are bytes 39*8to 39*8 + 7, followed by byte 40*8 at the top left of the second characterline.

First let us calcu late the character position on the sc reen . For eachincrease of 8 in Y (measured downward s) we will move down on e row of 40chara cte rs, ie we start with LL *INT(Y /8), where LineLength has been setto 40. Next, for each increase of 8 in .X, we will advance one character,adding INT(X /8). The corresponding byte of the colour map may need tobe poked witb th e colour, and checking the character position against zero

and the maximum value of 999, tells u s if the point is off the screen. Le t usput the 'set a point' routine at 8500:

8500 CS= LL*INT(Y / 8)+INT(X / 8): REM C HARA C TERPOSITION8510 IF CS< 0 OR CS > MX THEN RETURN : REM MISSED THESCREEN

Now the byte addr ess is found by adding 8*CS plus (Y AN D 7) to the sc reenstart address SC to give:

8520 SS=SC+8*CS+(Y AND 7)

Now we must poke the byte at SS with a value whi ch is ORed with the bit tobe planted. Thi s bit is in turn given by bit (X AND 7), which can be ca lculated as 2-(7 - (X AN D 7». To save calculation time, the values are held inan array BP(7), to give:

8530 POKE SS,PEEK(SS) OR BP(X AND 7)

Check to see if the character being written to is a new one, and, if so, set thecolour:

8540 IF CS < > OS THEN POKE CC + CS,CL:OS = CS

then

8550 RETURN

We still have some housekeeping to attend to:

10000 Y =O:X=O:CS=O:SS=O:DIM BP(7)JOOIO LL =4O:MX=999

23

Page 29: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 29/133

DIY Robotics and Sensors 011 the Commodo re Computer

and

10050 FOR I = OTO 7:BP(I) = 2'(7 - I):NEXT

You can tr yo ut the routin e up to thi s point by altering line 140 to :

140 FORA = OT06.3STEP.OI

with

ISO X = INT(IOO+ 90'COS(A»:Y = INT(lOO+ 90'SIN(A»160 GOSUB 8500:NEXT170 GOSUB 9100 :REM SET NORMAL SCREEN100 CL = 33:CH = 0

and afte r the sc reen is cleared, a circle should app ear.

PloUing straight linesAn important part of any graph ics package i s the ability to dra w anoblique strai ght line from XH,YH to XT ,YT (H ere to Th ere) . We willco m e across si milar routines later. when we program r obo ts to moveobliquely. Let us put this ro utine at 8000.

8000 DX = XT - XH :DY=YT-YH: REM CALCULATE SIZE OFMOVE

8010 IF ABS(DY» ABS(DX) THEN 8100: REM Y MOVE IS THEGREATER

8020 IF ABS(DX) < I THEN RETURN: REM NO LINE , GOHOME

8030 Y =YH:RA= DY/ABS(DX): REM SLOPE OF LINE8040 FOR X=XH TO XT STEP SGN(DX ): REM FROM HERE TO

THERE8050 GOSUB 8500:Y = Y + RA:NEXT8060 XH=XT:YH=YT:RETURN: REM HERE IS NOW

THERE

8100 IF ABS(DY) < I THEN RETURN : REM NO LINE8110 X = XH:RA=DX/A BS (DY)8 120 FOR Y = YHTOYTSTEPSIGN(Dy)8130 GO SUB 8500:X = X + RA:NEXT8140 XH=XT :YH = YT:RETURN

24

Page 30: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 30/133

Chapter 3 Graphic Design with a Joystick

To try out this part, cha nge lines 140 to 160 to:

140 XH= 190:YH = 100:FOR A=OTO 50 STEP 2.2

150 XT = INT(loo + 9O·COS(A)):YT = INT(I 00 + 9O·SIN(A))160 GOSUB 8000:NEXT

The shape filler

We need to be able to fill aline with colour. Let us pu t a subroutine at 9500,ca lled after sett ing var iables X and Y. I f tbe shape memory SH(Y) is set,then (he line will be filled from SH(Y) to X. I f not, indi cated by SH(Y) =- I, then SH(y) is set equal to X and the program returns.

Extra housekeeping is needed in the form of:10060 M8 = 255:XM=319:YM = I99:SH=0: REM MAX X,Y SHAPE

FLAG10070 JX = 54297:JY = 54298:REM ANALOGUE ADDRESSES (FOR

LATER ) 10080 DIM SH(200),FL(7),FR(7):REM SHA PE , ROWS OF BITS 10090 FOR I =0 TO 7:FL(I) =2·BP(I) - 1:FR(I) = BP(I) - I :NEXT

and the routine become s:

8600 IF Y< 0 OR Y > YM OR X< 0 OR X > XM THEN RETURN8610 XI =X:X2=SH(Y):SH(Y)= X:REM SET SHAPE TO NEW

POINT8620 IF X2 < OTHEN 85OO:REM SHAPE WAS NOT SET, JUST DRAW

EDGE 8630 IFXI > X2 THEN XI =X2:X2=X:REMSWAP 8640 CS= LVINT (Y/S)+INT(Xl/8):POKE CC+ CS,CL:REM

COLOUR 8650 SS

= SC+S·CS+(Y AND7)

8660 I = (INT(X2 / S) - INT(XI / S»·S:REM 1=0 SAME BYTE, S IF NEIG HBR S

8670 IF I = 0 THEN POKE SS,PEEK(SS)OR(FL(XIAND7) - FR(X2 AND7)):RETURN

86S0 POKE SS,PEEK(SS)OR FL(XI AND 7»:REM LH END OF LINE8690 POKE SS + I,PEEK(SS + I)OR (MS - FR(X2 AND 7)):REM RH

END8700 POKE CC + CS + I18,CL8710 IF I = S THEN RETURN:REM NO MIDDL E TO FILL8720 XI =SS+S:X2=SS + I -S :CS=CC+ CS+ I :FOR SS=XI TO X2

STEP 8 8730 POKE SS,M8:POKE CS,CL:CS = CS + 1

8740 NEXT:RETURN

25

Page 31: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 31/133

DI Y Robotics and Se nsors on the Commodore Computer

We are also going to need a routine to reset the shape array to - I, and toreset a flag:

9600 IF SH> OTHEN FOR I =OTO YM:SH(I) = - I :NEXT9610 SH = O:RETURN

Now for the routine which calls the line filler. This looks similar to the linedrawing routine, but operates just once for each value of Y:

8200 OX=XT-XH:X=XH8210 IF ABS(YT - YH)< I THEN XH = XT:X = XT:Y = YH:GOSUB

8600: RETURN

8220 R = O X I ABS(yT - YH)8230 FOR Y = YH TO YT STEP SGN(YT - YH)8240 GOSUB8600:X=X+R:NEXT8250 XH = XT:YH=YT:RETURN

Change 160 to

160 GOSUB 8200: NEXT

to tryout the new section.

The joystick routineSo far, we have developed routines which can be called from within a program to produce graphics on the screen. How do we link them tomovements of the joystick? We need a joystick routine which wi ll read thetwo analogue values, and then uanslate them into movements on thescreen in the range 0 to 320 for X and 0 to 200 for Y. Since the analoguevalue is an integer in the range 0 to 255, we have the choice of losing resolutibn in the X direction, or losing the righthand fifth of the screen - thelatter seems the better bet. There must then be a dot shown in the selectedposition, which must be removed when the joystick is moved to a new

place. The dot will show up best ifit twinkles. This means that we must firstrestore the byte of screen memory at the o ld joystick position, rememberedin variable OB (old byte), and plant a new byte in the new position with theappropriate bit reversed in value. Then we return to go round again.

5000 POKE SJ,OB: REM PUT BACK OLD BYTE5010 XT= PEEK(JX) :REM READ ANALOGUES5020 YT = PEEK(JY)5030 CS = LL*INT(YT 1 8) + INT(XT 18 )

26

Page 32: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 32/133

Chapler 3 Graphic Design with a Joy s tick

5040 SJ = SC + g*CS + (YT AND 7):REM ADDRESS OF SCREENBYTE

5050 OB = PEEK(SJ)

5060 1= BP(XT AND 7):POKE SJ, (OBORI)-(OBAND I) : REM FLIPBIT

5070 RETURN

When you come to try the program, you will probably find that the selectedspot is subject to a ce rtain amount of jitter. I t is easy to indude digitalnitering in the program to reduce this. Cons id er first the simp le instruction:

X = PEEK(JX)

As soo n a s th e ana log ue value cha n ges, the va lue of X wi ll change to matchit . Now consider in s tead:

x = X + (PEEK(JX) - X)/2

If the PEEK val ue has been zero for a while, and suddenJy cha nges to 100,then the next value of X will be 0 +{100-0) /2=50 . The following

value will be 50 + (100 - 50)/2 = 75, and so on. Each time through theprogram the diffcrenct>betweenX and the PEEK value will halve, so thatXwill eventua lly catch up with PEEK, although the effect of sudden changeswill be smoothed out. Using a number bigger than 2 in the program line willgive more smoothing, but X will tak e longer to catch up with the PEEK.This smoothing sys tem is ca lled a 'low pa ss filter' . It gives the same effectthat wou ld be gained by putting a series re sistor and shunt capacitor intothe analogue circuit. If the program line is made:

x= X + (PEEK(JX) - X) / F

the value ofF can be chosen to give a variety of time-constants. The longerthe time -constant , the less effect jit ter noise will ha ve, bu t the slower will bethe response of the joystick.

Now, if filtering is desired, lines 5010 and 5020 can be replaced by

5010 XT = XT + (PEEK(JX) - XT)/F5020 YT = YT + (PEEK(JY) - YT) / F

The rest of the programNow let us deal with the remainder of the housekeeping. We m ust firstclear the screen and initialise the values of OB and SJ. Lif e will be easier ifwe move the clear-screen routine to 9700 from its ' try-out' position at 11 0:

27

Page 33: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 33/133

DIY Robotics an d Sf?nsors on the Commodo re Computer

9700 FOR 1= CC TO CC + 999:POKEI,CL:NEXT:REM.CLEARCOLOUR

97 10 FOR I = SC TO SC + 7999:POKEI,0:NEXT:REM CLEARDISPLAY

9720 FOR 1= SC TO SC + 3:POKEI,M8:NEXT9730 RETURN :REM SET TOP LEFT CHAR TO SHOW SET

COLOUR

We can now add:

10100 CL = 22:GOSUB 9OOO:GOSUB9700:REM WHITE ON BLUE10110 F=4:GOSUB SOIO:REMJOYSTICK SET-UP10120 GOTO 100

Now we are ready for the main loop of the pro gram.First read the joystick, showing its position as a dot:

100 GOSUB 5000

Next test for a key-press. I f none, loop via the j oyst ick test. Th e key-press

testis

a little unus\lal, becausewe

would like the user tobe

ableto

hold down a key to repeat an operation. For this type of command, automatic repeat can be a mena ce, and it is better to look at the key-code echo at locat ion 197; this will have value 64 if no key is pressed. I a key is held down, then GET B$ will give the string value of the key the first time and " " sub sequently. Thu s the following code sho uld do the trick:

110 GETB$

120 IF B$< > " " OR PEEK(l97) = 64 THEN A$ = B$

I f no key is pressed, go round the loop again:

130 IF A$ = " " THEN 100

Is the key a 'P '? If so , set the point, clear the shape (if set) and loop:

140 IF A$< > " P " THEN 170ISO OB = OB OR BP(XT AND 7):GOSUB 9600

160 XH=XT:YH=YT:A$= " ":GOTO 100

Is the com mand 'L '? If so , draw the line and loop:

170 IF A$= "L " THEN GOSUB 8000:GOTO 100

28

Page 34: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 34/133

Chapter 3 Graph ic Design with a Joystick

If the command i s ' Area' then call the area routin e, if it is ' J' then dearthesc ree n:

180 IF A$ = "A " THEN SH = I :GOSUB 8200:GOTOIOO 190 IF A$ = "J" T HEN GOSUB 9700:GOTO 100

Otherwise th e co mmand i s ee' - or it is not rec og nised. In either case,re ve rt to normal sc reen:

200 GOSUB 9100: IF A$< > "C " THEN 240 210 PRINT "FOREG ROUND COLOUR (0-15) , BACKGROUND":

INPU T I,C L

220 GOSU B 9000:CL=(CL+ 16*I)AND M8230 POKECC, CL :GOTOlOO:REM SHOW AT TOP LEFT

If not recog nised, print a mes sage and wait for anoth er key:

240 PRINT CHR$(147)"P - POINT L - LINE" 250 PRIN T " A - A R E A C-COLOUR" 260 PRIN T "! - CLEAR SCREEN" 27 0 GET A$: IF A$ = " " THEN 270

280 GOSUB 9OOO:A$= "":GOTOl00

Now you can Jet your artistic talents run wild. You will need a very steady hand to drive the joy stick when h olding down a key for continuous writing. The result s can be mo st impre ss ive - especiall y if you ar e married to a graphi c designer.

Graphics by Joystick

5 POK E 5 6 , 6 4 : C L R : R E M PROTECT GRAPHIC MEMORY AREA10 GOTO 10 0 0 01 (10 GOSUB 5 0 0 0110 GET B$120 I F B$ <> .... OR PEEKtKB)=KO THEN A$=B$130 I F A$= .... THEN 1 0014 0 I F A$ <> "P"THEN 1 7 0150 OB = OB OR B P t X T AND 7 ) : GOSUB 9 6 0 0160 XH= XT: YH=YT: A $ = " " : GOTO 1 0 0

170 I F A $ = " L " THEN GOSUB 8 0 0 0 : GOTO 100180 I F A $ = " A " THEN GOSUB 8 2 0 0 : GOTO 1 0 0190 I F A $ = " ' " THEN GOSUB 9 7 0 0 : GOTO 100200 GOSUB 9 1 0 0 : I F A$ < > " C " THEN 2 4 0210 PRINT "FOREGROUND COLOUR ( 0 - 1 5 ) , BAC KGR OUND"

29

Page 35: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 35/133

DI Y Robotics and Sensors on the Co mmod ore Com puter

215 INPUT I , CL220 GOSUB 9000 : CL=(CL+16*I)AND MB

230 POKE CC,CL: GOTO 100: REM SHOW AT TOP LEFT240 PRINT CHR$ (147) "P-POINT L-LINE"250 PRINT "A-AREA C-COLOUR"260 PRINT" !-CLEAR SCREEN"270 GETA$: IFA$="" THEN 270280 GOSUB 9000:A$ =" ":GOTO 1005000 POKE SJ,OB: REM PUT BACK OLD BYTE5010 XT=XT+(PEEK(JX)-XT)/F5020 YT=YT+(PEEK(JY)-YT)/F5030 CS =LL*INT(YT/B)+INT(XT/8)5040 SJ=SC+8*CS+(YT AND 7)5050 OB=PEEK(SJ)5060 I = BP (XT AND 7 > : POKE S J , (oB OR I ) - (oB AND I )5070 RETURN8000 DX =X T-XH: DY= YT-YH8010 IF ABS(DY) > ABS(DX) THEN 81008020 IF ABS(DX) < 1 THEN RETURNB030 Y=YH: RA=DY/ABS(DX)8040 FOR X=XH TO XT STEP SGN(DX)8050 GOSUB 8500 : Y=Y+RA: NEXT8060 XH=XT: YH=YT: RETURN

8100 IF ABS(DY) ( l THEN RETURN8110 X=X H: RA=DX / ABS(DY)8120 FOR Y=YH TO YT STEP SGN<DY)8130 GOSUB 8500: X=X+RA: NEXT8140 XH=XT: YH= YT: RETURN8200 DX=XT-XH:X = XH:XH=XT8210 IF YT=YH THEN X=XT:Y=YH: GOSUB 8600 : RETURN8220 R=DX / ABS(YT-YH)8230 FOR Y=YH TO YT STEP SGN(YT-YH)8240 GOSUB 8600 : X=X+R: NEXT

8250 XH=XT: YH= YT: RETURN8500 CS=LL*INT ( Y/8) + INT(X/8)8510 IF CS <O OR CS >MX THEN RETURN8520 SS=SC+8*CS+(Y AND 7)8530 POKE SS,PEEK(SS) OR BP(X AND 7)8540 IF CS <> OS THEN POKECC+CS,CL: OS=CS8550 RETURN8600 IF Y<O OR Y)YM OR X<O OR X>XM THEN RETURN8610 Xl=X: X2=S H(Y): SH(Y)=X8620 IF X2 <0 THEN 8500

8630 IF Xl ) X2 THEN Xl=X2:X2=X8640 CS=LL*INT(Y/8)+INT(X1/8):POKE CC+CS,CL8650 SS=SC+8*CS+(Y AND 7)8660 I= ( INT(X2 /8 ) - INT(X1 /8»*8 : IF 1=0 THEN 87508680 POKE SS,PEEK(SS)ORFL(Xl AND 7)8690 POKE SS+I,PEEK(SS+I)OR(M8-FR(X2 AND 7»

30

Page 36: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 36/133

Ch apte r 3 Graphic Design with a Joysti ck

8700 P OKE CC+CS+I / 8,CL87 10 IF 1=8 THEN RETURN

8 720 Xl =SS+8:X2=SS+I-8:CS=CC+CS+l

87 25 FORSS = XlTO X2

STEP 887 30 PO KE SS,M8: POKE CS,CL:CS = CC+l87 40 NEXT: RETURN

87 50 POKE SS,PEEK(SS)OR(FL(XI AND7) - FR(X2 AND7»

8760 RETURN

900 0 PO KE CI , PEEK(CI) AND (255-1) :REM SET BANK 190 10 POKE VV+24,8+16*7902 0 POKE GF,GM: REM GRAPHICS MODE

90 30 RETURN

910 0 PO KE C I • PEEK ( C I ) OR 3 : REM SET BANK 0911 0 PO KE VV+24,209120 PO KE GF,CM: REM CHARACTER MODE

91 30 RETURN

960 0 IF SH >O THEN FOR 1=0 TO YM: SH(I ) = l : NEXT

96 10 SH =O: RETURN

9700 FOR I =CC TO CC+999: POKE I ,CL : NEXT

971 0 FOR I=SC TO SC+7999:POKE 1 , 0 : NEXT

97 20 FOR I = SC TO SC+3: POKE I ,M8: NEXT

9730 RETURN: REM TOP LEFT CHARACTER SHOWS COLOUR

10000 Y=O: X= O: Cs=o: 55=0: · DIM BP(7)10010 LL = 40: MX=999:KB = 197:KO=641002 0 SC = 1*16384+8*1024:REM SCREEN=BANKI SECTOR810025 CC = I*16384+7*1024:REM COLOUR=BANKI SECTOR710030 VV = 13 *4096:CI=VV+13*256:REM VIDEO CHIP,CIA10040 GF = VV+17: CM=PEEK(GF): GM=CM OR 3210045 REM GRAPHICS FLAG,CHAR. MODE,GRAPHICS MODE

10050 FOR 1=0 TO 7 : BP( l ) =2 " (7 -1 ) : NEXT

10060 M8 =255:XM=319:YM=199:SH=0: REM MAX X,Y10 070 JX=54297:JY=54298: REM ANALOGUE ADDRESS

1008 0 DIM SH( 2 0 0 ) , F L ( 7 ) , F R ( 7 )10090 FOR 1=0 TO 710095 F L ( I ) = 2 * B P ( I ) - I : FR( I )=BP( I ) - l :NEXT10 100 CL = 2 2 :GOSUB 9000:GOSUB 9700:REM WHITE/BLUE10 110 F=8: GOSUB 501010 12 0 SH=I:GOSUB9600102 0 0 GO TO 10 0

Sprite Editor

10 GOT02000: REM SPRITE EDITOR STARTS AT 200020 0 X=160:Y=100:DX=0:DY=0:X2=0:Y2=0:REM FUN DEMO

210 A=20:B=300:AY=40:BY=2 30220 M=255:V4=V+4:V5=V+5:VH =V+16

31

Page 37: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 37/133

DIY Roboti cs and Se nso rs on the Commodore Computer

300 X 2 = . I * ( R N D ( I ) - . 5 ) : Y 2 = . 4 * ( R N D ( I ) - . 3 )310 Xl=Xl+X2:Yl=Yl+Y2320 IF X<A THEN Xl=ABS(Xl)

325 IF X>B THEN Xl=-ABS(Xl)330 IF Y<AY THEN Yl=ABS(Yl)335 IF V) BV THEN Yl=-ABS(Yl)340 X=X+Xl:Y=Y+Yl350 POKE V5,Y:POKE V4,X AND M:POKE VH,-4*(X >M)360 GOTO 3002000 V=53248:PO KEV+21,4:POKE2042,1 32005 SB=832:POKEV+4,100:POKEV+5,lOO2010 POKEV+23,4:POKEV+29,4:PRINT CHRS(147):2020 E=0:B=7

2030 US=CHRS(145):DS=CHRS(17): REM CURSOR CHARS2040 LS=CHRS(157):RS=CHRS(29)2050 PRINT"SPACE TO CLEAR, . TO SET"2060 PRINT"CURSOR TO MOVE, X TO END"2100 P = P E E K ( S B + E ) : C = 2~ B : Q = ( P OR C)-C2200 POKE SB+E,Q:FORI=lTOIO:NEXT:POKE SB+E,Q ORC2210 GET AS:IFAS=""THEN:FORI=lT010:NEXT:GOT022002220 POKE SB+E,P2230 IFA$=" "THEN P=Q:A$=R$:POKE SB+E,P2 2 4 0 IFA$="."THEN P=Q OR C:AS=R$:POKE SB+E,P2250 IFA$=R$ THEN B=B-l:IFB)=O THEN 21002 2 6 0 IFA$=RS THEN B=7:E=E+l : IFE >62 THEN E=O2270 IFA$=L$ THEN B=B+l : IF B( 8 THEN 21002280 IFA$=L$ THEN B=O:E=E-I : IF E<O THEN E=632290 IFA$=DS THEN E=E+3:IF E >62 THEN E=E-6 32300 IFAS=U$ THEN E=E-3 : IF E<O THEN E=E+632310 IFA$="X"THEN PRINT CHRS(1471:GOTO 2002400 GOTO 2100

32

Page 38: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 38/133

CHAPTER 4

Logic In and Out

In Chapter 2, some mention was made of the internal goings-on of thecomputer and the difference between analogue and digital signals. Evenwhen the external signals are digital, bringing them to th e computer'sauen lion i s not a ltogether an easy matter.

Digital interfacesThe spine of the microcomputer is made up of two 'buses', bunches ofsignals which link mo st of the components together. The simplest of theseis the data bus. When the processor (another name for the microprocessor

chip) wants to sto re a data byte in memory, it switches the correspondinglogic vo ltage s on to the eight-bit data bus, issues a command, and theappropriate memory location remembers the data. When the processorwants to retrieve a byte, whether of data or the next instruction in its program, it sends out its command; the memory looks up the data and appliesa corresponding set of logic voltages to the data bus for the processor toread. You will see that the data bus is extremely busy, and an attempt toapply externa l signals to it could well send the processor diving in a spin.

To order the memory about, the pro cesso r mu st be able to specify an

address. Now we come across the second bus, the sixteen-bit address bus.65,536 different addresses can be speci fied as the bus stands, bu t a littlecheating can extend it to address any size of mem o ry you can afford.Another important line allows the processor to tell the memor y whether itwants to re ad o r write data.

What has all this to do with interfa cing? Clearly, s omething ha s to beplaced between aoy logic input lin e and the data bus, so that th e data is onlyallowed on to the bus forthe brief instan t when the pro cesso r wants to readit. This is th e rol e of the interface chip. I t mea ns, for insta nce , that eight

pins of the chip can be connected to a p lug on the ma chine for the convenience of the use r. Slip a socket on to thi s connector, and you can attacbex tra key s , se n sor co ntact s, or any other sort o f logic signal, and, with aprogram co mmand or two, read them into the computer. Thi s then is theuser port.

33

Page 39: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 39/133

DI Y Robotics and Sensors on the Commodore Computer

Making connections to the user portBefore gett in g to grips with the user port, it is a good idea to bring it within

reac h . This entails making a connecting ca ble, simil ar to the one describedin Chap ter 2, to bring the sig n als to a con nector st r ip beside the keyboard.Th e co nn ector in thi s ca se is a 12- way double-sided edge co nn ecto r pro viding 24 co nt acts with . 156 inch spacing. Suitable co des a re Cinch251.12.90.160, Amp 530657-3 a nd T eka TP3-121-E04. The connections of the l ogic data lin es are th e same for both the 64 a nd th e PET, butt he + 5V line to be found on the 64's co nn ector is missing fr om the PET.PET users must use a secon d connector attached to one of the cassetteports (against the advice in the PET manuals - but OK up to 50 rnA).

The connector pins are (looking in towar d s the comp uter) :

2 3 4 5 6 7 8 9 10 11 12A B C o E F H J K L M N

Strip: 2 3 4 5 6 7 8 9 10 II 12

CBM64 : 2 B C D E F H J K L M N

Signal: + 5V FIg PBO PBI PB2 PB3 PB4 PB5 PB6 PB7 PAZGndPet: • B C D E F H J K L M N

Signa l: +5VCA IPA OPA IPA2PA3PA 4PA5PA6PA7CB2Gnd

• (taken from PET cassette port pin B or 2)

After plu gging the edge connecto r into the comp ut e r, chec k o ut thesignals using the multim eter. Connect the negative test lead to position 12.Check for + 5V on po sit ion I - if it is no t there , perhap s th e socket is the

wrong way round . Signal s PBO to PB 7 (or PAO to 7) - fr om now on let uscall them PO to P 7 - can be chec ked by a mystic means which will becomeclear later in this chapter. Enter the program :

10 PO = 56577 : REM : • • • CBM 64or

10 PO = 5947 1 : REM: • • • PET20 PRINT 255 - PEEK(PO )30 GOT020

R un the program, and connect a wire from OV in turn to PO, P I up to P 7.The values I, 2, 4, 8, 16, 32, 64 and 128 shoul d appear on the screenre spe ctive ly.

34

Page 40: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 40/133

Chapter 4 Logic In an d Ou t

~ ~ ..~ ::-.

==--:

.........

"

--.: : ~

~

~~

g ~ . ,

t ~~ 0V\CL..

; )

0N

~"~

'- D

V \

j -

I " )

'"

0~

N~"

~-.0

VI

J

M

rJ

-1 l 5 It VI

+

~

\ I '

~

.. .::t ~~

~

"~~

~~l\..

~

CL" ....,

l\...

~

~

0~

Co

"~

-~: l

0~

0~

"""0"u'""'.;

"~'"b/ )

~

35

Page 41: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 41/133

DI Y Roboti cs and Sensors on the Commodo re Co mputer

How the interface worksNow at last we are in a position to look at the operation of the user port.

The signals which concern us at first are PO to P7, which are taken from theB-port of a Complex Interface Adaptor in the case of a 64 , and from theA-port of a Versatile Interface Adaptor in the case of the PET. The PET's

VIA is so versatile that it can baffle in an instant. I t is a single chip, a 6522,memory-mapped to appear at addre ss $E840 (the $ denotes hexadecimal). I f this makes sense to you, skip the next few paragraphs. Not contentwith being versatile, the 6526 CIA chip is complex. It is mapped at $ODOO.

Early computer systems used a special bus system for controlling input/ output, and many microcomputer s still have special input and output

instructions.I t

was soon realised, howe ver ,that

inputs and outputs couldbe treated as though they were memory locations. When a numb er is savedin memory, say in location $1234, voltages are altered within the circuitryof one of the memory chips. I f these were amplified and connected to theoutside world, they could drive eight output lines, so that storing a value of~ e r owould set all eight lines low, whilst 255 would set them all high. Whenthe contents of a memory location are loaded, on the other hand, the logicvalues of voltages stored in one of the chips will be copied into the accumulator of the microcomputer. Suppose tbat instead of stored voltages, thesesignals came from wire s connected t o eight voltages in the outside world,then we would have eight inputs. An interface chip can thu s be designedwhich will have a lot in common with a memory chip - and some manufacturers produce chips which combine both functions.

Address decod in gThe sixteen address lines of the 6502 microcomputer can directly addre ss65536separate bytes of memory - many more than will fit on the averagememory chip . The top few address bits are thus decod ed to give lines toaddress individual memory chips, whilst the remaining bit s are connectedto all chips in parallel to determine the address within the selected chip.(This is not absolutely true for some sorts of RAM, but ignore that fornow.) Not a ll the memory chips need to be present to make the systemwork, so there may be blank spaces within the memory map of themachine .

I f the top four lines are decoded, there will be sixteen ' chip-select' line s,the first responding to addresses from $0000 to $OFFF, the next from $1000to $IFFF and so on. One of these, the $ 0 line for instan ce, could enable

another decoder to decode the next four line s, giving sixteen more signal swhich would respond to addres ses$ OOXX,$OIXX . . . . . $OFXX, whereXX can be any two hex digits. One of these lines, say the one whichresponds to SOOXX, can enable yet another decoder, giving a further six teen lines which respond to $ODOX, $OOIX, etc. Finall y, one of these

36

Page 42: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 42/133

Chapter 4 Logic In and Out

lines, say, the $DDOX line, could enable a chip with just 16 memoryaddresses, $DDOOto $DDOF. Now suppose that, instead of being a genuinememory chip, this chip can be connected to the outsid e world. Tben, ifwe

save the value 7 (binary 00000111) in address $DDOI, we can control eightoutput lines to make three pins go high and another five pins go low . Tbat,in a nutshell (coconut?), is tbe principle of memory-mapped input / output. The troub le is that we now have to crack open tbe nut - and the 6522and 6526 are hard nuts to crack!

Port s a nd data directio n r egis tersSixteen bytes have 128 bits. I f we had separate lines for inputs and outputsthat would leave us with an awful lot of pins on the chip. After providingthe signals required to connect the chip into the micro system (18 lines) plustwo lines for power supply , a 40-pin pack does not have much to spare . The20 remaining pin s are arranged as two ports, each with eight data lines an dtwo control or 'handshake' lines. I t is one of these ports which should bynow be connected to the connector strip beside your keyboard . I t may looklikea connector to you, bu t the computer is convinced that it is the memorybyte at the address $DDOI (64) or $E84F (PET). Each port is bi-directional,that is each individual bit can be an input or an output. The direction ofeach bit is held in a register wit hin the chip called (wait for it) the Data

Direction Register. For the user port, the 64 sees DDR-B at $DD03 whilstthe PET addresses DDR-A at $E843. Each bit which is made a 1 at thisaddre ss will be selected as an output bit, whilst the Os will select inputs.

Now, how do we go about look ing at a specific addre ss location? Theexpre ssion PEEK( . . ) is used to denote 'contents of address'. Thus thecommand PRINT 5 will print the value 5, whi lst PRINT PEEK(5) willprint the contents of memory location 5. Similarly the command POKE 5,6will save the value 6 in memory 5 - and may crash the system at the sametim e!

Now get ready with your multimeter again. Set all the user port bits tooutput s by typing:

PO= 56577 :DD = 56579 for the CBM 64o r

PO = 59471 DD = 59459 for the PET

then POKE DD,255Also type:

POKEPO,255

to set all the bits high. Now check with your meter, and see that PO, PI,etc ., are all at about + 5V. Now type

37

Page 43: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 43/133

DIY Roboti cs and Sensor s 011 ihe Commodore CompUler

POKEPO,O

and see that PO, PI, etc., have all dropped toOV. Now, using the values 1,2,4 ,8,16,32,64 and 128 , ensure that you can set the lines high one at a time.Now try various combi nat ions - see why it 's easier to use hexadecimal?

Now tr y configuring th e port as an input. Just type:

POKEDD ,O

and every line will be an input. Enter the program:

10 PRINT PEEK(56577) : REM 64or

10 PRINT PEEK(59471): REM PET

20 GOTO 10

and run it. As you touch a OV wire on to each pin PO, PI, etc., you will seethe number change from 255. After a short battle of mental arithmetic, youmay prefer to change the program to:

10 PRINT 255 - PEEK(56577) : REM OR 5947120 GOTO 10

Sinks and sourcesYou have, of course, noticed that you have had to prod the inpu t wit h OV tochange it, not 5V. Each pin has an internal pull-up resistor which, if leftalone, will hold the input at 5V, and the computer will read it as a ' I ' . Topull the input down to a '0 ' , the input signal must be able to 'sink' about

IrnA of current. This current corresponds to one 'TTL load', and sets alimit on the number of logic inputs which a TTL logic gate output candrive. To have a good 'fan-o ut', a TT L gate must be able to s in k severa lmilliamps. but does not really nee d to 'source' any curr ent at all to work.The pulling-down capability of the logic output s is therefor e much betterthan the pulling-up power. (Althougb the 6522 and 6526 are MOS devices,they are designed to be TTL compatib le.)

More versatile yet!Of course that is not the whole story about the 6522. Four of its sixteenaddresses are taken up with data and data direction - that leaves twelvemore on which to build its reputation for versatility . Two pairs ofaddresses concern two sixteen-b it counters, which can be u sed for a varie ty '

38

Page 44: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 44/133

Chapt er 4 L ogic In and Our

of timing functions. Another controls a shift register, used to transfer datain and out ofCB2 . A further regi s te r, the flag register , indicate s the conditions whi ch c o uld have caused an interrupt , such as timer-e x pir ed, data

hands hake, etc. Finally two more register s , the Peripheral ControlRegiste r and the Auxiliary Control Register orche stra te the whole varietyshow. Eve n the simple-looking p o rt B ha s some surprise s up it s sleeve, forPB7 can produce a pulse of variable width or a pul se train under the controlof timer I, whilst PB6 can be used as an input for pulses to be counted bytim e r 2.

The 6526 is a close relative of the 6522, but tries to go one better. I t has abuilt -in time-of-day clock, which counts cycles of mains at 50 or 60 cycles.Otherwi se it is much the same, apart from a refinement to its serial output

which completely messes up the pse udo-analogue output scheme describedin Chapt e r 9 for the PET with it s 6522. With the addition of two re sistorsand a capacitor , the PET can give a signal which i s ideal for commandingan ana logu e ser vo -motor. The 64 has to find alternati ve methods.

Of g reate r imm ediate in ter est to PET owner s, is bow to input an analog ue s ignal from a jo ystick, and this warrant s a short chapt e r of its own .

Switching mains voltages

Having come to grip s with the port, now i s th e time to pu t it to some use. Aparti cularl y useful device when power- switchin g is required is the 'solidstate-relay' . Thi s is in fact an opto-isolated tri ac, which will switch an ACmains load of several amp s on or off at will. Provided aU nece ssaryprecaution s a re ta k en to avoid stray conductors ( o r, espe ciaUy, fingers) bridgingbetw een the signal end and the 'hot ' end of the device, the opto-isolationmakes it a safe de vice for connecting to the u ser port. Connection couldhardl y be simpler; th e + ve pin i s c onnected to + 5V, whil st the - ve pin isattached t o th e P bit , wh ich has been cho sen to o perate th e unit. Whene verth is bit is co nfi gur ed a s an output, and wb en the c or r espond in g output da tabi t is ze ro, th e swi tch will be on.

Th e RS numb er of th e 2.5 ampere de vice is RS 348-431. At a pricepushing £10 .00 , you may not want to add too man y channel s. The simplepro gram given b elow could be made to switch a readin g lamp on and off atrand om times. With simple modification s , the time s c ould be made lessrandom to give the impression of somebody working late, then going tobed. With the addition of a photoceU and a PEEK or two, the systemcan respond to fading daylight. Beware, howe ver , that the passing burglardoe s not deduce that the lamp is flashing th e pre sence of a computer in thehouse !

39

Page 45: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 45/133

DI Y Roboti cs and Sensors Oi l the Commodore Computer

+511 1¢( } 5 ~ V "t'Oft (..oN'l.U;ro",

MeUM i....

(fI-.'c IA)L :1i) ( ' j ~

=N '46> f1)

I f '

I 0r

.r ?!6ifl(/>(~ ):.(-1

fil,

~ E " ~ M E ./o

LIVE MA-IN5

"Box I I ,

~ La.r..r8ll»

@ € l

Figure 4.2 Solid state relay for light co ntrol

40

Page 46: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 46/133

Chapte r 4 Logic [n and Out

10 PRINT CHR$(147)"TIMES IN MINUTES: " 20 INPUT "MAX ON-TIME ";OM 30 INPUT "MAX OFF-TIME " ; FM

40 INPUT " MIN ON-TIME " ;OL 50 INPUT " MIN OFF-TIME ";FL 60 IF (OL - OM> 0) OR (FL-FM > 0) THEN GOTO 10

100 PO = 56577: DD = 56579 : REM *** CBM 64o r

100 PO=59471: DD =5 9459: R E M ' " P E T

11 0 POKE DD , I: REM MAKE BlTOAN OUTPUT

200 POKE PO,O: RE M TURN ON LIGHT 210 T =O L + (OM - OL)*RND(I): REM BETWEEN OL,OM

220 GOSUB 1000

300 POKE PO,I: RE M TURN OFF LIGHT 310 T = FL+(FM-FL)*RND(I) 320 GOSUB 1000 330 GOTO 200

1000 REM WAIT T MINUTES1010 T = T*60 : REM MAKE SECONDS1020 FOR 1 = 1 TO T1030 FOR J = I TO 1000: NEXT REM ONE SECOND DELAY1040 NEXT1050 RETURN

It's a bit primitive a s it stands, but I am sure th at you will be able to addany extr a features you nee d.

41

Page 47: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 47/133

CHAPTER 5

Analogue Input for the PET and 64

PET ow ners wi ll by now be imp at ient to know how to input a jo ystickpadd le signa l without needing to add an analogue-to-dig ital con verte rchip. The method described here uses no more than a single bit of the userport. The roots of the techniq u e lie in the depth s of antiquity - they are atleast five years old. Al though t he same princip le lies behind the converterbuilt into the 64, it can be extended to give high -q uality conversion suitablefor in s trumentation.

How it works

The old single-chip TV tennis games needed to encode the joystick signalswith a minimum of resources. There was no room for an analogue-to

digital conversion - the ch ip wou ld be hard pressed to proces s th e digitalva lue at display speeds anyway. Instead the joy st ick variable resistance wasco nne cted to a capacitor, giving a varia bl e time-constant. Let us considerhori zo ntal bat movement. At the start of each TV lin e the capacitor was

discharged. As the line was th en scanned, the capacitor cha rged up via thejoystic k r esis tan ce. As tbe capacito r passed the th r eshol d voltage of theinput co nn ectio n, the sc reen dot brightened to write the image of the bat.In other words, the joystick resistance was conve rted into a delay, whichcou ld be read by asingle input bit. Can't we play the same trick with one bit

of the user port?For demonstration purposes try a large value of capacitor first, so that

the timing ca n be don e with a loop of BASIC program . Afterwards reducethe capacitor so that machine code will give a sw ift answer. Start wi th 1000microfarads (a 6V elect ro lytic is actually quite sma ll ). Connect thisbetween OV ( - ve end) and PO. Now enter and run tbe following program:

10 PO =59 471: 0 0 = 594 59 :R EM • • • PETor

10 PO = 57577: DO = 56579 :REM ••• CB M 6420 POKE 00,1: REM configure PBO as an output30 POKE PO,O: REM zero ou tput to discharge capacitor40 GOSUB 1000: REM brief delay

43

Page 48: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 48/133

DIY Roboacs an d Sensors o n th e Commo do re Computer

100 C = 0: REM set co unt to zero110 POKE DD,O: REM PBO beco me s an input, capacitor rel eased120 IF (PEEK(PO) AND 1» 0 THEN 200 :REM got to thre sho ld ?

130 C = C + 1: REM k eep cou nting140 GOTO 120: REM round agai n200 POKE DD,I : REM di scharge the capacitor again210 PRINTC220 GOSUB 1000: REM brie f delay230 GOTO 100: REM do it all again

1000 FOR I = I TO 200: NEXT: RETURN

The numb ers w hich appear on the sc reen will depend o n the exac t value o f

the capaci tor. Discon nect the ca pa cito r and the num bers sho u ld fal l tozero . N ow connect a 2 kohm potentiometer, as a variable resistance inseries with th e capaci tor , to PO - ie capacitor + ve end to potentiometerwiper, one e nd of potentiometer to PO , - ve end of capacitor to OV. Whilethe pro gram run s, the number printed should change as the pote nti ometershaft is turned.

A high-speed machine code version

Som e reader s may be familiar with asse mbl y lan guage and machine code,while to others the subje ct mi gh t be a complete mystery. If, after readingth e next few paragr aphs, the subject is an even greater mystery, d o notdespair. The softw ar e is given in the form of BASIC data statements whichyou can enter i n the us ual way, and from. t hen o n you can rely on blind faithto make the program run. Your faith in your own typin g abi lity sho uld notbe quite so blind! I f you type th e letter 0 instead of th e number zero, th epr ogra m will almost ce rt ainly crash an d is likel y to be totally lost. Therefore before tryin g to run it , save it.

To ru n at an ac cepta bl e s peed , the routine mu st be rewrit ten in machinecode (ie assemb ly langu age ) an d shou ld ideally take the form of a USRfunction, so that you cou ld include the lin e:

X=USR(CH)

within a BASI C p rog ra m, to re turn th e value of chan nel C H . T hi s entailslinking the machine code to t he USR jump addres s, and also cal ling thefloating-poin t-to-integer co nve rsion routine (and vice versa) . With avarie ty of P ETs to deal with, not to mention the 64, all with ro utine s indiff ere nt place s, I pr efer to ta ckle the proble m in a different way.

Variables in the Commo d ore mach ines all take the same form. In particular, the fourth byte (ie b yte 3 - numb ered from 0) of an integer variablewill co n tai n the least -sig nificant byte of the value. Now, if that variable is

44

Page 49: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 49/133

Chapter 5 Analogue Input fo r the PE T and 64

1"f1A.t;-~ O ~ ~~ 10.... ti;: Y't ~ 1 v , 1J.IS (' lfO'-'!>e.cl .

Figure 5.1 Simple analogue input

45

Page 50: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 50/133

D ry Roboti cs and Sensors 011 the Commodo re Computer

the very first one to be declared , its location will be pointed to by bytes 42,43 (PET 30xx, 40xx , 80xx), or bytes 45, 46 (CBM 64) or bytes 124, 125 ifyou collect antique 2001s. Now two assembler instruction s:

LDY #$03LDA (VARS),Y

will load the accumulator with its value. Suppose the second variable to bedeclared is the integer V%, then:

LDY #$OASTA (VARS),Y

can be used to store the resuI t in V% .The next problem is finding a safe place to tuck the machine code . An old

favourite i s the second cassette buffer, starting at location $033A = 826.This u sed to be safe in the old days, but, in 40xx PETs, it is now gettingdecidedly crowded with disk signals. Others prefer the lOp of memory,pulling the ceiling down to prevent the code being trampled by strin gs. Myown preference is to make a sandwich in the BASIC, the bottom slice beingat the normal BASIC start address, containing a line such as (for 40xxPETs):

10 POKE 41,12: RUN

Then follows a generous filling of machine code, topped off at $OcOI bythe slice of BASIC which drives the machine code and takes the hard workout of disp laying o r filing the results. For demonstration purposes,howe ver, where the program ha s to be loaded from data sta tement s, wemight as well stick with the cassette buffer, using a patch at $0390 which isrelativel y traffic·free.

First the machine code must be loaded. Let us put the loader up out ofthe way at 10000.

10 CH% = O:V% =O:GOTO 10000

10000 MC = 3*16-3+9* 16: I = MC: REM $0390 10010 READ A$: IF LEN(A$)< > 2 THEN 100 :REM DONE IF XXXX 10020 GOSUB 10100 10030 POKE I,A: PRINT I,A$,A

100401=1+ 1: GOTO 10010 10100 A=ASqA$) - 48+7 *(A$ > ":"): REM CONVERT FROM HEX 10110 B$ = MID$(A$ ,2) 10120 A = 16*A+ASqB$)-48+ 7*(B$ > " :") 10130 RETURN

46

Page 51: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 51/133

Chapter 5 Analogue Input/or the PE T and 64

Now we ca n write the asse mbler in a recognisable form co nsisting of datastatement s (of co ur se yo u need not t ype in the REM parts). Do watch ou tfor capita l Os which shou ld be zeros!

10200 DATA AO,03 :REM10210 DATA BI,2A :REM10220 DATA A8 :REM10230 DATA 40,43, E8 :REM10240 DATA 8D,43,E8 :REM10250 DAT A 98 :REM10260 DA TA A2, 00 ,REM10270 DATA 7S :REM102S0 DATA 2C, 4F, ES :REM LOOP10290 DATA 00,05 :REM10300 DATA ES :REM10310 DATA DO, FS :REM10320 DATA A2, FF :RE M10330 DATA OD, 43, ES :REM DONE10340 DATA SO, 43 , ES :REM10350 DATA 5S :REM10360 DATA SA :REM10370 DATA AO,OA :REM103S0 DATA 91, 2A :REM10390 DATA A9,oo :RE M10400 DATA 80, 4F, E8 :REM10410 DATA 60 :REM10420 DATA XXXXX :REM

LOY ~ 3 PET.......LOA (VARS),Y

TAYEORDDR •STADDR •TYALDX #0

SEIBIT PORT •

BNEDONEINXBNELOOPLDX ~ $ F F

ORADDR •STADDR •C LITXALDY ~ 10STA (VARS),Y ..... *.

LOA 110STA P OR T •RTSEND

This version will work with 30xx, 40xx and 80xx ser ies PETs. The old 2001PET has it s pointers to the st a rt of variables at addresses 124 and 125, andso the code contained in lines 10210 and 10380 will need changing to:

10210 DATA BI, FC\0380 DATA91,FC

For the 64, the port and data direction addresses also need changing . Th ereare enough changes t o warrant listing this part of the program again:

10200 DATA AO , 03 :REM10210 DATA B1,20 :REM10220 DATA AS :REM10230 DATA 4D, 03, DD :RE M

10240 DATA SD,03.DD : REM10250 DATA 9S :REM10260 DATA A2,00 :RE M10270 DATA 78 :REM102S0 DATA 2C, 01, DD :REM LOOP

LOY ~ 3 CBM 64LDA (V ARS), YTAYEORDDR

STADDRTYALOX 110SE lBlTPORT

47

Page 52: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 52/133

DI Y Rob otics and Senso rs on the Commodore Computer

10290 DATA 00,05 :REM BNEDONE10300 DATA ES :REM INX10310 DATA DO, FS :REM BNELOOP

10320 DATA A2,FF :REM LOX ti$FF10330 DATA. OD,03,DD:REMOONE ORAOOR10340 DATA SO, 03, DO:REM STAODR10350 DATA 5S :REM e L I

10360 DATA SA :REM T XA

10370 DATA AO , OA : REM LOY t i l0103S0 DATA 91,20 :REM STA(VARS),Y10390 DATA A9 ,oo :REM LDA ti010400 DATA SD , OI,DO:REM STAPORT10410 DATA 60 :RE M RTS

10420 DATA XXXXX :REM END

Every so often the processor is interrupted, to go off and deal with somehousekeeping such as reading the keyboard. In a BASIC program this isnot noticeable, but, if it happens in the middle of the timing loop above, itwill mess up the result. The command SEI blocks the interrupt - butalways be su re to re-e nabl e it with CLI afterward s, or take theconsequences!

Now you can add a routine to test out the conversion. Remember thatthe channel number is set in CH"7o, with a result returned in V% . Theactual conversion is carried out by a caJ] SYS Me, where MC contains theaddress of the machine co de .

100 CH%=I:SYSMC:VI=V%: REM READ VALUE FROM PO110 CH%=2 :SY SMC:V2=V%: REM READ VALUE FROM PI120 PRINTVl,V2130 GOTO 100: REM MEASURE THEM AGAIN

Enter the program and set it running. With nothing attached to the userport, two columns of zeros shou ld appear on the screen . Now connect a 2microfarad capacitor in series with a 2 kohm potentiometer between POand OV. You shou ld find that, as you turn the potentiometer, you canobtain numbers in column I which vary from 0 to 255 . I f th e maximumnumber is less than 255 , use a cor responding ly larger capacitor. If thesmallest number i s not 0, u se a potentiometer of a higher value ofresj st ance.

Now give P I the same treatment, and yo u have the makings of a joystick. Of course, you can easily increase the number of input channels up toeight, one for each bit of the user port. There is not even any need to modifythe program - it will cope with 8 channels as it stands, provided they arecalled as 1,2,4,8,16 , etc.

48

Page 53: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 53/133

Chapter 5 Analogue In put/or the PE T and 64

The time for caution is when you have other inputs and outputs using theremaining bits of the user port. If you allow CHOT. to ha ve the va lue 240 oncalling SYS MC then the top four bits of the port will be left configured as

outputs. The program as it stands will also output zeros to all output bits;as long as your own BASIC program ensures that the bits which are to beread as analogue inputs are set to zero, you can simply omit line 10400.

A more accurate converterThe analogue input provision on the 64, and the co nvert er described so fa rin this chapter, are all very well for games joysticks, but they rall fa r shortof being usable fo r serious applications where linearity might be required.

They rely on the variation of a resistance for their input signal, and often asignal may instead be available in th e form of an analogue voltage, saybetween 0 an d 5 vo lts . This is the form which will be given as th e output ofan instrumentation amplifier, perhaps used for stra in gauges or such .

The modification to obtain a linear voltage input is a relatively slightone, bu t still only gives an eight-bit result. For many applications this wi ll

be sufficient, bu t a further modification to the software would allow theprecision to be as many bits as you like - although after twelve bits or sonoise will tend to swamp any improvement. The penalty for increasing th e

resolution is an increase in conversion time. For eight bits the conversiontakes about four milliseconds , and, at th e very best, the conversion timewill double for every extra bit which is added. A point is soon reachedwhere it is preferable to perform the conversion in a special hardware chip- although now added bits can cost extra in money.

The hardware refinement to linearise the input involves adding an integrator and a comparato r - two chips together costing under a pound. Thi swill in fact give you four channels of analogue input, taking up five bits ofthe user port.

Now an extra bi t is needed to control the integrator - we will use bi t P4.When this is high, the output of th e 747 operational amplifier (which formsthe integrator) runs rapidly negative until caught at OV by th e diode. WhenP4 is pulled low, the integrator is allowed to run positive to reach + 5V in atime lOOK' .047 microfarads = 10" 5 • . 047 • 10"(- 6) =4 .7 inilliseconds.The integrator ramp output is applied to the non-inverting input of each ofthe four comparators which make up an LM339. As the ramp passes eachof the input signals, which ar e connected to th e inverting inputs, th e corresponding output bit will change from 0 to I. This means that only a slight

change to the software given above is needed.First, the output of bit P4 must be pulled low at the start of conversion .This is achieved by adding a line to the software:

10235 DATA 09, 10:REMORA #$10

49

Page 54: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 54/133

l

l

-

"

1

"

0

.opoA

Page 55: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 55/133

Chapter j Analogue II/ put fo r the PET and 64

Alt he end of conversio n the bit P4 mu st be allowed high again to reset theintegrator to OV. Th is is performed by a new line 10335:

lOBS DATA 29. EF :REM AND #$EF

Now the softw are is co mpatible both with simple joysticks co nnected asbefore and with lin ear conversion of volta ges in the range 0 to 5V using theinterface of Figure 5.2 - t ry it and see .

Laboratory instrumentation

Now that PET Owners ca n read an analogue signa l or a joystick. they will

want to find an excuse to use it. Th e gra phics system of Chapter 3 is ou t oftheir reac h unless they have bought a high -resolution graphi cs syste m. buta much simpler use of graph ics will enable a high-resolutio n chart to beplaited down the screen . Thi s can enliv en ph ysics ex peri ments by catchingtran sients at up to fifty or so reading s per second . or by delegating to thecomputer th e task of sitting patiently taking readings every half hour.

To save the data po ints. i t is necessary to open an a rr ay by substitutingsome new line s at 100 onwards :

100 POKE 59468 .12 :PRIN T CHR$(128 + 14):REM SET GRAPHICSMODE

110 PRINT CHR$(l47) :REM CLEAR SCREEN120 INPUT "HOW MANY DATA POINTS";NP130 INPUT "HOW MANY CHANNELS (I TO 4)" ;NC:NC = NC - I

140 DIM R(NP .NC).CC(NC)150 FOR I = 0 TO NC:CC(I)=2'l:NEXT:REM SET UP CHANNEL

CODES160 INPUT "DELAY BETWEEN SAMPLES (WHOLE SECONDS)"

D170 D$ = RIGHT $(STR$ ( IOOOOOO + INT(D».6):TO$ = ' '000000''

Now wecan start to log data:

1000 FOR P = 1 TO NP:PRINT1010 FOR C = 0 TO NC:CHOlo= CC(C) :SYS MC1020 R(P. C) = V Olo: GOSU B 2000 :REM STORE DATA. PLOTlT1030 NEXT C:GOSUB 1500 :NEXT P:REM DELAY BETWEEN

POINTS1040 END

Subroutine 1500 must provi de the timi ng fun ction. waiting until the a ppropriate second has ticked:

51

Page 56: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 56/133

DI Y ROb Otics and Sensors on the Commodore Computer

1500 IF Ti $ < D$ THEN 15001510 TI$ = TO$ :RETUR N

We are now left with writing a display routine at 2000 onwards, capabl e ofshowing off the results to their best advantage. The very simpl est method isto ' tab ' across the screen with TAB(VOJol7), an d then to print a symbo lcorresponding to th e chann el number:

2000 PRINT CHR$(145) :REM CURSOR UP RETURN FOR LEFTMARGIN

2010 PRINTTAB(V%I7); CHR$(C+49);2020 RETURN

Try out the program as developed so far.With a resolution of only forty points across the screen, this is no t parti

cularly inspiring. Let us get higher resolution by using the graphics characters, each representing a vertical line in one of eight positions - this willgive 320 di splay values . and so none of the analogue resolution need bewasted. The graphics characters are defined by adding lines 180 onwards:

180 DIM G$(7):FOR 1=0 TO 7190 READ C:G$(J) = CHR$(C) :NEXT

10300 DATA 165,212,199,194,221,200,217,167

Now line 2010 can be replaced by

2010 PRINT TAB(V OJo/8);G$(V% AND 7)

Unfortunately. there is now no way of telling the channe ls apart , so, every161ines, the tr aces s hould be labelled. This can be achieved by putting backa variation on the old line 2010 as:

2005IF

(p AND 15)=0 THEN PRINT TAB(V% / 8);CHR$(C+49):RETURN

Having caught yo ur data, you may want to display it again by typing adirect command GOTO 3000. The routine at 3000 to play it out will simp lybe:

3000 FORP= 1 TO NP:PRINT:FORC=OTONC30 10 V% = R(p,C):GOSUB 2000:NEXT:NEXT3020 END

Now try this final version. I f you have lost tr a ck of its development, it islisted in full at the end of the chapter. Its structure is simple enough so thatyou shou ld easily be able to modify it to analyse the data automatically ,perhaps plotting the log Or th e square of one channel, and perhaps the ratio

52

Page 57: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 57/133

Page 58: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 58/133

DrY Roboti cs and Sensors on lite Commodo re Comp uler

Data Acqui sition and Plotting-P ET

10 CH'l.=O:V'l.=O:GOTO 10000: REM ~ ~ ~ PET100 POKE 5946B,12:PRINT CHR$(12B+14)110 PRINT CHR$(147)120 INPUT"HOW MANY DATA POINTS";NP130 INPUT"HOW MANY CHANNELS(l TO 4) ";NC:NC =NC- 1140 DIM R(NP,NC),CC(NC)150 FOR 1=0 TO N C : C C ( I l= 2 ~ I : N E X T

160 INPUT"SAMPLING INTERVAL (WHOLE SECONDSl ";D170 D$=RIGHT$ (STR$ (100000 0 +INT(DI 1 ,6 )175 TO$="O OOOOO"1BO DIM G$(71:FOR 1=0 TO 7

190 READ C:G$(I)=CHR$(Cl:NEXT1000 FOR P=1 TO NP:PRINT1010 FOR C=O TO NC:CH'l.=CC(Cl:SYS MC1020 R(P,Cl=V'l.:GOSUB 200010 3 0 NEXT C:GOSUB 1500:NEXT P1040 END1500 IF T I$ <D$ THEN 15001510 TI$=TO$:RETURN2000 PRINT CHR$(1451; : IF (P AND 151 ) 0 THEN 2 0102005 PRINT TAB(V7./Bl;CHR$(C+491:RETURN2010 PRINT TAB(V7./Bl;G$(V'l. AND 71:RETURN3000 FOR P = 1 TO NP:PRINT:FOR C=O TO NC3010 V'l.=R(P,Cl:GOSUB 2000:NEXT:NEXT302 0 END10000 M C= 3* 1 6~ 2 + 9 ~ 1 6 : I= M C

10010 READ A$:IF LEN(A$) <> 2THENI0010020 GOSUB 1010010030 PO KE I ,A:PRINT I ,A$,A1004 0 I = I+l:GOTO 10 0 1010100 A=ASC(A$I - 4B+7*(A$ >" :"110110 B$ =MID$(A$,2110120 A = 1 6 ~ A + A S C ( B $ ) - 4 B + 7 ~ ( B $) " : " 1

10130 RETURN10200 DATA AO,0 3 , Bl ,2A, AS , 4D,43,EB10210 DATA BD,43,EB, 9B, A2,00 , 7B10220 DATA 2C,4F,EB, DO,05, EB, DO,FB10230 DATA A2,FF, OD,43,EB, BD,43,EB10240 DATA 5 B, BA, AO,OA, 91 ,2A, A9,OO10250 DATA BD,4F,EB, 6010260 DATA XXXX10300 DATA 1 6 5 , 2 1 2 , 1 9 9 , 1 9 4 , 2 2 1 , 2 0 0 , 2 1 7 , 1 6 7

54

Page 59: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 59/133

CHA PTER 6Stepper Motors and Their Use

Stepper motors are a favouri te actuator for obtaining motor output. Theirdrives involve only logi c signals, with no need for digital-to-analogue conversion. Until recently, only precision 'upper-class' motors were availableat an outrage ous price, but, with the microcomputer an d a requirement forlow-cost peripherals, there has come a demand for cheap stepper motorswhich the industry ha s been swift to fulfil. A suitabl e motor for turtles andmicro mice i s the Philip s 1035, di st ribut ed by lmpex of Richmond ataround £12.00.

Problems and principlesDespite th eir apparent advantages, stepper motors are not without theirproblems. They have a firm restriction on 'their top speed, and the us ef ultorque falls off dramati ca lly as thi s is approached . Sudden spee d changes,even at relative ly low spee ds, can sta ll the motor. Unfortunately, unle ssspecia l sensors are added, the computer is unawa re that the motor hasslipped 'out of cog' . All subsequent movements therefore take place with aposition error , until a reset manoeuvre is made . Another drawback in abattery -driven system is power consumption; even when stationary, a stepper draws as much power as under full load.

Ju st how does a stepper motor work? The rotor is a permanent magnet,whilst the stator (the fixed case) has a number of electrical windings whichwhen energised create a magnetic field. The field pulls the rotor into line,and, by changi ng the selection of energised windings in a suitable sequence,lhe roto r is pulled round step by Slep. When the stepping sto ps, the rotor isheld in position by lh e magneti c field .

A simple stepper demonstratorThe movement of the permanent magnet rotor can be likened to therotation of a magnetic compass - indeed you can use a compass in an

experiment to demon strate how a stepper motor operates. Obtai n a cheapcompass - the simple so rt with a pointer rather than an ornate card will bebest. Wind a coil of 50 turns of fine enamelled copper wire - 36 SWG orfiner - across the compass. Obviously the wire must not obscure the v iewof the needle.

55

Page 60: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 60/133

IP9

/

.QUUnOA

Page 61: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 61/133

Chapter 6 Stepper Motors and Their Use

Connect a 47 ohm resistor in series with the coil, and apply 5V across theends . You can take 100 milliamps from the 5V p in on the user port connector - although this is the top limit. Of course, experimenting is made easyby using th e c hocolate blo ck connector strip and cable described inChapter 4.

When the vo ltage is applied, the needle should rotate and line up almostperpendicular to the co il , ie along the ax is of the coil . Reverse the appliedvoltage, and the needle will reverse. Cou ld the coil, and hence the needl e,be driven directly from two bits of the user port? Unfortunately, the current availab le from PBO-7 is limited to about 3mA: unles s yo u are prepared to wind coi ls of severa l hund red turn s, thi s will not dominate theeffect on the needle of the earth's magnetic field . The PET uses PAO-7,

which have even less drive . We must therefore use some amplificationno bad thing in preparing to drive genuine stepper motors. The simplestamplifier consists of just one resistor and one transistor per bit of o u t p u tfour of each per motor. (Later on, we can consider using a Darlingtondriver chip instead.) A good general purpose PN P transistor is a 2N 3703(RS 294- 334), costing well under £ 1.00 per pack of five. First con nec t justone transistor to your coi l, driving it from PBO via a I kohm resistor as inFigure 6.2.

Connect the circuit and switch on. Nothing should happen to the com

pass at first. Now tell the computer the addresses to use for the Data Dire ction register as variab le DD and for the output POrt as variable PO bytyping:

DD = 56579 : PO = 56577 : REM ***** CB M 64or

DD=59459: PO=59471: R E M · · · · · PET

Now you can set the output da ta register to all-bits-high by typing:

POKEPO,255

Next, configure bits 0 - 3 as outputs by typing:

POKEDD,I5

Still nothing should happen, because the output of bit 0 is high, and doesnot yet sink any current via the transistor base. Now type:

POKE PO,255 - 1

This will take bit 0 to zero and current willl10w into PBO (or PAO for PET)from + 5V through the tran sistor base and RI. The transistor will beturned on, applying 5V from the transistor collector to the coil and

57

Page 62: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 62/133

.1UUSU~!loqOH

A

Page 63: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 63/133

Page 64: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 64/133

0

.

1

-

.SA

Page 65: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 65/133

Chapter 6 Stepper Motors and Their Use

Figure 6.4 Two coil s

6 1

Page 66: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 66/133

DIY Robotic s and Senso rs on th e Comm odor e Compurer

Speed and acceleration controlEnter and run the following program:

10 DD = 56579:PO = 56577or

10 DO = 59459:PO = 59471

20 POKEDD,I 5 30 POKEPO ,255-5

40 GOSUB200 50 POKEPO,255-9

60 GOSUB200 70 POKE PO ,255 -10 80 GOSUB200 90 POKEPO,255-6

100 GOSUB 200110 GOTO 30

:REM • • • • IF CBM 64

:REM • • • • IF PE T

:REM BITS 0 -3 ARE OUTPUTS:REM BOTH COILS ON TO GIVE NE:REM I SECOND DELAY:REM NOW COILS GIVE NW

:REM NOW COILS GIVE SW

:REMNW

:ROUND AGAIN FOR ANOTHERREVOLUTION

200 FOR I = I TO 1000: NEXT:RETURN : REM DELAY I SECONDORSO

The compass needle should now rota te, if somew hat jerkily, acting as astepper motor .

Now you can try a variety of numbers in lin e 200 to set the speed of themotor. You will find that, if you aim too high, the mo tor wi ll not evenstart. Try accelerating steadily by making the following changes:

Add line 5Ch ange lin e 200Add line 210Add line 220Add line 230

V=2000

FOR I = I TO V:NEXTV = V- I

IFV < 50 THEN V = 50RETURN

Now the d elay will reduce progres sively, until the top speed is rea ched. Tryvarious value s in line 220.

The speed will climb very slowly, ru shing at the end. A steadier speed-upcan be obtained with:

210V = V· .995

You are now experimenting with techniques which you will need when yougraduate to a genuine steppe r mo tor . Of course, the pro gram is st ill grosslyinele gant, and is no t exactly versati le. Neverthe less , rhe compas s motorwill alr eady have tau ght you so me of the pitfalls to look for:

62

Page 67: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 67/133

Chapter 6 Stepper Molors and Th eir Use

1. Witho ut driv e, the motor does not ret ain its po sitio n.

2. Settling to a new po sition take s the form of a poorly-damped osc il

lation. At certain stepping speeds, th ere is a re sonance so that th e osci l lations build up; th e motor then stalls.

3. Move ment a t low spee ds is 'lumpy'. This ca n be impro ved somewh at bydoubling up on the applied steps, so that th e se qu enc e is N, NE , E, SE, S,SW, W, NW and back to N.

4. Sudd en changes of speed will stall the motor.

5. Ther e is no absolute position reference. Everythin g depen ds on themotor keeping in ste p.

Stepper software with some structureNow let us try to introduce so me 'style' into a new pro gra m, so that it willbe of more gene ral use. The code s whi ch determine the coil polaritie s arebes t held in an array. I ha ve a p erso nal preferen ce for puttin g all initialisati on dat a at th e end of the program, so that it do es not obscure lis tings ofthe functional part. Thus the program will start with GOTO 10000, an d alldefinitions will start at line 10000.

tOOOO DD = 56579 :PO = 565 77: REM • • • • CBM 64or

10000 DD = 59459:PO = 59471: REM • • • • PET

10010 DIM DR(7):FOR I =OTO 7: REM DRIVE CODES10020 READ J : DR(I)=255 - J: NEXT!10030 DATA 1 ,5,4,6,2, IO,8,9:REM COILS IN ORDER N -S-E-W10040 POKE DD , 15: REM MAKE BITS 0 -3 OUTPUTS10050 GO TO 100 : REM HOUSEKEEPING DONE

The number of steps to mo ve is held in variab le DI (DI sta nce) , whilst thedirection is held in RO (ROtation) a s a val ue ± l . Th e current p os ition isheld in HEr e, and the SPeed is se t by variable SP. Now an appropriatesec tion of progr am to command the movement could be:

200 GOSUB 5000: REM MOVE DISTANCE, ROTATION, SPEED

where tb e s ubroutine has be en defined as:

5000 IF (DI< I )OR (SP< I)THEN RETURN5010 FOR I = 1 TO DI

63

Page 68: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 68/133

DI Y R obo tics and Se nso rs on the Commodore Computer

5020 HE = HE + RO:REMADDROTATIONTOHERE5030 POKE PO,DR(HE AND 7) :REM OUTPUT CODE TO PORT5040 FOR J = I TO 1000 STEP SP:NEXT J

5050 NEXT I5060 RETURN

The variable delay of line 5040 might appear a clumsy way to setlhe speed,but it is effective unless the value of SP is excessive. A more elegant technique, that of the 'binary-rate-multiplier', is described in the next chapter.I t is useful for coordinating the movement s of several steppers, but,because of an uneven steppingYate, the top speed is reduced.

To compl ete this program , you can add:

10 GOTO 10000100 PRINT "DISTANCE, ROTATION DIRECTION , SPEED "110 INPUT DI,RO,SP200 GOSUB 5000210 GOTO 100

and you have a demonstration program enabling you to command a movefrom the keyboard . You should then be able to write a more elaborate

program which build s an array of programmed moves and then execut esthem.

A second stepper motor can be added, driven from bits 4 to 7. This willenable you to make a p lotter or a turtle, but will be a bit r es tricti ve f or arobot. You will need to use some c1eveLaddre ssing technique s ifup to eightmotor s are to be commanded from a single user port.

Power suppliesBefor e going into any more software detrul, let us con sider th e electroni cproblems of interfacing one or more genuine stepper motors to thecomputer. The principles rem run the same, but we must now be ab le tosupp ly much greater cu rr ents . The se are beyond the permitted drain whichcan be taken from the micro, and so a separate supply must be provided.You should be able to buy a I amp supply, variable from 4 to 10volts, forunder £30.00. Even so, thi s is scarcely enough current - although an overload will merely 'fold back' the output. The best an swer may be to build theunstabilized supp ly described in Chapte r I , which will giv e around threeamps ou tput at + 7V and - 7V. Many stepper motors will require 12V ormore to give of their best, and the power supply can be connected to give asingle 14V supply - ju st by using the - 7V terminal as the negativeconnection and ignoring the centre terminal.

64

Page 69: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 69/133

Chapter 6 Stepper Molors and Their Use

A lazy but risky alternative is to take your life in your hands and use amotor-car baltery charger. This will probably give you up to four amps,but will need a large external capaci to r - 10,000 microfarads or so. I t will

also give poor regulation, and will put nothin g better than a four-amp fusebetween your circuitry's well-being or annihilation. Still, it's better thanbuying an endless supply of batteries, unless you can afford rechargeables.

Interfacing hardwareThe simpl e tran sisto r will hardly have enough 'beta' to drive a steppermotor from the ea rlier circuit. However, you can buy Darlington transistors with much higher gain. They are, in fact, a pair of transistors in

cascade, but have the disadvantage of a higher 'bottomi ng' voltage - theyare less efficient in low voltage circuits. Nowadays, it is much moreeconomic to buy multi-fun ct ion chips than to bu y individual tran sisto rs,and the RS 307 -109 chip co ntains seven Darlington s, complete with inputres istor s and protection diodes, for well under £2.00. Murphy' s Law getsyou, of course, because to drive two step per motors you need eig ht outputs, not seven.

Another complication is that the se circ ui ts are sinks, Dot sources. Thecommon point of the motor windings must therefore be connected to the

positive supply, and the win ding will be ene rg ised when the user portOutput bit is high, no t low. The line ofthecomputer program setting up theoutput pattern s will have to be changed, leaving out the '255 - ' inversion,to become

10010 READJ:DRIVE(I)=J:NEXTI

Moreover, the program will have to poke PO and DD with 255 as early aspossible, so that zeros will be output and the motor will no t be incinerated

und er double its fair share of active currents .With the change to the program de scri bed above, and with the circuit

sbown below, you should be confident of your ability to drive step pingmotor s and should be read y to build a simple turtle.

Multi-pole steppersStepper motors can have as many as 200 steps per revolution. As the inputsare sw itched through one 'electrical revo lution', the motor only rotatesthrough a few degrees. How is this achieved? Figure 6.6 show s a rotorwhich, unlike a simple compass needle, has two North and two Southpoles . The motor coils are no longer wound directly across the rotor , bu tare wound on pairs of sali en t poles. When winding 1 is driven in the positive direction, let us say that poles 'A ' become South and poles 'a ' become

65

Page 70: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 70/133

DI Y Robot ics and Senso rs on the Commodor e Computer

1'¢

PL

.p2..

1"3

0 - /

66

:I.Mot'" J.

<..c """,e..GA I 0 I'\. ~

'~ IS ',~ w

1 _ _ _ _

+/'1-11

- - .,

r-/ 'I, I

,.

P o . , J ~ V

5 ~ NW " ~ E

0 " $"fF1

N

@M v'€

"" et.r"E

5£ , t ' . ' ; v \ - A . I ~ " , - ! : rvtOt-r~ t ~ V " " " ' (c.f) ........e<.,C'o'"

Fi gure 6.5 Darlington driver chip

Page 71: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 71/133

Chapter 6 Stepper Moto rs an d Thei r Use

Figure 6.6 A four-pole stepper

67

Page 72: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 72/133

DIY Robo tics and Sensors on the Com modore C om put er

North. When instead winding 2 is driven in a positive dir ect ion, pol es ' 8 'bec ome South and the rotor i s pulled round through 45 degrees. After the

windings have been stepped through one electrical revolution, winding 1will again be driven positively, and the rotor will have made ju st half a turn.Pu t more poles on the rotor, and the rati o between e lectrical steps androtation angle will incr ease.

68

Page 73: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 73/133

CHAPTER 7A Simple Turtle

If yo u come across an inverted soup bowl , wandering about and perhapsdrawin g s hape s on a large sheet of paper, you have met a turtle. There is noattempt here t o go into the intricacie s of turtle graphics; instead the prin ciples of the turtl e se rve as a good excuse for puttin g a pair of steppermotor s to work .

Turtle fundamentalsThe turtle i s a simple 'wheelchair' system, propelled b y two independentwheels on a diameter. Ball bearings or skids limit the resultant fore-and-afttoppling . To move straig ht abead, both wheels rotate in step. To tum onthe spot, one wheel rotates forwards while th e other rotates backwards atexactly the sa me rate. I f one wheel turns at exactly twice the speed of theother, the turtle will follow a circle with its centre one wheel-space from theslower wheel. Ac curate movement calls for the motors being driven accurately in step - ju st the jo b for step per motor s!

At the cent re of a 'genui ne' turtle is a retra ctabl e pen , so that it s perambulations ca n be used to draw shape s, or even graphs and illu stration s. Letus think about that problem later.

Two stepper motors ca n be dri ven, with littl e complication, from th eeight bits oft be user po rt. With the aid of two multi-Darlington chips plusthe expe rien ce of the last chapter, the ta sk of making the motor s rotateshould give littl e trouble. The more difficult part i s to make the so ftware' meanin gf ul', so that a co mmand stru ctu re can be ba sed on the de siredmovement s of the turtl e without goi ng into the gor y details of the numberof motor step s required for each gy ration . Takin g a ' top-down' look at theprob lem , we want to be able to type 'advance 100' to move 100 mm forwards, or p e rhap s ' turn, clockwise, 90'. C ircl es wou ld be nice to add, withperhap s 'circle, clockwise, 200 , 90' giving 90 degree s of a 200 10m radiu scircle. It might not even be ove r the top to add Cornu spiral s to blend oneradiu s with another - but not ju st at the moment. With graphics in mind,

the furth er command s 'p en, up ' and 'pen, down' complet e the set. Thetask of workin g out where the turtle would wind up after a givenmano euvre can b e performed on the command sequence by anothersubroutin e, if req uired , although mechanical tol erance s mean that theresult will not be parti cularly accurate after a lengthy perambulation.

69

Page 74: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 74/133

O

\\

".

~'#d

. -0

>/

)~ " \f #..J~s

t~

~ ~

rl"~d

"

.OPSOA

Page 75: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 75/133

"Pcp

P1

P P3

fr

p~

p~ P an

(~"')

{

l

r~<..(6

)

!1

ov

,~ f

+1

1

. ;J

.

Fg

e72

Cic

fo

r

u

ed

n

o

~

L~tMO

c

OV

'R1~k.tM.OtO)l"

n

?_

L.f

g

Page 76: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 76/133

DI Y Robotic s and Sensors o n (he Commodore Computer

Mechanical designTh e sugges ted stepper motor s are type [035, mad e by Philips and distri

buted by Imp ex of Richmond at a price around £12.00. The y have 4 8 stepsper rev. , ie 12 elect rical r evo lution s per mechanical revo lution. If you dri vethe motor in half- steps, ie N , NE, E , SE, S, SW, W , NW, yo u will now have96 half -steps per revolution of the wheel. Suppose that your wheels are 80mm in diameter, then th ey wi ll have a circumfe rence of around 250 mmand each half-step will give a movement of about 2.6 mm . If you don'tmind mak ing or trimmin g yo ur own wheels, then a diameter of 2*96 / pi =

6 1.1 mm will give exactly 2 mm per half step - but you would be best tobuy the neares t large r size from th e model-shop, and accept a slig htl y o dd

scale factor.Wh en the motors are driven eq uall y in opposite directio ns, the turtlerotates about its cen tre . I f ea ch wheel make s o ne revolution, then the turtl ewill turn through (diameter-of-wheellseparation-of-wheels) revo lutions.Make the separatio n two-and-a-half time s the diameter, and each step willgive ju st one degree. If the motor s are driven at un equal speeds , the distan ce ad va nces will be give n by th e averag e o f the (signed) number of steps,whil st the turtle will turn through an angle equal to ha lf their difference.

The chassis can be made from plywood or even balsa woo d, since it ha sve ry little work to do. Th e ski ds can be forme d from lightw eig ht cupb oardball-catche s, althou gh a co upl e of bent paper clips wi ll really serve thepurpo se . They sho uld just clear the ground , so th at only one touches thegrou nd at a time . Most of the mecha nical load will be due to the umbilicalcab le, and thi s must be co nnected to the turtle a t a high cent ral p oi nt. I f yousac rifi ce some so rt of plastic bowl to make a cover , then the cab le ca n safelyemerge from a ho le in the centre. If, howev er , your turt le is naked yousho uld mount a mas t in th e centre - no t too tall, o r the turtl e w ill topple.Th e ca ble should approach the turtl e from above, d angling from a supporting strin g attac hed to the ceiling.

At fir st sight you wi ll need at least a dozen conductor s in the cab le, fivefor eac h m o to r, two f or a pen- lift plus more for any se nso rs yo u ma y addlater. At a pinch yo u ca n ge t away w ith two less, s harin g a co mm o n positivepower lin e, but thi s may b e a fal se economy sinc e the resistance o f the ca bleca n ca use co uplin g betw een the motor dri ves. Ribb o n cab le is the neatestsolution , but far from the cheapest. Perhap s I should recommend a goo dbook o n plaiting.

Control s trategie sWe ca n make up an algo ri thm for converting th e com m ands jntodemand ed motor half-ste ps (from now o n , let u s call them just 'ste ps') asfollow s. Let us ass ume a w hee l diameter of 61 mm and a se paration of2.5* 61 = 152 .5 mm . See Tahle 7.1.

72

Page 77: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 77/133

Chapler 7 A Simple Turtle

Table 7.1

COMMAND LEFT MOTOR STEPS RIGHT MOTOR STEPS

Advance distancel2 distance/2Turn, cw + angle - angleTurn, acw - angle + ang leC ircle , cw ang le*(radius/I15 + I) angle*(radius / I15 - I)Circle, acw angle*(radius/I15 - I ) angle*(radius / I15+ I)

Now the command interpreter must ' talk to' a motor control module,whi ch w ill accept commands in the form of the numb e r of steps each motormu st move. An extra command, 4speed, 20', can adjust a general va riabl ewhich need not feature in the syntax. Let us use a subroutine to commandthe motor s , an d let us define this at line 8000 onwards.

Vary in g the spee d of a single motor ca n be done wi th a simple variabl edel ay, bu t to drive two motors at different speed s calls for a different co nce pt, the binary-rate-multiplier. Suppose that th e left motor must mov e100 steps, whil st the right motor mu st move only 67. Th en we first construc t the ratio of the two, in this caseO.67 . Each time round tbe lo o p we stepthe left motor, bu t the r igh t motor mayor ma y not need to step. To makethe decision we keep adding the ratio to another variab le, say T. 1fT is nowgreater than I, the motor is stepped an d T is redu ced by I . Sounds confusing ? Then let' s try an e xa mple, in Table 7.2 .

Table 7.2

LEFT MOTOR T RIGHT MOTORPOSmON POSITION

StepStep

StepSte pStep

012

345

0.67

1.34

1.01.681.35

Step

StepStepStep

00I

223

T becomes 0.34

Tbeco mes 0.01

T becomes 0 .3 5

Step 97 .99 Step 64Step 98 1.66 Step 65 T becomes 0 . 66

Step 99 1.33 Step 66 T becomes 0.33

Step 100 1.00 Step 67 T becomes 0.00

So we arrive at the end of the mov ement with each motor having takenthe correct number of steps. This is the principle behind most graphplottin g routines for drawing oblique straight lines. The result is sl ightlyimproved if T starts with the value 0.5, since this causes the une ve nne ss to

73

Page 78: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 78/133

DI Y Rob otics and Se nsors on the Commodore Comput er

be shared out symmetrically along the line. In the example above, the onlyoccurrence of three right-motor steps in a row is at the end of themovement; had T started with Ihe value 0.5 they would have occurred inthe mi ddle.

Motor control softwareWe can now define the subroutine to MOVE the motors, where th e numberof steps for the left motor is stored in LM and for the right motor in RM.

8000 AL=ABS(LM):AR=ABS(RM):REM ABSOLUTE VALUES OFSTEPS

8010 SL = SGN(LM):SR = SGN(RM):REM AND SIGNS OFDIRECTIONS

8030 IF AR + AL = 0 THEN RETURN:REM NO MOVE, GO HOME8040 IF AR > AL THEN 8200:REM DEAL WITH THIS

SEPARATE LY

8100 RA=AR / AL: T=0.5:REM RATI O OF MOVES8110 FOR M = I TO AL :REM HERE WE GO8120 GOSUB 9000:REM STEP LEFT MO TOR DIRECTION SL

8130 T = T + R A8140 IF T > I THEN GOSUB 9100: T = T - I: REM RIGHT MO TOR8150 GOSUB 9s60:NEXT M: RETURN:REM THAT'S ALL, GO

HOME

8200 RA=ALlAR: T = OS:REM RIGHT MOVE > LEFT MOVE8210 FOR M= I TO AR8220 GOSUB 9 10 0:REM RIGHT MOTOR EVERY TIME8230 T = T+RA8240 1FT > I THEN GOSUB 9000:T=T- I : REM LEFT MOTOR

8250 GOSUB 9500:NEXT M:RETURN

This still leaves us with the ' bottom -up ' task of writing the motordr ivers. We sta rt with housekeeping at line 10000:

10000 LP = O:RP = O:SP = lOO:REM MOTOR POSITIONS,SPEED

10010 PO = 56577:DD=56579: REM PORT, DATADIR ••• CBM64or

10010 PO=5947I:DD=59459: REM " . PET

10020 DIM LD(7) ,RD(7): REM TWO ARRAYS FOR MOTORDRIVES

10030 FORM = OT0710040 READJ : LD(M)=J: RD(M) = 16 ' J : NEXT

74

Page 79: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 79/133

Chapte r 7 A Simple Tu r tle

10050 DATA 1,5 ,4 ,6,2,IO, 8,9 :REM COILS IN ORD E RN -S-E-W10060 POKE DD,255:POKE PO,O :RE M MAKE OUTPUTS, SET TO

ZERO

10070 GOTO 100

Then we add the motor drivers, and a delay which depe nd s on SPeed:

9000 LP ~ (L P + SL) AND 7: REM LEFT MOTOR NEW POSITION 9010 POKE PO, (PEEK(PO) AND 240) + LD(LP) 9020 REM MIX NEW LEFT MOTOR DRIVE WITH OLD RIGHT,

OUTPUT9030 RETURN

9100 RP ~ (RP + SR) AND 7: REM RIGHT MOTOR NEW POSITION9110 POKE PO, (PEEK(PO) AND 15)+ RD(RP)9120 RETURN9500 FOR D ~ I TO 1000 STEP SP:NEXT

95 10 RETURN

(Us in g a modi cum of cunning , you sho uld be a ble to rewrite the m oto rproc ed ure s into a single procedure with two arguments QL and QR pre sentto SL, SR orzero. You should then be able to tidy up th e move procedure to

make it less lumpy. Th e ine legant procedur es here are designed to be easierto understand.)Befo re adding the clever stuff, trouble- shoot these module s with a ' jiffy

program':

10 GOTO 10000100 PRINT "LE FT MOTOR, RIGHT MO T OR"110 INPUT LM,RM120 GOSUB 8000

130 GO TO 100

and if the r esult doe s no t look too good, try some thing even simpl er:

100 SPEED ~ 10:SL ~ I110 GOSUB 9000:GOSUB 9500: GOTO 110

to get down to bedr oc k. I f all e lse fail s, ta ke manual co ntr o l by POKEingPO to var ious va lue s, and get out your tru sty test mete r.

Pe n li ft

Whilst we are dealing with the 'nuts and bolts', let us have a look at th e penlift. H aving t horou ghly used up the bits of PO to P7 , the o nly convenient

75

Page 80: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 80/133

9

"mL

.UUOpDsoA

Page 81: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 81/133

Chapler 7 A Simple Turtle

user port bit left is now pin M, position 11 of the connector strip , which isPA2 (64) or CB2 (PET). Without wishing to tangle too closely with theintricacies of the peripheral control register of the VIA, it is safe to revealthat POKE DO + 9, 14'16 (pOKE $E84C,$EO) will set the PET's CB2 high,while POKE DD + 9,12*16 will se t it low. Now pin M can be wired toanother channel of a Darlington chip (using up one of the six spare channels) to give a signal beefy enough to drive a solenoid. For the 64 we canadd:

7000 D = PEEK(PO - I)AND251: REMPORTA,BIT2LOW:* , . CBM 64

7010 IFP=OTHEND=D+4 : REM ENERGISE TO LlFT PEN702

0 POKEPO-I

,D:RETURN: REMOUTPUT TO PORT

Aor for the PET we can instead add:

7000 IF P = 0 THEN POKE DD+ 9,224:RETURN: REM ENERGISETO LlFT PEN

7010 POKE DO + 9,192:RETURN: REM DEENERGISE, DROPPEN

This does not answer your problem of finding a pen-lift solenoid to drive.A commercial solenoid can easily be bought, but is likely to be heavy andover-powered. I t doe s not take much to lift a ball-point, and even less to lifta felt-tipped pen, and yo u can subst itute a little dexterity for a lot of powerconsumption. An o ld post -office relay can, with the removal of the contactassembly, provide more than enough lift. You may need to fidd le a littlewith the pen h eight, but, provided your wheels are not eccentric, youshould get acceptable results.

Simple command interpreterNow we are ready for the command interpreter. This cou ld be written mostelegant ly and almost incomprehensively with searc hes in command lists.Instead let us try a 'knife and fork' job, which will simply perfo rm eachcommand imm ediately. I t can be adapted later to memorise and edit acommand sequence. The task of inputting the commands is no t madeeasier by the motley assortment of arguments they can take. We have on

the onehand'

ADVANCE, 200', andon

the other 'CIRCLE, CW, 45,150', so the user will welcome some user-friendly guid ance. Let us pu t theparsing routine at 1000:

100 GOTO 1000

77

Page 82: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 82/133

Page 83: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 83/133

Chapter 7 A Simp le Turtl e

8100 R A~ A R / A L :T ~ . 5

8110 FOR M ~ 1 TO AL:GOSUB 9 0 0 0 : T ~ T + R A

8140 IF T ) 1 THEN GOSUB 9 1 0 0 : T ~ T - l

8150 GOSUB 9500:NEXT M:RETURN8200 R A~ A L / A R :T ~ . 5

8210 FOR M ~ 1 TO AR:GOSUB 9 1 0 0 : T ~ T + R A

8240 IF T ) 1 THEN GOSUB 9000: T ~ T - l

8250 GOSUB 9500:NEXT M:RETURN9000 L P~ ( L P + S L )AND 79010 POKE PO, (PEEK (PO) AND MR)+LD(LP)9020 RETURN

9100 R P ~ ( R P + S R )AND 79110 POKE PO, (PEEK (PO) AND ML)+RD(RP)

9120RETURN

9500 FOR D ~ 1 TO 1000 STEP SP:NEXT:RETURN10000 L P ~ 0 : R P ~ 0 : M R ~ 2 4 0 : M L ~ 1 5 :REM MASKS

10010 P O ~ 5 6 5 7 7 : D D ~ 5 6 5 7 9 :REM *** CBM 6410020 S P~ 1 0 0 : D I MLD(7) ,RD(8)10030 FOR M ~ OTO 710040 READ J : L D ( M ) ~ J :R D ( M ) ~ 1 6 * J :NEXT

10050 DATA 1 , 5 , 4 , 6 , 2 , 1 0 , 8 , 9 : REM N-S-E-W10060 POKE DD,255: POKE PO,O10070 GO TO 1000

79

Page 84: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 84/133

CHAPTER 8

Interfacing a Robot

A fully-fledged robot ha s seven degrees of freedom , that is to say it requiresseven independent motor s to drive it. The 'end effe ctor' (a fancy term for'hand') must b e ab le to move in three dimen sion s, and for any given position it should be ab le to sw ivel abo ut three more axes. A furth er channel isneede d for 'ope n' or 'clo se', although this is often a simple on/off valvewo rking a p neumatic gri pper. Edu cational robots, suc h as the Armdroid ,sac rifice ooe of th e 'w ri st' axes, but give continuou s grip mo vement. Thisreduc es th e number of channel s to six . I f the se are driven by steppermotors, how can we interface them to the computer? [n the las t chapt er,two chann els of slepper motor were interfa ced to the u ser port with the useof a ll eight bits , so for six channels we !Ilust find so me new tecbnique tocommand th em all. I t is necessary to includ e an address a s part o f theuser-port data , which ca n be decoded within the robot itself.

Multi-stepper controlThe user port provide s eight bit s : a stepper motor need s four bits to define ahalf-step position (unles s you are happy interfacing using the scale of three:N, of f,S) . That leaves four bits for hou sekeepin g. From three of thesebit s, a n address can be con structed to address e ight channel s. Th eaddressed cbannel will now cap ture the mot or s ign als in a fo ur-bit latch,and ca rr yo n dri ving the motor line s until told to do otherwise. Now weneed a 's trob e' signal a s we ll , so that we can tell the circuitry ' the motorlines have finished chang ing, the add ress lines are settl ed, ca tcb th is datanow and use it' .

The co nne ction s to the somew hat ageing Armdroid on which tbe programs of thi s chapte r have been tried out are as follows:

PBO PBI PB2 PB3 PB4 PBS PB6 PB7 Str obe ------Channel-- ---- N--- ------ -E-- -------W --------- S

Note that lh e 'co mp ass ' bit s are sllUffled in comparison with the la stchap te r , and so the data statements for th e co des are different. Putting the' channel' bit s in a shifted po sition does complicate the code calcula tion alittl e, but eve rythin g co me s out in th e wasb.

8 1

Page 85: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 85/133

DI Y Robotics and Sensors on the Commod ore Computer

Sin ce the strob e will be ac tive when low , the pro ced ure for outp uttin g anew comma nd is as follows :

1. Look up th e code for the de sired mot o r position.2. Add o n 2'(channel number), hold th e result in CO, say .3. Set th e st robe bit (bit 0) high in CO .4. Output CO to the use r port.5. Set bi t 0 of CO low; output CO to the user port.6. Set bit 0 o f CO high again; output CO to the user port.

Putting the algorithm into softwareLet us adopt our usual technique of def ini ng da ta and a rrays 'up in thesky', with h ousekeepi ng at 10000:

10000 DD ~ 59459:PO ~ 59471 :KB ~ 547:KO ~ 255:R E M ANTIQ U EPET ******

10000 DD ~ 59459:PO ~ 59471 :KB ~ 166:KO ~ 255:REM 8000, 4000PE T ****

10000 D D~ 5 6 ~ 7 9 : P O ~ 5 6 5 7 7 : K B ~1 9 7 : K O ~ 6 4:REMCOMMODOR E 64 • • • • •

100 10 DIM DR(7): REM DRIVE VALUES WITH STROBE ALR EADYHI GH

10020 FOR I ~ O T O7: READ J: D R ( I ) ~16*J + 1: NEXT10030 DATA 1,3,2 ,6,4, 12,8,9: REM N-E- S-W10040 M A~ 2 54 : POKE OD,255 :REMSETTO OUTPUTS

Now we can look at a s ubroutine for drivin g o ne of th e molars . I f the

chann el numb er is se t in var iable C H , whilst the step angle is held as valu e V(meas ured as number of steps from the sw itch-on po sition) , then the following routin e will output lhe requi re d code to th e motor:

9000 CO ~ DR(V AND 7) + CH '29010 POKE PO ,C O : REM OUTPUT THE CODE, STROBE BIT HIGH9020 POKE PO,CO AND MA :REM 'AND' WITH MA SK - STROBE

LOW9030 POKE PO ,CO: REM ST ROBE HIGH AGAIN9040 RETURN

Thi s routine takes one or two sbor t cut s from t he algorithm above, and willsimply set up one motor drive to command a given po sition.

82

Page 86: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 86/133

Chapter 8 Interfacing a Robot

Troubleshooting th e connectionsFor the Armdroid's end of the connections, you wi ll have to refer to thehandbook - the edge-connector has been modified in recent issues_ I f youhave constructed your own ci rcuit (perhap s from the one given later in thischapter) then it should already be familiar to you.

Apart from rea ss uring yourse l f that something will really happen, thenext test will establish which chan nel numbers control which axes of therobot, and in which direction. Enter the following simp le test program_Since it will get progressively overwritten as you work through the chapter ,you might like to save it at eac h stage for future use.

10 GOTO 10000100 INPU T "C HANNEL NUMBER, D1STANCE":CH,DI11 0 FORV=OTODISTEPSGN(DI)120 GOSUB 9000:NEXT130 GOTO 100

10900 GOTO 100:REM AT END OF HOUSEKEEPING

Now check out each of the channels in turn, entering values from 0 to 7 forthe chann el number , and around 50 or - 50 for the distance. Two of theeight possibilities will of course have no effect, since only six channels are

used. Make a caref ul note of the axis and the direction, in terms of up,down, pivot left, right, forwar ds, backwards, gripper open and close. TheArmdroid uses two motors at a time to rotate the wrist, and to swive l thewrist up and down. Make a note of which doe s which. A program with amachi ne -code output routine can afford the time to un scramble sep aratecommand s to twis t and tilt the wrist. In BASIC, thi s make s the sys temrather slow , so here we will at first drive ju st one motor at a time.

Keypress commandsNow let us add a routine so that holding down a key will drive a motor. I t isimpo rtantto display a menu of keys on the screen, showing which key doeswhat - nothing is more frustrating than having to guess. To get smartlooking upper and lower cases legends, pu t the machine into lower-casemode before typing in the program. Of course, when listed in this mode allthe co mmand s in the softw are will appear in lower case, but it is clearer toshow them here in the usual capitals.

Now we must al locate a key to each movement, up, down, Jeft, right,forwards, ba ck, open and close, plu s wrist up and down an d rotate. Thekeys U, D, L, R , F, B, 0 and Care obv ious enough as c hoices, but we mustchoose four more for the wrist - how about W, Q, Tand Y? To each keywill correspond a channel number and a direction. We must add a set ofdata sta tement s to the ho usekeeping to sort them out - use your results

83

Page 87: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 87/133

Page 88: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 88/133

Chapter 8 Interfa cing a Robot

earlie st will operate the faste st. Lo oking througb the program, we see tbatCO, PO, V, Dl, CH, KB and K are used every step, some several times. Ifwe change line 10 to the strange -looking form:

10 DIM CO,PO,V, DI,CH,I ,R, KB,K :GOTO 10000

then there should be a satisfying increa se in speed. (I and R have beenincluded for later use.)

Programmed movementsWhen every move must b e controlle d from the keyboard, the robot isjust a

toy. If, h oweve r, we can program into it a sequence of movements which it can perform automatically, then we can start to explore its serious use. We therefore need to be able to record each target point , and we need a second command level which will let us switch between the 'teach-mode' section (the program we have already tested) and the routines which will drive the robot au tomatica lly. For thi s, we use a second menu start ing at line 100:

100 PRINT CHR$(l47);"Teach, Perform," I 10 PRINT "Repeat, Clear,"

120 PR INT "Save, Input" 130 GET A$: IF A$= ""THEN 130: REM WAIT FOR A KEY-PRESS 140 FOR I = 1 TO 6:IF A$< > MID$("TPR CSI" ,1,1) TH EN

NEXT:GOT0100150 J = I:I =6:NEXT: REM CLOSE THE FOR . . . NEXT LOOP

NEATLY160 ON J GOTO 1000,5000,5 100,2000,6000,7000

So far, we have only written the 'teach ' routine at 1000, and even this needs

some modification . We must allow the selection of any point to be added tothe man oeuvre, and we must allow a return to command mode. We therefore fill in the gaps in the program with:

1060 PRINT"Point End teach"1110 IF A$ = "E " THEN 1001120 IF A$< > "P " THEN 11501130 IF NP = MP THEN lOOO:REMTOO MANY POINTS1140 NP = NP+ I:FOR I =0 TO 5:PT(I,NP)= HE(I):NEXT:GOTO

1000

Now for some more housekeeping. The array PT(5,MP) must be declaredto hold the point s. Th e limit, MP, can convenie ntly be set at 20, but if youwish you can choose a much bigger number.

85

Page 89: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 89/133

DI Y Ro bo tics and Sens ors on the Co mmod ore Computer

10300 NP = O:MP = 20:DIM PT(5 ,MP)

To keep track of progress, we can display the present coordinates and thenumber of points set with:

1080 PRINT :PRINT NP;"POINTS"1090 FOR I = OTO 5:PRINT HE(I):NEXT

That completes the teach mode section of the program. We are left with thetask of writing tbe routine to perform the set of actions.

Routines to perform a manoeuvreHaving remembered the moves, we can perform them by looking up targetpoints in turn, and then calling a routine at 8000 to move from HEre(l) toTArget(l). Ifwe wish to perform them just once, then we can GOTO 5000,and:

5000 IFNP=OTHENGOTO 100:REM NO POINTS5010 ·FOR P = I TO NP

5020 FOR I =OTO 5:TA(I) = PT(P,I):NEXT5030 GOSUB 80005040 NEXTP5050 GOTO 100

I f we wish to repeat the cycle until a key is pressed, then wecan usea sectionof program at 5100:

5100 IFNP=OTHENGOTO 1005110 FORP = 1 TONP5120 FOR I =OTO 55130 TA(I)=PT(P,I):NEXT5140 GOSUB 80005150 NEXT P5160 GET A$:IFA$ = ""THEN 5110: REM NO KEY, ROUND AGAIN5170 GOTO 100

This has still not resolved the problem of what to put at 8000 . For bestspeed of response, we will at first move just one axis at a time, although wewill go on to consider diagonal movements. After declaring tbe arrayT Arget(5) with:

10200 DIM TA(5)

86

Page 90: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 90/133

Chapter 8 Int erfacing a Robol

we can compare eac h channel of TArget against HEre. and. if necessary.move accordingly .

8000 FOR CH =OTO 58010 IF TA(CH) = HE(CH)THEN NEXT:RETURN8020 FOR V = HE(CH) TO TA(CH) STEP SON(TA(CH)-HE(CH»803000SUB9000:NEXT:HE(CH) = TA(CH)8040 NEXT:RETURN

Now. to complete the command routines we can add a 'clear' one-liner:

2000 NP = O:OOTOIOO

and we sho uld also add routines at 6000 and 7000 to record and retrieve aset of movements. For now, plus the lines with:

6000 OOTO 1007000 OOTO 100

and crea te you r own routines when you have cbecked out the re st of theprogram.

As it stands. the pro gram will act as a quite acceptab le robot driver, butthe exec ut ion of the manoeuvres, one axis at a time, will seem inelegant. I t

would be far better to interpolat e the movements with all axes firingtogether. Unfortunately, the program which follows in th e next sec tion isexcruciatingly slow in its performance, and the only really satisfactory wayto achieve the result is by using machine code.

Simultaneous movementsWe want a routin e which will set up all six channel s of the robot. and willinterpolate a manoeuvre so that all cbannels can be made to move at once.This is another task for the binary-rate-multiplier, this time firing on sixcylinders. Our starting position is HEre. an array with six elements, one foreach motor axis. The destination is beld in TArget. and we can workthrough all six axes, fmding which one demands the greatest change . Nowit is a st raightforward jo b to calc ulate the ratios, and to makeastep according to the overflow of a REgi ster, just as in the last c hapt er. We need somemore arrays along the way, and the hou sekeeping routine at 10200becomes:

10200 DIM TA(5).RA(5).WA(5).RE(5)10210 FOR CH = OTO 5:HE(CH) = O:RE(CH) = .5Hl220 V = 0:GOSUB9000:NEXT:REM ZERO MOTORS

87

Page 91: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 91/133

DI Y Ro b otics and Sensors on the Com m odore Computer

Now we can write a subroutine to move all six channels from HEre to theTArget position:

8000 REM MOVE FROM HERE TO TARGET: FIRST FIND LONGEST MOVE

8010 RM=0:FORCH = O T 0 58020 RA( C H) = ABS(TA(CH)-HE(CH»:REM WORK OUT DlS

TAN CEAND

8030 W A(CH) = SGN(TA(CH)-HE(CH»:REM DIRE CTION FOREA C H AXIS

8040 IF RA(CH» RM THEN RM = RA(CH):REM FIND MA XDISTAN CE

8050 NEXT:/F RM = 0 THEN RETURN: REM NO MOVE8060 FOR CH = OTO 58070 RA(CH) = RA(CH) / RM:NEXT:REM RATES NOW IN

RANGEOTO I

8100 FO R R = I TO RM: REM NOW WE AR E READY TO MOV E8J10 FORCH=OT058120 RE(CH) = RE(CH)+RA(CH)

8130 IF RE(CH) < 1 THEN 8160

8140 RE(CH) = RE( CH ) - / :HE(CH)=HE(CH)+ WA(CH)8 150 V = HE(CH):GOSUB 9000 :REM MOVE MOTOR

8160 NEXTCH8170 NEXTR

8180 RETURN: REM NO W HERE = TARGET

Lines 8100 to 8 180 are written with tbe aim of being easy to understand.Some improvement in speed can be made at tbe expen se of clarity. Aft ertrying the first vers io n, try sub sti tuting this:

8100 FO R R= 1 TO RM:FOR CH=O TO 5:1 = RA(CH):IF I = 0 THEN8130

8110 I=I+RE(CH): IFI< I THENRE(CH) = I:NEXT:NEXT:RETURN

8120 RE(CH) = I - I:V = HE(CH) + WA(CH):HE( CH) = V:GOSUB 90008130 NEXT:NEXT:RETURN

8140-8180 are now redundant and sh o uld be deleted.Even if you u se only the program listed here, you will be able to teach the

robot a routine which it will perform with interpolated movem ent s. I stilldon ' t claim that the execution will be fast - you will soon want to performthe binary-rate-multiplier funct io ns in machine code, and include a ramp

88

Page 92: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 92/133

Chap ter 8 In terfaci ng a Robot

p¢iPI. - - - -{P2.

H..,. ,,,,,.....torS N 74- t . . S O ~

h_ _ _ ~ " ~ c.h'lYl'\€l¢ s U ~I I I ( )~ 1

P72!.

+ S v( ~~ < l 7)

4 n - _ ~ s C J . , . ~S s~ ( , € .

' - _ - ' (c . . . . . . . . L')Ov

~ 3 - - r - - - -- - - - -- - - - ~ 4 -- - ~< - - - - -- - - - - -- P S - - 7 -~ - - - - - - - - - - - - - - 1"6

~4 5 12 13

S N )4-LS 1)5Q " " - J . . ~

2 7 10 15

I 2 3 It s

1 ) ( ) X ~ t o n .

t "It; lit '3 ~

•~g

0 .

.,.14-,,;

+ ~ v

O V

(c...

" J l ~.. \too.p ... ,'16 J Y~ , ; ( .\

2 " IS:I " I ' t

4 " 13S " 1"

" 41 / I7 10

Figure 8.1 Circuit for 6-axis robot de co der, latches, drivers

89

Page 93: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 93/133

DI Y Robotics and Sen sors on the Commodor e Computer

speed-up routine to achieve top speed without breaking away. Someelegant programs (eg MEMROB, written in collaboration with Tim Daddand distributed by Colne for using an Armdroid with a PET) link the interpolation and output functions to the computer's interrupt, and commun i cate between BASIC and machine code by planting values in an array ofvariables. In this way, the BASIC part can do its 'thinking', working outthe speed ratios for the next move at the same time as the present move isbeing made. Thelisting ofMEMROB has baffled multitudes, and has littleteaching va lu e.

Building your ow n robot

You will first need half-a-dozen stepper motor s. The ID35 mentioned inthe last chapter will do nicely - it is the one used in the Armdroid. TheDarlington drivers have been covered pretty thoroughly in Chapter 6. Thatleaves only the channel decoders and the four-bit latches - and the powersupply. The supply detailed in Chapter 1 should be adequate, and will costless than a single stepper motor. A circuit diagram for the 'innards' oftherobot is drawn in Figure 8.1, and this should do all that you need.

For a do-it-yourself mechanical design, you can either follow close onthe heels of the commercial robots, or you can be more adventurous. Whenyou start to examine the number of ways you can link six motors together,the choice is amazing. Your geometry can be cartesian, polar, cylindricalpolar or a variety of strange hybrids. Let us start by looking at the 'conventional' robots.

Robot anatomyThe first axis of movement is a rotation of the who le assemb ly about thevertical . You can' humanise' this by thinking of it as swivelling abou t the

waist. Next, the shou lder joint allows the arm to tilt up and down, so that,using these two motors alone, the hand could reach any point On thesurface of a sphere. Next comes the elbow joint. As this bends, the arm iseffectively shortened, although the hand now moves in a way which needsmore and more trigonometry to describe it. In principle, the robot shouldnow be able to reach any point within a sphere, bu t if, for example, theupper arm is not the same len gth as the forearm, there will be some unreachable zones. T he wrist joint should now be able to swivel both up-anddown and left-to-right. The Unimation Puma instead uses a movement likethe human wrist, where the up-and-down hinge is an axis which can in turnsw ivel about the line of the forearm. The Armdroid leave s one of thesemovements out. Now the Puma can in effect lin e up a screwdrive r with ascrew in any position; the final axis twists the screwdriver to drive thescrew.

90

Page 94: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 94/133

Chapler 8 lnter/acing a Robot

Figure 8.2 Axes of a 'c onventional' robot

91

Page 95: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 95/133

Page 96: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 96/133

Chapzer 8 Interfacing a Robot '

Figure 8.4 Cartesian robot arrangement

93

Page 97: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 97/133

P

.JnJps:J!loqo~

A

Page 98: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 98/133

Chapter 8 Interfacing a Robot

Some sophisticated robots, such as the Puma, perform laboriouscomputation s, allowing the user to specify that the hand should move in ast raight lin e and that the tool should not rotate in space. New position s are

calculated for the motor axes up to forty times per second, and themovement is th en smoo thed out by 'rate control', similar to the technique sdescribed earlier. I t is a challenging exercise to try!

Even when the geometry is settled, there are many ways to connect themotors to the axes. The Puma uses brute force, so that the entire leverageof the arm and its load will appear at the shoulder joint. The Armdroid onthe other hand uses a cunning bit of string-work. so that as the shoulderrotates the upper arm. the forearm remains parallel to its former position.This effectively hal ves the leverage of the load on the sho ulder motor

although it do es not do aJot for the string which is annoyingly apt to break .The IBM robot is ca rtesian , and bear s a strong resemblance to an overgrown grap h plotter for controlling the X and Y axes. The Z axis is an evenmore overgrow n pen-lift. raising and loweri ng a bar which can rotate to

provide the first of the wrist axes. All the problems of straight -linemovement are solved at a stroke. but tracks and pulleys are now needed inplace of pivots and levers.

When computing power is let loo se. anything goes. Co nsiderabl eindustrial research is being pu t into developing a device using six exte nding

rods;. driven by motor s and leadscrews. Imagine a triangle ABC fixed to thefloor. with the tool attached to a movable triangular plate DEF. The plateis held up by six rods AE. AF, BF. BD. CD andCE. As these vary in length,so the plate can be moved in three dimensions and rotated about three axes.I f you have an idle moment, calculate the relationship between the lengthsand the position of the plate. or more especially the lengths required toplace the plate in any particular position - a prize is offered for thesimplest solutio n! No wonder it is called the 'Gadfly'.

The se var iations hardly scratch the surface of the possible combinations. If you connect up the six stepper motor channe ls, you can try anynumb er of 'lash-ups' using cardboard. string and balsa wood beforeimmortali sing your design in aluminium or stee l. Good luck!

Robot Control Program

NB. Change line 10000 if using a PET.

10 DIM CO,PO,V,DI,CH,I ,R,KB,K: GOTO 10000 100 PRINT CHR$ (147) ; "TEACH, PERFORM," 110 PRINT"REPEAT, CLEAR" 120 PRINT"SAVE, INPUT" 130 GET A$: IF A$= .... THEN 130:REH AWAIT KEYPRESS

95

Page 99: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 99/133

DI Y R obo tics and Sensors on th e Commodo re Compu ter

140 FOR 1=1 TO 6145 IF A$ < >MID$ ("TPRCSI", 1 ,1 ) THEN NEXT: GOTO 100150 J=I : I=6:NEXT: REM CLOSE 'FOR' LOOP NEATLY

160 ON J GOTO 1 0 0 0 , 5 0 0 0 , 5 1 0 0 , 2 0 0 0 , 6 0 0 0 , 7 0 0 01000 PRINT CHR$ (147) ; "UP DOWN"1010 PRINT"LEFT RIGHT"1020 PRINT"FoRWARD BACKWARD"1030 PRINT"OPEN CLOSE"1040 PRINT"WRIST Q "1050 PRINT"TWIST Y"10 60 PRINT"PoINT END TEACH"1080 PRINT: PRINT NP; "POINTS"1090 FOR 1=0 TO 5:PRINT HE(I ) : NEXT1100 GET A$ : K=PEE K <I<B): IF K=KO OR A$= .... THEN 11001110 IF A$= " E" THEN 1001120 IF A$ <> "P"THEN 11501130 IF NP=MP THEN GOTO 1000:REM TOO MANY POINTS1140 NP =NP+I1145 FOR 1=0 TO 5:PT(NP,I)=HE(I):NEXT:GOTO 10001150 FOR 1=1 TO LEN(C$)1155 IF A$ <> MID$(C$, I , I ) THEN NEXT: GOTO 10001160 J = I : I=LEN(C$): NEXT:REM CLOSE LOOP NEATLY1170 CH= I N T « J - I ) / 2 ) : DI=2*(J AND I ) - I : V=HE(CH)1180 V=V+DI:pOSUB 9000: REM TAKE A STEP1190 IF PEE K (KB)=K THEN 1180: REM KEEP STEPPING1 2 0 0 HE(CH)=V:GOTo 10002 0 0 0 NP=O:GOTO 1005000 IF NP=O THEN GOTO 100: REM NO POINTS5010 FOR P=1 TO NP5 0 2 0 FOR 1=0 TO 5 : TA ( I ) = P T ( P, I ) : NEXT5 0 3 0 GOSUB 80005040 NEXT P5050 GOTO 1005100 IF NP=O THEN GOTO 100

5110 FOR P=l TO NP:PRINT P;5 1 2 0 FOR 1=0 TO 55130 TA ( I ) = P T ( P, I ) : NEXT5140 GOSUB 80005150 NEXT P5160 GET A$:IF A$="" THEN 51105170 GoTo 1006000 GOTo 100:REM PUT 'SAVE' HERE7000 GOTo 100: REM PUT ' I N P u r HERE8000 REM MOVE FROM HERE TO TARGET

8010 M=O: FOR CH=O TO 58020 RA(CH)=ABS(TA(CH)-HE(CH»8030 WA(CH)=SGN(TA(CH)-HE(CH»8040 IF RA (CH) }RM THEN RM=RA(CH)8050 NEXT: IF RM=O THEN RETURN: REM NO MOVE

96

Page 100: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 100/133

Chap ter 8 Interfaci ng a R obo l

8060 FOR CH=O TO 58070 RA(CH)=RA(CH) / RM: NEXT8100 FOR R=l TO RM8105 FOR CH=O TO 5: I=RA(CH): IF 1=0 THEN 81308110 I=I+RE(CH) : IF 1( 1 THEN RE(CH)=I:NEXT:RETURN8120 RE(CH)=I- l : V=HE(CH)+WA(CH): HE(CH)=V8125 GQSUB 90008130 NEXT: NEXT: RETURN9000 CO=DR(V AND 7)+CH(CH)901 0 POKE PO,CO:POKE PO,CO AND MA:POKE PO,CO9020 RETURN10000 DD=56579:PO=56577:KB=197:KO=64: REM CBM 6410010 DIM DR ( 7 ) : REM DRIVE VALUES WITH STROBE HI1002 0 FOR 1=0 TO 7 : READ J : DR(I )=16*J+ l : NEXT100 30 DATA 1 , 3 , 2 , 6 , 4 , 1 2 , 8 , 9 : REM N-E-S-W10040 MA=254 : POKE DD,255: REM SET TO OUTPUTS10100 DIM CH(S) ,HE(S) : FOR 1=0 TO 5 : READ J1011 0 CH(I )=2*J : NEXT: REM CHANNEL CODE10120 DATA 1 , 3 , 5 , 4 , 2 , 610 130 C$="UDLRFBOCQWTY": REM COMMAND KEYS10200 DIM TA(5) ,RA(S) , WA(S),RE(5)102 10 FOR CH=O TO 5 : HE(CH)=O: RE(CH)=.S10220 V=O: GOSUB9000: NEXT: REM ZERO THE MOTORS10300 NP=0:MP = 20:DIM PT(S , MP)109 0 0 GOTO 100

Si mple Dri ver and Channel Identifier

NB. Cha nge line 10000 if using a PET.

10 GOTO 10000100 INPUT"CHANNEL NUMBER,DISTANCE";CH,DI110 FOR v=o TO DI STEP SGN(DI)12 0 GDSUB 90 00:NEXT130 GOTO 1009000 CO=DR(V AND 7)+CH*29010 POKE PO,CO:POKE PO,CO AND MA,POKE PO,CO9020 RETURN10000 DD=56579:PO=56577:KB=197:KO=64: REM CBM 6 410 010 DIM DR ( 7 ) : REM DRIVE VALUES WITH STROBE HI10020 FOR 1=0 TO 7 : READ J : DR(I )=16*J+ l : NEXT10030 DATA 1 , 3 , 2 , 6 , 4 , 1 2 , 8 , 9 : REM N- E-S-W

1004 0 MA=2S4: POKE DD,255: REM SET TO OUTPUTS10900 GOTO 100

97

Page 101: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 101/133

CHAPTER 9· Analogue Output and Position Servos

Despite the advantage of ease of interfacing , the stepp er motor has noabsolute posit ion reference, and ru n s into more prob lems when speedyresponse is nece ssary. Th e analogue se rvo-mo tor can take i ts reference

from a simple pote nti o meter , altho ugh much more so phistica ted devicessuch as sync hros an d enco ders can be used. Th e feed-back signal is su btr acted from the command signal, and the di ffe ren ce represents the positionerro r of the serv o-motor. The servo is now driven in proportion to theerro r , so that it mo ves to red uce it. When the required positio n is reac bed,the motor ceases to require power. On the debit side , if th ere is a standingfo rce load on tbe moto r, it will ha ve a pers istent error, the va lue o f errorneeded t o give a dri ve eq ual to the force. To minimi se thi s error , th e se rvo'loop' must be ' st iff ' , that is t o say, a small error mu st give a lar ge motor

torque . Thi s rai ses even more problems , since a small e rr or ca n causeenough to rqu e fo r the motor to pick up speed, and sp rint p ast th e targ et toco me to rest with a large r error on the other sid e . Then of co ur se it spinsback agai n , and again . . . The servo ha s s tart ed to osci llate.

Feedback and st abilityTo avoid osci llati on, either the stiffne ss mu st be redu ced o r a velocitysigna l mu st be ad ded . A veloc ity ter m winds down t he motor driv e as itpicks up spee d, so tha t for any giv en error there is a speed at which tbe servo

is content to freewheel.I f

the freewheeling spee d i s excee ded, tbe se rvodrive acts in reverse to slow dow n tbe motion. Thus, if th e right mixture ofpo sition and veloci ty is made, the servo co mes briskly to rest at the desiredposit ion. A velocity or ' tacho' sig nal can be expensive, but there are waysof obtaini ng a similar effect more cheapl y. A certain amount of velocityfeed-back comes from the motor it self, in the form of the 'back-e.m.f.'generated by the rotation of the DC moto r . Thi s lim its the speed up towhich the motor w ill run in response to a given amplifier output voltage,and adds the necessary dose of dampi ng to a low-sti ffn ess sys tem . As the'gain' of th e co ntrol loop (ie the volta ge out per unit of position error) isincrea sed , so this self-dampi ng becom es less effect ive. In th e limit thesystem is ' bang-ba ng' , driving flat out for tbe slightest error, and, withoutth e additio n of a ve locity signal to the in put of tbe amplifier, osc illa tion isinevitab le .

99

Page 102: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 102/133

0

t

.~

~

i(1"~~~)'II~J"C

O"~""OJf~

J

'~

?

JOO>A

Page 103: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 103/133

Chapter 9 Ana/oglle Output and Position Servos

A high-power sophisticated servo will have a separate tacho to give aspeed s ignal. H owever, thi s need be no more exotic t han anoth er muchsmaller motor connected to th e main motor shaft and ac tin g as a voltage

ge nerator. This sort of system is simpl e to design , a nd can be madeext reme ly s tif f, but for educatio nal robots the cost of doubling-up on themotors is worth avoiding .

Phase advanceSo w hat ot her possibilities are there? A sub stimt ial increase in stiffness,retaining stability, ca n be obtained using 'p ha se-advance'. The feedbackre sis tor i s s plit into tw o series resistors, and a capacitor is connected across

one of these. Since the current in a capacitor is proportional to rate-ofchange of voltage, the feedback signal current into a 'virtual-earth'amplifier will include a term due to rate-of-change of error position - avelocity term. Unfortunately , phase-advance also magnifie s the effect ofany no ise o n the signa ls, and, if the motor s are driven from the same powersuppl y that energ ises the po sition potentiometer, yo u will soon find oscillation s aided and abetted by the power suppl y lin es themselve s.

Tacho signal from back-e.m.f.A more cunniog technique is to use the motor back-e.m.f. again, but toseparate it from the vo ltage ca used by the drive CUrrent. This involves theuse of a resistance bridge and a differential amplifier - in fact, consis tingof no more than three resistors to complete the bridge, and oDe moreresistor plus a fifty pence TL081 chip. This can be very effective if enoughcare is taken to balance the bridge, but setting up can be fiddly.

A simple circuitBefor e you leap into action and start to construct a se rvo system, it is onlyfair to warn yo u that the analogue output technique which follows will onlywork for the PET . Read to the end of the chapter, and you will find othertechnique s described.

For now, be co ntent to pu t together a slightly less c risp servo system,which will probably do all you need. A servo module containing motor,gea rbox and feedback potentiometer can be bought from a model shop for£10-£20. Th e motor used to tryout this design was aSkyleader SRC 4BB.A drive amplifier can be made from a single-chip 759 power operati onalamplifier (RS number 303 - 258), and the power supp ly described inChapter 1 can be connected to give + 7V (or so) and - 7V outputs. Youronly problem is how to obtain an analogue drive signa l from your

101

Page 104: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 104/133

DI Y Robotics and Sensors on the Commodore Computer

M.t... .l"'",e.'R4

'Rl 'R.

'Rs. ~ ,'R ..

> ' O-rcJ..o

O " " ' ~

~ s i\. coJ)t.I..sWto ",ok 'Rs = ~ I ' \ J

~ 1<,w ....... r .... t ~ - . . ~ , . , .r - e . ~·' s t ~.

~ " l~.. J - . o ~ " ,t ;k . w!> tt:.......r" , tA o N O ~ , j

toss 01-M O ~ rr..;U- ·

O ~ / A , t ~ ~ ~ ~ } .. Wf. ."',+,~ , 1.\ .... r,..

( F..,. /0 ~ ,•••;t"" tv7 "R., ~ 1 ·}.tL , It(;-"-1. . 1. JUL

It,:: fa i th I R L : . l ' f / d L , I t s : I k J L r s t ~...

r.u .... ' ~ , ' . )

Figur e 9.2 T acho signal from mol o r b ac k e .m .L

102

Page 105: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 105/133

Page 106: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 106/133

V

t.~

1-~w

-()~~ ~<

~~-

U "

l,.

l ..~

c" ~- 'n 'lC w

t r'. :

~0.

" ='CrI

'"

~:

'"~ ~'

J~,e:> V.r

~~~~~I",

JJA

Page 107: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 107/133

Chapter 9 Analogue OU lput and P osit ion Servos

100 FOR V = OT0255:V07. = V:GOS UB lOOO:NEXT110 GOTO 100: REM OUTPUT A REPEATED RAMP

1000 A = V07./32:B = V07. AND 31: REM SPLIT UP V 07.

1010 FOR I = I TO 20: REM TRY VARYING TH E LOOP1020 C = A: S = S + B1030 IF S> 31 THEN S=S-32 :C = C + I: REM NEXT PATTERN UP

1040 POKE PO,PA(C)1050 NEXT I:RETURN

If you enter and run thi s program, and connect your tru sty meter (6V scale)between CB2 and OV, you sho uld see th e needl e repeated ly climb slowly to5V and then dr op again. Notice that the program spend s most of it s time ina loo p, and any t ime that it needs to p erform a lengthy calculation, theoutput will take one of the nine ' stead y' output values - any servo wouldtwit ch by up to thirty degrees.

Interrupt·driven outputTo avo id the need for a loop in the program , the interpolation (ie averag

ing) can be done with an interrupt. The BASIC pro gram goes its happyway, and , every time a certai n timer give s a pul se, the co mputer 's attentionis di verted to an interrupt routine.

Fi rst this store s away the status and all n ecessa ry reg ister s, then the processo r leaps into the appropriate bit of machine code. Aft er executing this,control must return to the tail-end of the interrupt routine which restoresall the registers and status, carrying on with the original program as thou ghnothing had happ ened. The interrupt routine can now look up the value of

V"I. as save d by the BAS IC program, split it and average it , outputting a

new pattern every time an interrupt occurs. Th e output appears as if bymagic, fo llowi ng each and every change in the va lue of V07. with noapparent output command.

Such an interrupt occur s in the PE T (and in the 64 too) sixty tim es persecond . It s norm al purpose is to scan t he keyboard and update the timeTI$. A fter saving all the registers , the machi ne ma kes an indir ect jump toan address held in locations $90 and $91 (144 and 145). A new piece of

software can be 'plugged in' to the interrup t routine by planting its ad dr essin these locat ions. At the end of th e new rout ine, a jump must be made to

the origi nal add ress so that th e keyboard hou sekeepin g gets done .Plantin g the new addre ss requires rath er special ca re: if only one of thelocat ions has been chan ged when an interrupt occurs, a cras h is almostinev itabl e. The addres s must therefor e be planted by means of othermachine- code program which temporarily inhibits int errupts. (To see the

105

Page 108: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 108/133

DIY Robot ics and Sens o rs 0 11 the Commodore Computer

sort of thing that can happen, make sure that any useful program has beensaved, then POKE 145 with any number which takes your fancy.)

Th e next problem is to make some space for the machine code to occupy.When the code is held as a set of data statements for planting by part of aBASIC program, the sewnd cassette buffer will do very well (apart frombeing.trampled by any disk commands). For something used more often, itis preferable ,to be able to save,away both BASIC and machine-code partsin an instantly usable form . If the first line of the program is:

10 POKE41,5: RUN

then the start of BASIC is lifted to $0501, where the main program canreside. The direct command

POKE41,5: POKE 5*256,0: NEW

sets up the po inter s to enable you to type in the rest of the program, leavinga gap of over 200 bytes in which to plant your machine code.

Th e first line of the upper BASIC program must be

10 V"7o = O

so that V% is the first variable of the program. The machine code can nowfind it through the pointers at $2A, $2B (42, 43). Next comes a call SYS 1056to the machine-code routine, which sets up the interrupt links . This swapsthe addre ss of the jump which ends the interrupt with the addre ss alreadyheld in $90, $91. (Tbe metbod works for 3Oxx,40xx and 80xx series PETs).tailing tbe same SYS addre ss will now swap them back to normal again.

20 SYS 105630 POKE 5946 7,16:POKE59464,0

100 INPUT "NEW VALUE (0 TO 255)"; V%110 GOTO 100

Apart from the machine code, that's all there is to it! Instead of inputtin gva lues, you can o utpu t a ramp as before - no need for the POKEcommand though, and subroutine 1000 merely becomes a brief delay loop :

1000 FO R I = 1 TO l00:NEXT:RETURN

Otherwi se, perform any sort of comp uta tion, such as:

100 FOR 1= 1 TO 10000110 V% = 128 + 127*SIN(1I100)120 NEXT: GOTO 100

106

Page 109: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 109/133

Page 110: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 110/133

DJ Y Ro b otic s and Sensor s on the Commodore Computer

POKE 41,4

This sets th e start-of-BASIC pointer to normal, and you can save th e pro

gram on cassette or tape in th e normal way.Whilst you can type in th e machine code without needing to understand

it, 1 am sure that you will prefer to see what it consists of . The PLANTroutine starts at $0420

0420 PLANT SE I0421 LDA0424 LDX0426 STA0428 STX

042B LDA042E LDX0430 STA0432 STX0435 CLI0436 RTS

0438 DTOA LDY043A LDA043 C LSR0430 LSR043E LSR043F LSR0440 LSR0441 TAX0442 LDA0444 AND0446 CLC0447 AD C044A CMP044C BMI044E IN X

044F AND0451 NOMORE STA0454 LDA0457 STA

045A 1 IMP

045D S BYTE

hence th e SYS 1056.

1+1$90$901 + I

1+2$9 1$911+2

1+3($2A),YAAAAA

($2A),Y1+$IF

S1+ $20NOMORE

1+$IFSPA,X$E84A

DTOA

0

;INHIBIT IN TERRUPTS;SWAP JUMP POINTERS

;PERMIT INTERRUPTS;END OF PLANT , RETURN

;READY FOR V'Io;LOAD VALUE OF V'Io

;DIVlDE BY 32;PARK IT;GET vo/, AGAIN;MASK WITH 31;CLEARCARRY;ADDS;OVER31?;NO;INCREASE OUTPUT ONENOTCH;CHOPDOWNS;SAVENEWS;LOAD X'TH PATTERN;PLANT IN SH IFTREGISTER;NOTE : THIS IS NOBBL EDBY;'PLANT' TO POINT TOTH E REST;OF TH E NOR MALROUTINE .

045E PA BYTE 0 , 1, 17,73,85,182,23 8, 254 ,255

108

Page 111: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 111/133

Chapter 9 Analogue Output and Position Servos

Driving radio-control servosIf you ha ve ploughed t hrough the preceding sect ions, you may feel that it isunfai r to wa it until n ow to tell you that there is another way to go abo utdriving a servo. Thi s method i s a favouri te of Alan D ibley, who uses it withdevastating eff ec t for bu ildi ngMicromice. What is more, 64 ow ners wi ll beglad to learn that they can use it too - although t hey lack the machine-codemonitor which makes loading the PET so easy.

For radio contro l, you can buy a serv o-motor off -the-she lf completewith drive ampli fier. There is no need to worry about fee dback, s tability ortacho s ignal s. Th e motor com es with a thr ee-w ire co nnecti on: two are forpower suppl y wh ilst the third is the co mm and input.

Command s to the ser vo take the form of pul ses every 20 milli seco nds orso. T he width of eac h pulse determines the commanded position, one mill isecond giving full scale one way, varying to two milliseconds for f ull scalethe other way. Once again we can u se an interrupt to repeat the mo tor

output, and we can again use the dodge of comm unicat ing with the interrupt routine hy savi ng the value in VOfo. Now C B2 wi ll give an output in theform of a tra in of pul ses , and ca n be co nnected to the servo com mandin put.

Radio-control servo programTo avoid t he loading probl em, let us revert to the technique of Chapte r 5, inwhich the ma chine cod e is defined by data statements within the BASI Cprog ram. Th ese will be plant ed in the cass ette buffer by the loader and hexto -dec imal co nve rter at 10000 onwards:

10 V% = O:GOTO 10000

10000 MC =3*16-2+

9*16 :1= MC:

REM $039010010 READ A$:IF LEN(A$)< > 2 THEN 100 :REM DONE IF XXXX

10020 GOSUB 1010010030 PO KE I ,A: PRI NT I,A$ ,A10040 I = I + I : GOTO 10010

10100 A=ASQA$) - 4 8 +7*(A$> ":") : REM CO NVERT FROM HEX

10110 B$ = MID$(A $,2) 10120 A = 16*A + ASC(B$) - 48 + 7*(B$> " :" ) 10130 RETURN

Now we can also simplify matters by using one of the user port dat a bits, rathe r than CB2 . As before, the re will be seve ral dif fe rences between PET and 64, so both sets of data statement s will be given:

109

Page 112: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 112/133

O

r3o

=o.

o

o.o

;S..=

.

0

"o"-"-

o<

Q

JUUSpA

Page 113: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 113/133

Page 114: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 114/133

DI Y Robotics and Sensors on the Commodore Computer

10360 DATA 80,0 1, DO :R EM STA PORT HIGH10370 DATA CA :REM LOOP DEX -COUNTX10380 DATA DO, FD :RE M BNELOOP10390 DATA A2, 7F :RE M LOX #127 ' VARY TOGlVE

1 MS10400 DATA CA :RE M LP2 DEX10410 DATA DO, FD :REM BNE LP210420 DATA A9, 00 :REM LOA #010430 DATA 80,0 1, DO :REM STAPOR T - CLE AR10440 DATA 4C, AB, 03 :R EM J 1MP D T OA - GETS NOBB LED10450 DATA XXXXX :REM END BY PLAN T

Now we need to set bit 0 of the port as an output, an d to wake up theinterrup t , and we are ready to go:

100 POKE 59471,1 :REMIFPETor

100 POKE 56579, I :REM IF 64

11 0 SYS M e :RE M WAKE UP

Now the servo sh o u ld respond to any value saved in variable V%, and youcan use th e following program as a simple test:

1000 FOR I =OTO 2551010 V"lo= I: REM YES, THAT'S ALL IT TAKES1020 FOR J = I TO 100 :NEXT: REM BR IEF DELAY1030 NEXT I1040 GOTO 1000:REM OUTPUT ANOTHER RAMP

When you press BREAK after running th e program, the compu ter willcarryon outputting V% on interrupt. To reset to normal, type:

SYSMC

as a d irec t command.

Analogue Output for P ET - Ba sic

10 V% =0 :PO =5946620 DIM PA(8):FORI=OT08:READ PAtI ) :NEXT30 DATA 0 , 1 , 1 7 , 7 3 , 8 5 , 1 8 2 , 2 3 8 , 2 5 4 , 2 5 540 POKE59467,1650 POKE59464,100

11 2

Page 115: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 115/133

C ha pl er 9 Ana/oglle O utp ut an d Posi tion Se r vos

100 FOR V=O TO 255:V7.=V:GOSUBI000:NEXT110 GOTOI001000 A=V7./32:B=V7.AND31

1010 FORI=1T0201020 C=A:S=S+B1030 IFS >3ITHENS=S-32:C=C+l1040 POKEPO,PA(C)1050 NEXT:RETURN

Pulse-width Servo Output - PET

10 V7.=O:GOTO 10000100 POKE59471,1 :REM **** PET110 SYS MC

120 INPUT"POSITION DEMAND (0 TO 2 5 5 ) " ; Vi(130 GOTO 12010000 MC=3*16 " 2+9*16 : I=MC10010 READ A$:IF LEN(A$) <> 2THENI0010020 GOSUB 1010010030 POKE I ,A:PRINT I ,A$ ,A10040 I=I+I:GOTO 1001010100 A= ASC(A$)-48+7*(A$ >" : " )10110 B$=MID$(A$,2)10120 A=16*A+ASC (8$) -48+7* (BS >" : " )

10130 RETURN10200 DATA 7 8 , AD,CO,03, A6,90 , 8 5 , 9 010210 DATA 8E,CO,03 , AD,CI ,03 , A6,9110220 DATA 8 5 , 9 1 , B E , C l , 0 3 , 5B, 6010310 DATA AO,03, Bl ,2A , AA, EB, A9,0110320 DATA BD,4F,EB, CA, DO,FD, A2,7F10330 DATA CA, - DO,FD, A9,OO, BD,4F,EB10340 DATA 4C,A7,0310350 DATA XXXX

Pul se-width Servo Output - CBM 6410 V7.=O:GOTO 10000100 POKE56579,1 :REM **** CBM 64110 SYS MC120 INPUT"POSITION DEMAND (0 TO 2 5 5 ) " ; V7.1 3 0 GOTO 12010000 M C = 3 * 1 6~ 2 + 9 * 1 6 : I = M C

10010 READ A$:IF LEN(AS)<>2THENIOO10020 GOSUB 1010010030 POKE I ,A:PRINT I ,AS,A

10040 I=I+l:GOTO 1001010100 A=ASC(A$) - 4B+7*(A$ >" : " )10110 B$=MID$(A$,2)10120 A=16*A+ASC(B$)-4B+7*(BS > " : " )10130 RETURN

113

Page 116: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 116/133

Page 117: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 117/133

CHAPTER 10

Simple Robot Vision

Much of the work described in this chapter forms part of the research of AliHosseinmardi. Its publication here does not prejudice his claim to originality. The simp lest vision system has been taken up by Upperdata Ltd, andis being marketed for the incredible price of £50.00. I f you are industrious,you can build your own 'eye' from scratc h using the information here, butyou might well take the lazy way out.

Provocative instrumentationThe techniques of capturing analogue signa ls within the computer aremany and various, and the computer is fast replacing the instrumentation

recorder in process plants. Traditional instrumentation has been concerned w ith developing sensors which will respond to temperature,pressure, level, acidity, etc., and building them into systems which will givea steady voltage or current proportional to the quantity being measured. Inmany present computer applications, electri cal signals which otherwisewould have driven charts or pointers, are dangled under the computer'snose, to be sampled at leisure. But the computer is capable of better thingsthan this.

The computer can perform experiments to obtain the data it needs, pro

voking th e s ystem to obtain a response - hence the term I have coined,provocative instrumentation. The vision system is a prime example. Asighted man will analyse the signals which happen to arrive at his eye. Theblind man must tap about with his stick, building up an image of his surrounding s from the responses. This image may be less detailed than thesighted on e, but it is much better than no image at all.

The Cyclops vision system equips the robot with just one single focussedphotoce l1 - the blind man's stick . Thi s one point of vision is scannedabout by tbe robot itself, enabling a picture to be built up. The slow way is

to drive the robot in a raster scan, al10wingthe leve ls of grey to be written tothe display screen to build up a conven tion al image. More interesting is thetechnique of allowing the robot to fo l1ow the edge of any contrasting feature, so that the image is analysed for shape even before it is completelyinput. One or two cunning techniques allow features to be fol1owed even

115

Page 118: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 118/133

DIY Roboti cs and Sensors on the Commodore Computer

when they are grey-on -grey, and even when the unevenne ss of the illumination represents more intensity variation acro ss the field of view than thefeature itselL

Making the vision systemAs Mrs Beeton n ea rly said, 'Fir st cat ch your robol.' You will need so memeans of deflecting the lens and photocell t o scan the view. You ca n attachthe eye to the forearm of a ready-made robot such as the Armdroid, or youcan relati vely easily make up a special two-channe l deflection sys tem; itcould end up looking much like the home-made joystick, but with stepper

motors in place of the potenti ometers and the eye in place of the joystickitself. Unfortunately, the step per motor steps are rather large, andtwenty-four half-steps will cover a full ninety degrees. You will th ereforeneed to find some way of gearing down the movement, either with conven·tional gears or with a simple string and pulley system. If you overdo thegearing, you can always modify the software to give you a number of stepsof movement between sample points.

The eye is no more than a lens, a tube, a photocell (OP500 will do nicely)and a connecting cable. Fo r machines similar to the PET, some extra

circuitry is provided in the commercia l version to give analogue-lo-digitalconversion (very similar to the system described in Chapter 5), but formachines with the foresig ht t o provide a built-in converter, thi s is hardlynecessary. In strong li ght, an OP500 can be connected directly to one of thepaddle inputs of the 64, and for lower light levels a single transistor and lworesistors can be added.

The lens should be 10 dioptre s or alittJestronger - ieshould have a focallength of 10 cm or less. A simple plastic magnifying glass could be ideal. I f

you are too serious to u se a Smartie tube to mount it in, a roll of paper can

be held together with draughting tape. Once the photo ce ll is fixedat

thefoca l point and the tube is attached to the robot or scanne r unit, littleremains except the software. To check ou t your connection s to the eye, andto make sure that the resistor is appropriate to the light level, you can key inand run the one-liner:

10 PRINT PEEK(54297):GOTOIO:REM CBM 64

For the PET, you would have to key in line 10 and lines 10000 onwards of

Chapter 5, and then test the value with:

100 CH"lo = I:SYS MC:PRINTV"lo:FOR I = I TO 500:NEXT:GOTOIOO

116

Page 119: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 119/133

Chapter 10 Simple Robot Vision

Figure 10 .1 Mechanical mounting for eye

117

Page 120: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 120/133

DIY Roboti cs and Sensors 011 the Commodore Computer

But if you use the user port for reading the photocell, where can you attac hthe robot? In fact robot vision is rather hard for the PET owner, notbecau se of any problems in detecting the image but because of the lack of

graphic s for displaying it. I f you are prepared to accept a black-and-whitescene, then you can s imply co nnect the OP500 to an LM339 comparator,set the threshold with a potentiometer, and read the light level with a singlePEEK . To leave the u ser port clear, co nn ect the eye to the cassette port,stealing the LM339 's + 5V from pin BI2. Th e output is now attached topin F/ 6, usuall y used for reading the cassette switch on pin PA4 of the6520 PIA. This port appears at address $E810, and so the input can be readby PEEK(59408) AND 16. I t is this technique which is descri bed in Figure10 .2.

Two vision strategiesA quick and effec ti ve way to transfer an image to the screen is by means ofa ra ste r scan. The eye is scanned to and fro, movin g steadi ly downwards,whilst a blob, havi ng a n intensity corresponding to the photocell signal, iswritten on to the screen at each point. In principle, one scan line can bemade from lef t to right, whilst the next is right to left. In practice, thebacklash will cause alternate lines to be slightly shifted, and so a conven

tional raster is.preferable. Now tllere are two nested FOR . . . NEXT loopsto command the motor movement . The light level is read at each point, anddivided by a scale factor to give a result in a ran ge, say of 0 to 7. Th isnumber can be used to select a character from a st ring of increasingly den sesymbol s , which is then written to the corresponding screen po sition. Alternatively, the value can be u sed to select the foreground colour, and a character written which is a solid b lock of colour. When displayed in black andwhite, the right c hoi ce of colours will appear as a grey scale - you willhave to use an array as a conversion table for deciding the co lour s, but that

is easily dealt with.An edge-following program is much more interesting. You can exploitthe full resolution of the photocell, to detect edges which are light grey ondark. Let u s start off by assuming that the picture is thor oug hly black andwhite. We wish to mo ve round the boundar y of a white area , keeping blackon our left and white on our right. Obviously, since we can only look at onepoint at a time, we will have to keep zig-zagging across the boundary tomake sure that we do not los e it. A strategy tha t Ali and I have foundeffective is as follows .

Imagine that you have a compass drawn on a sheet of paper, with Northand East marked. You are standing on an array of square tiles. The tile youare standing on is white, and you are facing North (as marked o n the compass) along a row of more white tiles. On the paper are written the following rules:

118

Page 121: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 121/133

Chapter 10 Simple Robot Vision

L t . M

10k.. . '"'f""'_.Ls <O-t<.<IvJ..,,) to ~ U: +$'",+t;v

l IK

"l.N l ) O ~

OPSDO p<>tx1'0* X

r

OP5DO O V

- F w ~ U - ~ U !=='o-v~ ~ U -

Figure 10.2 A low cost 'eye'

119

Page 122: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 122/133

Dry Robotics an d Sensors 0 " the Commodore Computer

1. If you are standing on a white square, rotate the compass 45 degrees tothe west. T ake a step 'Compass North', to the centre of the nextsquare.

2. I f yo u are sta nding on a black square, rotate the compa ss 45 degrees t o

the east. Take a step 'Compass Eas t ' , to the centre of the next square.

If you follow lhe rules , you will turn half left and step forwards - diagonall y . If this square is black, yo u will turn half right (now facing you roriginal direction) and take a sid eways step to the right. You are now juston e square in fro nt of your or iginal position. I f there is a row of blacksquares to th e left of your row of white tiles, you will zig-zag forwardsadvancin g one square each two moves. I f your white sq uar e co me s to anend, you will keep on turning half right until you again reach a whitesquare , and so you will turn any corner of the boundar y. It ' s hard toexplain, but easy to program.

Now, how ca n the strategy find an edge in a varying shade of grey? Thetechnique involves setting up a local THreshold level, midwa y between'Local-Black' and 'Local- White' . I f the point you are now looking at is

blacker th an Local -Black, then Local-Black is immediatel y modified tothat value. Similarly Local- Whit e is immediately changed if a whiter-thanwhite point is found. If the level lies somewhere between these values, thenboth values are allowed to edge inwards slightly , by assignment s such as:

LB = LB + (fH - LB)120:REMTHRESHOLD - LOCALBLACK

In this way, tbe black / white decision is made about a thr esho ld which canfollow the variations of illumination across the image. Ali's experimentalset- up can trace the outline of a black letter, even when another sheet ofpaper is placed over the top of it - but the robot is apt to chase off after acrease in the paper.

By now you s hould ha ve enough clues to write your own edge-followingprogram, after you ha ve tried out the raster program given below . I t is hardto say when such a program is comp lete, since having ca ptur ed a set ofdata-point s representing the edge of the object, these need smoot hin g to

remove the 'hem-stitch' pattern. They can then be processed to removeirrelevant points - straight lines can be sufficiently well represented byone point at eacb end, and a littl e cunning can reduce the outline of a Kfrom several hundred points to fourteen. (Somehow the program seemsunable to manage eleven.)

120

Page 123: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 123/133

Page 124: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 124/133

DIY Robotics and Sensor s On the Commodore Comp u ter

1030 POKE CC+40*RO + CM,CC(pEEK(EY)*LS):REM SETCOLOUR ••• 64 ONL Y

1040 PRINT" ";:REMPRINT(REVERSED)SPACE*"640NLY1050 X=I:Y=O:GOSUB 6000 :REM CAN CHANGE X VALUE TO

SCALE1060 NEXT CM: RE M NEXT COLUMN1070 X= -20 'X:Y = -1:GOSUB6000:REMSCALEYVALUETOO1080 NEXTRO1090 X = O:Y = -2S 'Y:GOSU B 6000:REM MOVE BA CK TO START1100 GET A$:IF A$ = " " T H E N 11001110 GO TOIOOO

For the PET, line 1040 is omitted and line 1030 become s:

1030 POK E CC + 40'RO + CM,32 + 8*(PEEK(EY) AND 16)

which will plant a space if the input is low, and a reversed space if high.This should be enou gh to transfer a view to the screen. If you are using a

television set as a monitor, turning the colour right down will give you agrey scale. I f your set is black-and-white, you win hand s down!

Of course, that famous law will ensur e that the photocell will start off

pointing in the wrong direction. You will wa nt to add:

200 PRIN T CHR$(I47);"SET EYE TO TOP LEFT OF SCENE"210 INPUT "MOVE RIGHT HOW MANY? ";X215 INPUT " MOVE DOWN HOW MANY ? ";Y220 GOSUB 6000230 INPUT "OK?";A$:IF LEFT$(A$,I) < > "Y"T H EN 200

As soon as you are able to capture an image in the computer, a new world

opens up in which you can try edge processing, image matching, twodimensional filtering, and a variety of advanced techniques which are thesubj ect of cur rent research. The computer may fall short of 'real-time'analysis by a factor of hundr eds in speed, and the 'pixe l' resolution ma ynot be marvellous, but the principles of any strategy should be within thecapab ilitie s of the machine.

122

Page 125: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 125/133

CHAPTER 11

Whatever Next?

I t ha s taken a lon g time for the great computer manuf acturers to acknowledge the existen ce of the micro. Despite their efforts at ignoring it, itwouldn't go a way. At first, low-cost microcomputer systems were littlemorethan toys, so obvious ly handicapped by their eight-bit inferiori tythatthey couldn't ever threaten the mainframe - or could they? Their accessibility attracted many people to software writing, some of whom wouldcringe at the tag 'computer scientist', and, before lon g, a wealth o f ingeniou s packages were hitting the market , ranging from word processors tosp readsheet calculators, from pa yrolls to catering analysi s. As the supplyof peripherals moved upmarket in performance and downmarket in price,it became obviou s that the micro was no mere lightweight but was set t o

become th e cor n ersto ne of commerce - warranting numerou s co mmer

cials every night on television. When sixteen-bit chips appeared, the giantsstarted to sti r - alt hough their software was mainly based on transcriptions of eight-bit routines and seldom gave any speed advantage. Now themainframe m a nufacturers are scrambling to integrate micros into theirmarketin g str ategies.

Th e same story is starting to unfold for robots.

Robot evolution

Production enginee rs have long been familiar with numerically co ntroll edmachine tool s . Controlled by barbaric mean s such as punched paper tape ,these are identical in concept to the rest of the industr ial robots. Instru ction s programmed once are repeated to produce a strea m of identical product s. Change the instructions, and the same expensive machine tool canproduce a different product - the sta rt of a flexible manufacturingsystem . Only when the anthropomorphic robot arm appeared did the term' robot ' gain general acceptance for this type of automation, a name carriedby the IBM robot which is more like the arrangement of a milling machinethan like a human arm. Indu strial robots in this league carry price tags of

tens of thousands of pound s, and a vision system may cos t several timesmore .

Th en the educatio nal robots appeared on the scene. A few hundredpound s cou ld buy a rather tinny device, admittedly resembling a toy

123

Page 126: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 126/133

DIY Robolics an d Sensors on the Commodore CompUler

version of the business end of a JCB. This could be connected to almost anyHigh Street microcomputer to allow it to be programmed in a way resembling its larger cousins. Its lifting power was practically zero and its speedwas not remarkable , but robots were no longer the exclusive property of

major indu str ies. Even to these humble devices, sensors could be addedand linked with programs which leaned towards intelligence. As smallfirms (and some large institutions) experimented with the po ssi biliti es of

cheap automation, it became clear that a demand wa s growing for therobot which could combine relative cheapness with a usable performance.Just as the micro co mputer grew to fill its market place, so the micro robot isstretching its muscles to find industrial application. Unlike its upmarketforebears, the micro robot is not shackled to obsolescent and expensiveminicomputers; it can exploit the latest and cheapest microcomputer technology. Complete with computer, language and performance to matchtoday's market leaders, a new generation of robots should be priced atunder £5,000.

Availability of robot-power is only half the story, as far as industrialexploitation is concerned. Few applications as yet employ a fraction of thesophistication of which the robot is capable, and a shortage of able robotprogrammers means that 'teach-and-repeat' programming is the mostcommon. The end of this problem is in sight, though. With the microcom

puter ha s grown a generation of youngsters made familiar in school and athome with micro programming. Some have made fortunes as entrepeneurs, others have found sadly that computer programming can be aslowly paid as sho rthand typing. As micros throughout schools and homesbecome equipped with robots, so another generation will take industrialautomation in its str ide. Soon every back-street workshop will be able toafford a robot or two, and there will be expertise in plenty to set them up.For a while, however, experience with robots will be a highly prizedcommodity, and I hope that this book will give you a start.

Robot intelligenceThe definition of a robot can be broadened to embrace any machine whichis a 'robotnik ' - a worker. I t is not hard to include automatic wa shingmachines and dish -washers, which after all measure such variables aswater level and temperature and apply programmed control accordingly.Although a micromouse does little work, it is s ur ely a robot. The micewhich have struggled to the centre of the Euromicro 'Euromouse' maze

have used sensors and actuators with a large amount of intelligence - ifonly by proxy from their designers. Indu strial robots too are starting todepart from the 'do just as 1 tell yo u' image, and apply correctio n andadaptation to the way in which they perform their tasks, in order to achievea more generally specifie d goal. (With some difficulty I suppress an urge to

124

Page 127: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 127/133

Chapter J J Whatev er Nex t ?

go into the details of the 'Craftsman Robot' project, for which my group atP o rtsmouth Po lytechnic is receiving support from the SERC.)

The major maze-solving algorithm was estab lished by Nick Smith, first

Eu romou se c hampion in [980. I t invol ved allocating numb ers to thesquare s, s tartin g from zero at the centre. An y square accessible from thece ntre wa s numbered one, any square accessib le from a one- square wasnumber ed two, and so on. As new walls were found, link s to [owernumbered sq uares were broken, and the va lues ' floated up'. Th e best wayto the centre was found by following the number s downwards - until anew wa ll wa s met. A pedant would insi st on calling the techniqu e ' recursivedynami c pro gramming ' . Micromice then start ed to wi n by agility andespec ially re liabi lity. David Woodfield 's 'Thumper' still performs

impeccably two yea rs after its [981 victory. Alan Dible y has introduced theconcep t of th e 'economy mouse'. Cutting the keyboard of f the cheapestavailab le micro, he mounts it on a plywood or bal sa fram e co ntrolled byco mmer cial mod el aircraft servos. Using the technique mentioned inChapte r 9, he achieves a considerable measure of sucess - although notenoug h of lat e to defeat the Finni sh ch am pions. Of particular signific anceis the appearance in the co ntest of school team s, even making the pi lgrimage to Madrid . Th eir mice may leave a lot ofroom for impr ove ment, bu tthe pattern h as been set. A school team might even become the Copen

hage n champions , to go on to an expenses paid trip to co mpete in Japan'sown contes t.

Robot ping-pongNow aco ntes t is needed which can try th e mettle ofthe robot profes sionals.[ h ave proposed a contest of robot ping-pong, and have already receivedseve ral dozen ser iou s enquiries from potential contestants (or shou ld I saypotential d esigners). The date for the firs t match was at fir st set for 1986,

butthi s will no w almost ce rtainly be brought forward to [985. The contestis not as fa r-fetche d as it ma y fir st appear. The table is a mere half-metrewide, and is two metres long . Hal f-metre square frames at each end andabove the net rest rict t he allowable m ovement of the ball, and reduce thearea which the robot s mu st be able to reach . The net is a quarter metre hi gh,and thi s in turn mak es a slam a recipe for losing a poin t. Simulations showthat in order to make a return difficult, a ro bot must deliver the ball withgreat precision.

The serve is handled by the table itself. The ball start s at rest suspendedfrom the ce nt re fram e above the net. When both rob ot vision systems havelocked on to it, a nearl y tran sparent ' fly swat pat s the ball toward s therobot ' on se rve' . The ba ll boun ces once before emer ging from the ' playingframe', and the robot must return it to boun ce once before emerging fromthe op ponent's playi ng frame. And so the game goes o n.

[25

Page 128: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 128/133

9

.!~ ~~r<;'-'~....-s~

.UUpA

Page 129: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 129/133

Chapter J J Whatever Next?

A few calc ulati ons show that the dexterity required is no t enormo us . Agood X - Y plotler mounted close to th e playing frame could form most ofthe hardware. The bat can be held by its centre by a glorified pen-lift, whichis armed by a sm all motor and fired as the bal l approache s the baL Bat tiltcan be added, or the same effect can be gained from a curved bat surfaceand precise pla cing. The number of alternative design s is at least a s big asthe variety of micromice, an d there is no rea son to suppo se that entries willbe confined to the 'professionals'. What is clear is that success will beearned by a comb ination of agile optical tracking an d ingenious strategicplay.

Interest in the competition is already becoming interna tional . From theint ere st shown by the Japanese delegates to the M adr id Euromicro, they

ma y be as quick to adopt robot ping-pong as they were to adoptEuromou se .

In conclusionMicroproce sso rs an d robots may do all the pundi ts claim, in es tabli shing anew industrial revolution. Manufactured good s will probably continue toslide in price, a nd only a nation of Luddite s would continue to rely onm o no to nous assem bly-line work as the basis of the national economy. Youma y be ab le to hasten the revolution a little; it would be hard to delay iL Butwhatever eco nomic significance robots may have, they are enormous fun.

127

Page 130: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 130/133

Other titles from Sunshine

SPECTRUM BOOKS

Spectrum AdventuresA guide to playing and wr iting adventuresTo ny Bridge & Roy CarnellISBN 0 946408 07 6ZX Spectrum A stronomyMaurice GavinISB N 0 946408 24 6

Spectrum Machine Code Applications

David LaineISBN 0 946408 17 3

The Working SpectrumDavid LawrenceISBN 0 946408 00 9Master your ZX MicrodriveAndrew Penne ll

ISBN 0 946408 19 X

COMMODORE 64 BOOKSGraphic Art for the Commodore 64Boris AllanISBN 0 946408 15 7

Artificial Intelligen ce on the Commodore 64Keith & Step hen BrainISBN 0 946408 29 7

Commodore 64 Adventure sMike GraceISBN 0 946408 I I 4

Bu si ness Applications for the Commodore 64Jame s HallISBN 0 946408 12 2

Mathematics on the Commodore 64Czes KosniowskiISBN 0 946408 14 9

£5.95

£6.95

£6.95

£5.95

£6.95

£5.95

£6.95

£5.95

£5.95

£5.95

Advanced Programming Techniques on the Commodore 64

David Law renceISBN 0 946408 23 8

The Working Commodore 64David Lawren ce

lSBN 0 946408 02 5

£5.95

£5.95

128

Page 131: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 131/133

Commodore 64 Machine Code MasterDa vid Lawrence & Mark England £6.95{SBN 0 946408 05 X

ELECTRON ROOKS

Graphic Art for the Electron ComputerBori s Allan £5 .95

{SBN 0 946408 20 3Programming for Education on the Electron ComputerJohn Scriven & P atrick Hall £5.95{SBN 0 946408 21 1

B B e COMPt:TER BOOKS

Functional Forth for the BBC computerBori s Allan £5.95{SBN 0 946408 04 IGraphic Art for the BBC Computer~ ~ M ~ £ 5 ~

{SBN 0 9 46408 08 4DIY Robotics and Sensors for the BBC computer

John Billing sley £6.95{SBN 0 946408 13 0Programming for Education on the BBC computerlohn Sc ri ven & Patrick Hall £5.95{SBN 0 946408 10 6Making Music on the BBC ComputerIan Waugh £5 .95

{SBN 0 946408 26 2

DRAGON BOOKS

Advanced Sound & Grapbics for tbe DragonKeith & Steve n Brain £5.95{SBN 0 94640 8 06 8Dragon 32 Games MasterKeith & St even Brain £5.95{SBN 0 94640 8 03 3The Working DragonDavid Lawrence £5.95

{SBN 0 946408 0 J 7The Dragon TrainerA handbook for beginnersBrian Llo yd £5.95{SBN 0 94640 8 09 2

129

Page 132: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 132/133

Page 133: DIY Robotics and Sensors on the Commodore Computer

8/6/2019 DIY Robotics and Sensors on the Commodore Computer

http://slidepdf.com/reader/full/diy-robotics-and-sensors-on-the-commodore-computer 133/133

How do you interface a home·made joystick, stepper

motor or a fully fled ge d robot to your Commodorecomputer? How do you write software for steppermotor control and how can you use the software anda few pennyworfh of components to get an output foranalogue control?

Step by step instructions guide you in constructing awealth of gadgetry . Atthe same time you will buildan understanding of the principles of digital andanalogue input and output.

Although he spent eight years as a Cambridge donJohn Billingsley has a practical approach toengineering. His commercial designs range fromauto· pilots and hospital computer systems tosingle·chip cooker timers and a rising damp meter .

He Is a member of several lEE commiHees, leads ateam researching Into robotics and is well known asthe organlser of the Euromouse Maze contest.