Game Programming For The Propeller Powered HYDRA 32360 Dev Manual V1.0.1

User Manual: Pdf

Open the PDF directly: View PDF PDF.
Page Count: 812 [warning: Documents this large are best viewed by clicking the View PDF Link!]

Game
Programming
for
the
Propeller
Hydra A Guide to Developing Games
,
Graphics, and Media Applications
Hydra Game System BY ANDRE LAMOTH
Programming for the Propeller Pow
e
Hydra A Guide to Developing Games
,
Graphics, and Media Applications
Hydra Game System BY ANDRE LAMOTH
Programming for the Propeller Pow
e
Hydra A Guide to Developing Games
,
Graphics, and Media Applications
Hydra Game System BY ANDRE LAMOTH
Programming for the Propeller Pow
e
Hydra A Guide to Developing Games
,
Graphics, and Media Applications
Hydra Game System BY ANDRE LAMOTH
Programming for the Propeller Pow
e
Hydra A Guide to Developing Games
,
A Guide to Developing Games, Graphics, and Media Applications for the HYDRA Game System
Game Programming
for the Propeller
Powered HYDRA
B
Y
A
NDRE
L
A
M
OTHE
Andre LaMothe
´
Front Matter
Warranty
Parallax Inc. warrants its products against defects in materials and workmanship for a period of 90 days from receipt of product. If you
discover a defect, Parallax Inc. will, at its option, repair or replace the merchandise, or refund the purchase price. Before returning the product
to Parallax, call for a Return Merchandise Authorization (RMA) number. Write the RMA number on the outside of the box used to return the
merchandise to Parallax. Please enclose the following along with the returned merchandise: your name, telephone number, shipping address,
and a description of the problem. Parallax will return your product or its replacement using the same shipping method used to ship the product
to Parallax.
14-Day Money Back Guarantee
If, within 14 days of having received your product, you find that it does not suit your needs, you may return it for a full refund. Parallax Inc. will
refund the purchase price of the product, excluding shipping/handling costs. This guarantee is void if the product has been altered or
damaged. See the Warranty section above for instructions on returning a product to Parallax.
Copyrights and Trademarks
This documentation is copyright ©2006 by Nurve Networks LLC. By obtaining a printed or electronic copy of this documentation or software
you agree that it is to be used exclusively with Propeller-chip-based HYDRA products. Any other uses are not permitted and may represent a
violation of copyrights, legally punishable according to Federal copyright or intellectual property laws. Any duplication of this documentation for
commercial uses is expressly prohibited. Excerpts from the Propeller Manual v1.0 are Copyright © 2006 by Parallax Inc. and used here with
permission.
Propeller and Spin are trademarks of Parallax, Inc. HYDRA is a trademark of Nurve Networks LLC. Other brand and product names herein
are trademarks or registered trademarks of their respective holders.
Version 1.0, 2nd Printing
ISBN 1-928982-40-9
Disclaimer of Liability
Parallax Inc. is not responsible for special, incidental, or consequential damages resulting from any breach of warranty, or under any legal
theory, including lost profits, downtime, goodwill, damage to or replacement of equipment or property, or any costs of recovering,
reprogramming, or reproducing any data stored in or used with Parallax products. Parallax Inc. is also not responsible for any personal
damage, including that to life and health, resulting from use of any of our products. You take full responsibility for your Propeller microcontroller
application, no matter how life-threatening it may be.
Errata
While great effort is made to assure the accuracy of our texts, errors may still exist. If you find an error, please let us know by sending an
email to editor@parallax.com. We continually strive to improve all of our educational materials and documentation, and frequently revise our
texts. Occasionally, an errata sheet with a list of known errors and corrections for a given text will be posted to our web site,
www.parallax.com. Please check the individual product page’s free downloads for an errata file.
Supported Hardware, Firmware and Software
This manual is valid with the following hardware, software, and firmware versions:
HYDRA Board Propeller Chip Software Firmware
Rev A P8X32A-D40 Propeller IDE v1.0 P8X32A v1.0
Dedication
Dedication
I dedicate this book to Fox Mulder and Dana Scully. Without the X-Files to look forward to
each night at 3:00 a.m. I would have surely gone insane!
Front Matter
Acknowlegements
Writing a book is a tremendous amount of work for the author, but there is a small army of
people that support him and do a lot of work behind the scenes, especially since this book is
really part of a larger product, the “HYDRA Game Console Kit.” I would like to thank the
following people for their support and contribution to this project. First, Chip and Ken Gracey
of Parallax for collaborating on a project of this scale. Hopefully, this is the first in a long
series of collaborations.
Next, all the support staff at Parallax including Stephanie Lindsay who created the look and
feel, edited and laid out the book, and Rich Allred who transcribed my artwork into final
renderings for the book and read my cryptic writing! Also, thanks to Jen Jacobs for the
artwork and packaging of the book and kit (and making it “edgy” enough). Next to Aristides
Alvarez for managing the final manufacturing, assembly, and production of the HYDRA itself
along with Mac Ma in China for manufacturing support. Additionally, Lauren Bares in
marketing, Lynette Cepeda in purchasing, Jim Carey in sales, Jeff Martin in software
engineering, and last, but not least Jim Ewald that made sure my email got through!
I would also like to thank all the vendors, companies, and friends that helped the HYDRA
project and this book in one way or another (in no particular order); Iain Cliffe of Labcenter
Electronics (www.labcenter.co.uk) for the use of Proteus to design the HYDRA, Sellam Ismail
of Vintage Tech (www.vintage.org) for always getting me those hard to find retro items, Ari
Feldman for the use of SpriteLib (http://www.flyingyogi.com/fun/spritelib.html). And Mike
Perone of Barracuda Networks (www.barracudanetworks.com) for hosting and spam
firewalls. To Steve Wozniak and Depech Mode, thanks for the concert! And David Perry of
Shiny Entertainment and Game Consultants (www.gameconsultants.com) for helping get the
word out about the XGS and HYDRA. To Steve Russell for writing the foreword, I really
appreciate it.
The next group of people I would like to thank are the demo coders that created many of the
cutting edge demos for the HYDRA (found in Chapter 25). The demo coders are: Rémi
Veilleux, Colin Phillips, Robert Woodring, Jay T. Cook, Nick Sabalausky, Rainer Blessing,
Matthew Kanwisher and Michael Thompson. Also, special thanks to Lorenzo Phillips
(www.ldp-solutions.com) that managed the software development and asset organization as
well as Terry Smith for webmastering (www.ternaryworks.net).
Finally, to my mom, dad, and beautiful girlfriend Ines – they all put up with me once again
through my 7 day a week, 100+ hour schedule from hell.
Author Bio
Author Bio
André LaMothe holds degrees in Mathematics, Computer Science and Electrical Engineering.
He has been programming since 1977 when he started writing games on the TRS-80 at the
local Radio Shack. He has worked in many fields of Computer Science and engineering.
Highlights include the head of Graphics R&D at Software Publishing Corporation by 19, a
NASA Artifical Intelligence research associate at 20, and the creator of one of the first super
computer, networked Virtual Reality games at 24. He is the founder of Xtreme Games LLC,
the Xtreme Games Developers Conference, as well as Nurve Networks LLC. Additionally, Mr.
LaMothe is a best-selling author with numerous titles on game development, graphics, and
DirectX programming. He is a native Californian and lives in sunny Silicon Valley. You can
reach him at ceo@nurve.net.
Front Matter
Table of Contents
Game Programming for the Propeller Powered HYDRA Ì Page 7
FOREWORD BY STEVE RUSSEL............................................................................................... 9
CHAPTER 0: INTRODUCTION AND A LITTLE HISTORY ABOUT GAME DEVELOPMENT...............................11
PART I: THE HYDRA HARDWARE ....................................................................... 25
CHAPTER 1: HYDRA SYSTEM OVERVIEW AND QUICK START ........................................................27
CHAPTER 2: 5V & 3.3V POWER SUPPLIES...............................................................................77
CHAPTER 3: RESET CIRCUIT................................................................................................81
CHAPTER 4: USB-SERIAL PROGRAMMING PORT ........................................................................83
CHAPTER 5: DEBUG INDICATOR HARDWARE.............................................................................91
CHAPTER 6: GAME CONTROLLER HARDWARE............................................................................95
CHAPTER 7: COMPOSITE NTSC / PAL VIDEO HARDWARE..........................................................103
CHAPTER 8: VGA HARDWARE............................................................................................115
CHAPTER 9: AUDIO HARDWARE..........................................................................................125
CHAPTER 10: KEYBOARD & MOUSE HARDWARE ......................................................................141
CHAPTER 11: GAME CARTRIDGE, EEPROM & EXPANSION PORT HARDWARE ..................................159
CHAPTER 12: HYDRA-NET NETWORK INTERFACE PORT...........................................................167
PART II: PROPELLER CHIP ARCHITECTURE AND PROGRAMMING.... 175
CHAPTER 13: PROPELLER CHIP ARCHITECTURE AND PROGRAMMING .............................................177
CHAPTER 14: COG VIDEO HARDWARE..................................................................................233
CHAPTER 15: THE SPIN LANGUAGE .....................................................................................245
CHAPTER 16: PROGRAMMING EXAMPLES ON THE PROPELLER CHIP / HYDRA ..................................319
PART III: GAME PROGRAMMING ON THE HYDRA.................................... 425
CHAPTER 17: INTRODUCTION TO GAME DEVELOPMENT .............................................................427
CHAPTER 18: BASIC GRAPHICS AND 2D ANIMATION ................................................................461
CHAPTER 19: TILE ENGINES AND SPRITES.............................................................................509
CHAPTER 20: GETTING INPUT FROM THE “USER” WORLD..........................................................559
CHAPTER 21: SOUND DESIGN FOR GAMES.............................................................................593
CHAPTER 22: ADVANCED GRAPHICS AND ANIMATION ...............................................................619
CHAPTER 23: AI, PHYSICS MODELING, AND COLLISION DETECTION - A CRASH COURSE! ...................673
CHAPTER 24: GRAPHICS ENGINE DEVELOPMENT ON THE HYDRA ................................................759
CHAPTER 25: HYDRA DEMO SHOWCASE..............................................................................779
BACK MATTER.......................................................................................................... 799
EPILOG........................................................................................................................800
INDEX .........................................................................................................................801
Front Matter
Page 8 · Game Programming for the Propeller Powered HYDRA
Foreword
Game Programming for the Propeller Powered HYDRA Page 9
Foreword by
Steve Russel
Over 45 years ago, a new PDP-1 computer
arrived near my office with a display system
that could do more than anything I had seen
before. There was just one demonstration
program, but it didn’t use all the power of the
display.
I thought that I could make a better
demonstration program, and after discussion
with my friends, I started writing code. That
program developed into “Spacewar!” – one of
the first computer games to use a display and
the distant ancestor of Atari Asteroids. I
learned that playing computer games was fun,
but writing them was even more fun!
One of the great things about writing a game is finding solutions to the puzzle of trying to
get the most fun into the game while getting it to work well. Unlike most computer
programming assignments, with a game you can adjust the problem to fit the available
solution.
The development of SpaceWar! was a collaboration, for example Dan Edwards looked at my
version of Spacewar! and decided it needed a sun and gravity to better show the problems of
getting a spaceship into orbit. Even after he developed a run-time code generator that wrote
a custom program to drive the display at its
maximum speed, there still was only time to
compute the gravity effect on 2 spaceships!
We left the torpedoes untouched by gravity, and
decided that they were “photon torpedoes” that
were unaffected by gravity since they are pure
energy (a game developer’s perogative). The
game still played fast enough, and the spaceship
orbits added a great deal to the fun.
At one point, I decided that the torpedoes would
be more “realistic” if they had a little random error,
just like real torpedoes. I added this but everyone
else complained loudly, so I took it out in the next
version.
The PDP Computer
and Display Figure F:1
Screen Shot of
SpaceWar! Figure F:2
Front Matter
Page 10 · Game Programming for the Propeller Powered HYDRA
A few years later I had a different, much better display system arrive. I was able to write a
very primitive flight simulator for it, but the pace was so slow that it was no fun. I learned
that just having 3 dimensions doesn’t necessarily make a game better.
You have much better hardware, software and examples to start with, so I hope you will
learn how much fun game programming is with less pain and more fun than I did nearly half
a century ago!
It turned out that I never got a new version of Spacewar! working well until some time
between midnight and 6 AM.
Steve Russell
Co-creator of SpaceWar!
San Jose, California
July 2006
Introduction and a Little History 0
Game Programming for the Propeller Powered HYDRA Page 11
Chapter 0:
Introduction and
a Little History
about Game
Development
Welcome to
Game Programming for the Propeller Powered HYDRA
. This is a no-
holds-barred development manual about creating basic games and graphics applications on
the Propeller powered HYDRA game console. As you might know, game development is the
most complex field of computer science in the world and takes years to master. A video
game is unlike any other program you can write for a computer; games must be fast, fun,
graphically intensive, real-time, support multiple players, run on minimal hardware, and
perform complex and/or seemingly impossible mathematical calculations at a rate fast
enough to update the screen at 30-60 frames per second or more!
Additionally, games pull from advanced research in artificial intelligence, optimization theory,
multiprocessing, compiler design, memory management, data structures, physics modeling,
networking, compression, search algorithms, and much more. And if that wasn’t enough,
there are all the graphic, audio, and artistic media assets needed for a game. Some games
literally are built upon tens to hundreds of terabytes of data and take hundreds of man-years
to develop! Thus, video games are the ultimate fusion of science and art, together creating a
real-time experience that billions of people have enjoyed since the late 50’s.
Today games such as Halo II shown in
Figure 0:1 amaze and delight millions. With
the new next-generation systems available
such as the XBOX 360 and the Playstation
III (shown in Figure 0:2) the future is almost
frightening to think of what will come next.
The sheer computational power of these
systems is staggering – each system is
capable of an excess of 1.5 trillion floating-
point operations per second! Both with
multiple computational elements, especially
the PS3 which contains the most advanced
processor in the world – the
“Cell”
processor, a multibillion-dollar joint venture
among Sony, IBM, and Toshiba.
Halo II Running
on the XBOX Figure 0:1
Introduction and a Little History
Page 12 Game Programming for the Propeller Powered HYDRA
The XBOX 360 (left) and Playstation III (right) Figure 0:2
Everyone knows that game development is serious business. With a gross revenue in excess
of $30B, the game industry is larger that the movie industry, so getting into game
development is one of the most desired job positions now and in the future for many
engineers, programmers, and artists. Never has there been more freedom technically and
artistically than there is today for game development. For fun, let’s take a stroll down
memory lane of some of the highlights in the game development and computer industry. This
list is by no means complete. In fact, I highly recommend that you read some good books on
the history of the video game industry and the computer industry, it’s fascinating stuff.
I highly recommend the following texts if you’re interested in learning more
about the foundations of the video game and computer industries and the
amazing personality and technical challenges therein:
Hackers: Heroes of the Computer Revolution by Steven Levy
The Ultimate History of Video Games by Steven Kent
Supercade: A Visual History of the Video Game Age by Van Burnham
Masters of DOOM: How Two Guys Created an Empire and Transformed
Pop Culture by David Kushner
Opening the XBOX: Inside Microsoft’s Plan to Unleash an Entertainment
Revolution
Finally, watch the DVDs Pirates of Silicon Valley and Nerds 1.0, both fascinating
introspections into the genius and innovation the early years of computing
generated.
Introduction and a Little History 0
Game Programming for the Propeller Powered HYDRA Page 13
0.1 A Brief History of Games 1958 - 1993
Ironically, game development is a very complex field. Most would think games are toys and
simple, but many game developers have been programming 10-25+ years and are experts in
numerous fields of computer science; moreover, the field is extremely competitive and
changes on a day-to-day basis. Nonetheless, developing games and graphics applications are
some of the most rewarding things to do with a computer; there is nothing like playing your
own games, or watching others have fun with what you have made! As an artist it’s the
ultimate form of what I call “liquid art.” Additionally, learning to develop games makes you a
much better programmer; you will no longer be limited by memory, processor speeds, or the
need for high-level languages; a game developer can literally make impossible things happen
with a computer.
0.1.1 Table Tennis for Two (1958)
History is replete with examples that literally changed the world. With that in mind let’s take
a look at few key events in the development of the video game industry.
Table Tennis for Two Hardware Figure 0:3
Let’s begin by setting the record straight. Many people think that
Nolan Bushnell
created
the first video game with
“PONG,”
then others think that technically it was
Ralph Baer
with the
“Brown Box”
and the Magnavox
Odyssey
game console, still others think it’s
“Space War!”
developed by
Stephen “Slug” Russell
, but they are all wrong – in fact, it
Introduction and a Little History
Page 14 Game Programming for the Propeller Powered HYDRA
was a physicist –
William Higginbotham
in 1958 at the Brookhaven National Laboratory
developed a game called
“Table Tennis for Two”
for an open house to show their new
analog computer. Figure 0:3 shows a picture of the hardware that “Table Tennis for Two”
ran on with an arrow pointing to the output device. Also, check out the link below to see the
game in action (Real Player format):
http://real.bnl.gov/ramgen/bnl/PONG.rm
The game was developed completely in hardware by means of an analog computer. The lab
wanted to show off something interesting other than weapons design research, so Willy took
the manual that came with the analog computer and read about examples of drawing
trajectories and curves on the oscilloscope. He took this information, and with the addition of
some hardware he and a colleague cobbled together the VERY first video game in history.
0.1.2 Space War! (1962)
Next up was the creation of
Space War!”
by Stephen “Slug” Russell at MIT. Other major
contributors include Peter Samson, Martin Graetz, Wayne Witanen, Alan Kotok and Dan
Edwards. The game was written on a DEC PDP-1 in pure assembly language in 1962. Steve
“Slug” was nick-named “Slug” since like all software engineers, he took forever to finish
anything! Figure 0.4 shows a screen shot of the original Space War! hardware, quite a
difference from your laptop. You can actually play a remake of Space War! by following this
URL:
http://lcs.www.media.mit.edu/groups/el/projects/spacewar/
Figure 0:4
Space War! Running
on a DEC PDP-1
Introduction and a Little History 0
Game Programming for the Propeller Powered HYDRA Page 15
0.1.3 Ralph Baer, the Brown Box, and the Maganvox Odyessy (1966)
Figure 0:5
Ralph Baer and his
Magnavox Odyssey
Ralph H. Baer was a TV engineer who had an interest in interactive TV. He was the first
person to ever have the notion of moving objects around on a TV screen, and quite frankly
his associates and boss at Sander and Associates told him to forget about it and focus on
making better TV sets. Nonetheless, Ralph kept working away on his
“Brown Box”
and in
1968 had a working prototype of a hard-wired game system capable of moving simple dots
around on the screen.
Figure 0:5 shows Ralph and the Magnavox
Odyssey
system. The rendering ability (if you
can call it that) of the Odyssey was non-existent, so in a brilliant stroke of “engineering
ingenuity” Ralph thought “Why not add transparent backgrounds as overlays on the TV set
itself?” So, that’s what they did; the games that ran on the Odyssey all were nothing more
than dots moving around, but when you put a nice background on the TV set screen itself of
a tennis court, baseball diamond, or haunted house, it was like nothing anyone had seen.
The Odyssey sold about 100-150,000 units depending on where you get your information.
Interestingly though, it came out in 1972 officially, which was the same time that Atari PONG
came out.
Introduction and a Little History
Page 16 Game Programming for the Propeller Powered HYDRA
0.1.4 Atari PONG (1972)
Next, the most important commercial game was
“PONG”
developed by
Nolan
Bushnell
and
Al
Alcorn
of newly formed
Atari
in 1972. This game was responsible for putting games
on the map and was the genesis of the entire video game industry as we know it. It all
happened at Andy Capp’s Tavern in Sunnyvale, CA. Nolan Bushnell, with his newly founded
company Atari, decided to test a prototype of new game that his new engineer Al Alcorn
developed called PONG in local neighborhood Andy Capp’s Tavern as an experiment.
Figure 0:6
Original Atari PONG machine
developed by Nolan Bushnell
and Al Alcorn
Figure 0:6 shows one of the hand-made early prototypes. To their surprise, one week after
the game was deployed there was a line around the corner to play, and the coin mech (a
coffee can) was jammed since the machine was completely full of quarters! This moment in
time launched the $30B video game industry, and Atari, one of the icons of American
business and innovation, was created.
Atari was the fastest growing company in history at the time! And Bushnell, when he sold the
company for $24M+ and change, was the “rock star” of Silicon Valley. Atari PONG more or
less put the Odyssey out of business when Atari came out with a home version of PONG –
remember it? The Atari version of PONG and the system it ran on (PONG on a chip) was
light-years ahead of the Odyssey. The reason why is that the Odyssey technology was really
early 60’s technology and it took Ralph Baer such a long time to get the suits to listen, by the
time they did, Nolan Bushnell was able to create the 2nd generation of games with PONG
and capture the consumer market. But, we should acknowledge that technically the first
game console was the brain-child of Ralph Baer, thus the designation of
“Father of the
Video Games”
goes to Nolan Bushnell, while the
“Grandfather of Video Games”
goes to
Ralph Baer! Interestingly, the first big patent infringement goes to Nolan Bushnell and PONG:
Magnavox, on their knees, financially sued Atari as a last-ditch effort saying that PONG was a
copy of games on the Odyssey. Atari did settle, but patenting dots running around on the
screen – you’ve got to be kidding!
Introduction and a Little History 0
Game Programming for the Propeller Powered HYDRA Page 17
0.1.5 The Apple Computer (1977)
The personal computer industry was also a result of video games.
Steve Jobs
(co-founder of
Apple) worked at Atari, and he and
Steve
“The WOZ” Wozniak
were both interested in
developing their own computer and game system to play games on and hack. Steve Jobs
actually worked at Atari – Nolan Bushnell requested him to create a prototype of a new game
called
“Breakout”
and Jobs accepted the challenge, enlisting electronics guru Steve
Wozniak to do the design.
Together after a 4 day straight engineering/programming tribute to sleep deprivation, the
result was a completed game in a ridiculously low number of chips with NO microprocessor!
In fact, the design was so clever, so optimized, that Atari engineers couldn’t understand it!
However, the knowledge that Steve Wozniak learned and experimented with over those 4
days helped him develop both the Apple I and II computers, and the beginning of the
personal computer era begun in 1977.
Figure 0:7
The two Steves
(Jobs left, Woz right)
holding their creation
– the Apple II
Figure 0:7 shows the two Steves working on the original Apple I personal computer; this was
of course followed by the Apple II which made Apple computer the fastest growing company
in American history and the largest IPO (initial public offering) in history – I still am mad at
my dad for not believing me in the late 70’s when I told him to buy Apple stock!
Introduction and a Little History
Page 18 Game Programming for the Propeller Powered HYDRA
0.1.6 Pac-Man (1980)
So, now we have the creation of the
video game industry and the personal
computer industry, the 80’s are upon us,
and things are getting serious and
competitive. With the USA taking the
lead position in the industry, the
Japanese weren’t far behind with their
own blockbuster game and their
contribution to changing the world of
games.
Toru Iwatani
, a 24 year old
programmer, was in Tokyo and decided
to sit down with some friends and have
some pizza at the American franchise
Shakey’s Pizza. While ordering pizza,
someone took a single piece of the
cheese pizza and that image of a yellow
circle with a piece removed was the
inspiration for “Pac-Man,” quite arguably
one of the most successful games in
history. Toru and his colleagues worked
for 18 months on the game with a team
of hardware and software engineers to
develop Pac-Man. It was the largest
game ever developed and the largest
team ever to develop a game, but it paid
off.
Pac-Man as shown in Figure 0:8 was an instant hit in America and all over the world where
the machines were sent. The characters of Pac-Man also become overnight stars and
everything from sequels to cartoons to breakfast cereals had a Pac-Man logo on it. The age
of engineered games and product marketing was born. People realized this was serious
business, and there were billions to be made…
Pac-Man was originally called “PUC-MAN”, but when shipped to America, kids
used to erase part of the “P” and the resulting name was less than desired by
Namco. Thus, they change it to “Pac-Man” so at worst the game would read
“Fac-Man”!
Pac-Man –
the First System
Engineered Game
Figure 0:8
Introduction and a Little History 0
Game Programming for the Propeller Powered HYDRA Page 19
0.1.7 Wolfenstein 3D and the Era of First Person Shooters (1992)
Certainly, there are dozens of games worth
mentioning that were eventful in the industry,
but we don’t have time to really cover them in
the depth that they deserve. Games like Space
Invaders, Asteroids, Computer Space, and more
all made a difference in the early 60’s, 70’s and
80’s, but it wasn’t until the 90’s that games got
scary – enter
id Software
the creators of
Wolfenstein 3D
as shown in Figure 0:9.
Another Cinderella story,
John
Carmack
and
John
Romero
both were Apple II fanatics, both
loners, and both interested in making games and
world domination. John Romero, a little older
than Carmack, had been bouncing around
working at various places on game projects; at some point he met up with John Carmack and
the results were similar to Bill Gates and Paul Allen getting together. John and John literally
changed the world with their games. Soon after their initial meeting they were working at a
company called
Softdisk
Publishing
, and to make a long and interesting story short, they
were making a game a month for Softdisk to place on a floppy with a magazine! This is a
feat to say the least, but during this time they got really good at making games, and did
what most game programmers take years to do in months. Thus they honed their skills to a
white-hot blaze ready to cut the fabric of space-time.
Ready to take on the world and report to no one, they started id Software. Their first game
of note was
“Commander Keen”
(1990), a side scrolling tour de force thought to be
impossible to achieve on the IBM PC, but they were just warming up. Carmack, turning into
the technical guru of the group, had been experimenting with “ray casting” technology, a
simplified version of “ray tracing” used to create photo real imagery in CG movies. However,
ray casting allows 3D rendering to be achieved at blazing speeds due to simplified
geometrical assumptions and a lot of tricks. The results of this ray casting technology was
“Wolfenstein 3D” released in 1992, a 3D remake of the popular Apple II game “Castle
Wolfenstein”, but Wolfenstein 3D was 3D, and immersed the users in a fluid world running at
blistering speeds. Figure 0:9 shows a screen shot.
Wolfenstein 3D was not only a technical marvel and for the billionth time made all the
doubters realize that game developers are sorcerers and capable of magic, but Wolfenstein
was highly controversial – its depiction of Nazis’, blood and gore got the whole world up in a
roar, but it was the first real-time cinematic experience on a personal computer. And like it or
not, the world wanted more...and more they got…
Wolfenstein 3D
by id Software Figure 0:9
Introduction and a Little History
Page 20 Game Programming for the Propeller Powered HYDRA
0.1.8 DOOM (late 1993)
DOOM shown in Figure 0:10 speaks for itself; there are few people that do not know what
DOOM is or who haven’t played it.
Enter DOOM Figure 0:10
DOOM by far was the most impressive technical achievement on a PC the world had ever
seen. Released in 1993, DOOM was based on a technology called
“Binary Space Partition”
or
BSP trees, a technique discovered in the 60’s to bisect space into half spaces for easier
computation in a recursive algorithm.
Technical details aside, the results of the algorithm coupled with a game developer’s clever
programming was the most incredible experience ever on a PC: DOOM. Millions of people
were stunned by the technology, and numerous industries including military, medical, and
architectural, were affected. Not to mention the game spawned (no pun intended) the entire
3D accelerator market.
If you are interested in DOOM technology and how BSP trees work and how to
implement them, you will be pleased to know that The Black Art of 3D Game
Programming by yours truly is in electronic form included with the CD of this
book. It came out in 1994/1995, and within it I showed the world how DOOM
worked among other things.
Introduction and a Little History 0
Game Programming for the Propeller Powered HYDRA Page 21
0.2 Origins of the HYDRA
A few other hits have come out since including Quake, Half Life and of course Halo, but none
with the impact of awe of these early games. The technology of game development is now
being disseminated at an exponential rate; books, courses, and entire degrees in game
development technology are now available. Alas, we won’t be changing the world here, but I
can’t think of a more engaging way to have fun with the new Propeller chip than to make
games on it! The Propeller chip has something near and dear to my heart and that’s
multiprocessing
. I simply love multiprocessing; if I could I would multiprocess in my sleep
– I would! Game developers for years, including myself, have had to fake multiprocessing
and/or use pseudo-multiprocessing with Pentium or PowerPC chips via
“multiple execution
units”
which isn’t the same. The Propeller chip is a true multiprocessing processor and
definitely a very interesting chip to develop games on. Therefore, I thought “What better
application than a game console around it, and to make some games on to get people
interested in the processor and of course interested in games!”
When I developed the HYDRA, I wanted to keep the system open, simple, and more or less
just a Propeller chip without adding a lot of ancillary hardware, thus the HYDRA has no extra
computing augmentation and is more or less completely powered for the most part by the
Propeller chip itself. The HYDRA is a good example of what you can do with just a Propeller
chip; if you were to add extra SRAM or other hardware then the Propeller can be used to
create all kinds of embedded applications. Additionally, the HYDRA was developed to simply
experiment with the Propeller chip; the HYDRA has an expansion port, mouse and keyboard
ports, game ports, dual 3.3 V / 5.0 V supplies, VGA and NTSC/PAL out, networking
(RJ-11 based) and much more – I had a lot of fun designing it, and hopefully you have a lot
of fun learning the Propeller chip and game development with it!
0.3 What to Expect
There is so much to cover in game development, a complete treatise on the subject usually
takes about 1000-2000 pages to even scratch the surface. Alas rather than go nuts like I
usually do, I decided to take a more beginners’ approach with this book since unlike my
other game development books where I assume we are all programming on a PC with
DirectX, this is not the case. In this case, we have new hardware, a new chip, a new
language, and you might be learning game development for the first time, not to mention
being only a beginning programmer as well. Thus, I decided rather than engaging the
transwarp drive like I usually do, let’s keep this at impulse speed for most of the time with a
romp here and there to warp speed!
With that in mind, I assume that you are a programmer; this book will not teach you
programming. However, I don’t assume you have done any game or graphics programming,
so that part we will explore together, but you should be familiar with one or more of the
Introduction and a Little History
Page 22 Game Programming for the Propeller Powered HYDRA
following languages: BASIC, C/C++, JAVA, ASM, PASCAL, DELPHI, etc. I will discuss the
language constructs of the Propeller chip’s native language “Spin”, but I will not teach
programming concepts. Additionally, there is a large part of the book on the Propeller chip
itself and a lot of Assembly language material; if you are new to Assembly language, I
suggest you read a good book on 6502, or ARM, or even 8086 and write some programs to
get the hang of the language. Specifics aside, I will always try my best to teach where
possible, so those of you that get bored, simply skip past anything that is old news to you.
Now, let’s take a look at the three main sections that make up the book:
The HYDRA Hardware - This is a fast and furious circuit description of the HYDRA
Game Console’s implementation around the Propeller chip. Not meant to be
complete, it simply gives you a frame of reference as programmers, so you know
what hardware does what along with some technical detail here and there. Each
chapter tends to focus on a specific aspect of the HYDRA, thus some chapters are
short; others are longer.
Propeller Chip Architecture and Programming – This is the nitty-gritty of the
Propeller chip and has examples of programming graphics, sound, joysticks, I/O,
networking, and explains both the ASM and high-level language (Spin) supported by
the Propeller chip as well as the technical description of the Propeller chip itself. This
part of the book is hands-on and you will get to run a number of demos and see
what they do. Also, we will focus on using Parallax general-purpose objects rather
than high performance gaming code, so we can keep a black box approach.
Game Programming on the HYDRA – This is the fun part. Once we have all the
fundamentals down and you know what the HYDRA does and how the Propeller chip
works and is programmed, then we can sit down and start learning about game
development and graphics.
0.4 Target Audience
Typically game development is all about software; however, if you have purchased a HYDRA
then you probably are interested in embedded systems, hardware, and may even be a
full-fledged Electrical Engineer. On the other hand, you might be a programmer that is
interested in getting into embedded systems, and what better way than with games? Trying
to cater to everyone is nearly impossible, so this book is going to be more of a software
guide rather than a hardware guide in as much as we are going to spend 90% of our time
programming, rather than doing circuit analysis. That is, when I show a circuit to you, I am
going to assume that you understand electronics, rather than explain the nitty-gritty. If you
don’t know anything about electronics, the explanation will be more than enough for
programming purposes. So this book is about writing games, graphics, and media
applications on the HYDRA and learning the Propeller chip, it’s not about designing game
consoles or the hardware therein. Considering that, we are still going to cover every single
Introduction and a Little History 0
Game Programming for the Propeller Powered HYDRA Page 23
piece of hardware in the HYDRA in the first part of this book before getting into software.
This way, even software guys will have some idea of what does what, and hardware guys will
have a good reference for each sub-system to know what’s doing what, or can make changes
if they wish.
0.5 Conventions Used in this Book
The book’s text is more or less straightforward: what you see is what you get. Typically, I
will highlight important terms in the text the first time I introduce them, secondly, code
listings will always be set off in a fixed point font and in a slightly smaller font pitch that the
general text so more code can fit per page. Also, from time to time you will see special
sidebars, like Notes, Warnings, etc. Lastly, when discussing key presses and menu item
selection sequences I will always place angled brackets around the key or menu selection
sequence, for example, if I wanted to tell you to press the control key and J at the same
time, you will see “<CTRL + J>”, similarly if I want you to go to the main menu, then select
the sub-menu tools, then from there select configuration, I will write it something like this
<Main Menu
Tools
Configuration>.
And I may italicize the sequence and or
highlight it to bring your attention to it and separate it from the text. Also, in the text, to set
off code variables, I will simply italicize them. For example, if I wanted to talk about a “for
loop”, I would say something like, “referring to the
FOR
statement on line 10…”, as you can
see the “
FOR
” element is italicized.
0.6 Requirements
The main part of working with the HYDRA or the Propeller chip is using the Propeller Tool
IDE. Currently, it only supports Windows XP, 2000, 2003. There are no Windows 95/98/ME
tools or Linux. In the near future, I suspect there will be, so stayed tuned. But, most
everyone with a PC has a copy of Windows XP/200X on it, so you should be fine. Other than
that you should have at least one USB port free, and a standard multimedia type PC. Since
the only thing you will use the PC for is compiling programs, you don’t need a lot of
horsepower, so a Pentium II or greater (or AMD equivalent) is more than enough.
Additionally, you will need a NTSC/PAL compatible TV to connect to the output of the HYDRA
since it generates standard composite video. Also, if you want to experiment with the
HYDRA’s VGA output abilities you will need a VGA monitor or a simple KVM to switch your PC
with the HYDRA. The HYDRA kit comes with everything else you need, so turn the page and
let’s start experimenting!
Last, but not least, skim entire book BEFORE doing anything! There are a few
items that are embedded in the middle or end that will help you understand
things, so best to read the whole thing first THEN go ahead and start playing
with the hardware and programming.
Introduction and a Little History
Page 24 Game Programming for the Propeller Powered HYDRA
H
ardware Part I The Hydra Hardware Part I T
The Hydra Hardware Part I The Hydra Hardwar
e
Part I The Hydra Hardware Part I The Hydra
H
H
ardware Part I The Hydra Hardware Part I T
The Hydra Hardware Part I The Hydra Hardwar
e
Part I The Hydra Hardware Part I The Hydra
H
H
ardware Part I The Hydra Hardware Part I T
The Hydra Hardware Part I The Hydra Hardwar
e
Part I The Hydra Hardware Part I The Hydra
H
H
ardware Part I The Hydra Hardware Part I T
The Hydra Hardware Part I The Hydra Hardwar
e
Part I The Hydra Hardware Part I The Hydra
H
Part I: The HYDRA Hardware
I The HYDRA Hardware
Page 26 Game Programming for the Propeller Powered HYDRA
Chapter 1: HYDRA System Overview and Quick Start, p. 27
Chapter 2: 5V & 3.3V Power Supplies, p. 77.
Chapter 3: Reset Circuit, p. 81.
Chapter 4: USB-Serial Programming Port, p. 83.
Chapter 5: Debug Indicator Hardware, p. 91.
Chapter 6: Game Controller Hardware, p. 95.
Chapter 7: Composite NTSC / PAL Video Hardware, p. 103.
Chapter 8: VGA Hardware, p. 115.
Chapter 9: Audio Hardware, p. 125.
Chapter 10: Keyboard & Mouse Hardware, p. 141.
Chapter 11: Game Cartridge, EEPROM & Expansion Port Hardware, p. 159.
Chapter 12: HYDRA-NET Network Interface Port, p. 167.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 27
Chapter 1:
HYDRA System
Overview and
Quick Start
In this chapter, we are going to get acquainted with the HYDRA game console and the
Propeller Chip, as well as the Propeller Tool IDE itself. Of course, we are going to have some
fun and try some games, load some programs, and in general get comfortable with the
HYDRA system and everything that comes with it. Here’s a general outline of what we are
going to do:
Take inventory of the HYDRA game console kit
Experiment with the “Quick Start” demos
Learn a little about the HYDRA and Propeller chip
Install the USB drivers for the Propeller Tool
Install the Propeller Tool and learn about the IDE
The HYDRA Game Console Figure 1:1
I The HYDRA Hardware
Page 28 Game Programming for the Propeller Powered HYDRA
The HYDRA Game Console (HGC) is developed around the Parallax Propeller chip.
Figure 1:1 shows an image of the HYDRA with all the various functional units labeled. The
HYDRA has the following hardware:
40-Pin DIP Package of the Propeller chip, as DIP makes future upgrades and change
outs easy; runs 80 MHz.
RCA Video and Audio Out Ports.
HD15 Standard VGA Out Port.
PS/2 Mouse and Keyboard Support.
Two Nintendo NES/Famicom compatible gamepad ports.
RJ-11 (phone jack), Peer to Peer networking port, supports full-duplex serial at up to
2.56 Mb at 100 meters with simple coding.
Single 9 VDC power in with regulated output of 5.0 V @ 500 mA and 3.3 V @
500 mA on board to support external peripherals and components (Note: the
Propeller chip is a 3.3 V device).
Removable passive XTAL to support faster speeds and experimenting with various
reference clocks.
Debugging LED output.
On-Board 128 KB Serial EEPROM used to hold program memory when power shuts
down. The Propeller chip uses 32 KB currently only.
Cartridge/Game/Expansion Port that exposes I/O, power, networking, USB, etc.
Onboard Mini-B USB interface/programming port based on the FTDI USB chip.
Backup external 4-Pin programming port compatible with Parallax “USB2SER”
hardware/tools.
The HYDRA is more or less a minimal part count gaming platform to show off the capabilities
of the Propeller chip. The hardware around the Propeller chip enhances functionality and
interfacing, but doesn’t add computational elements, thus all work performed by the HYDRA
is solely the responsibility of the Propeller chip.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 29
1.1 HYDRA Kit Package Contents
Figure 1:2
The HYDRA Game
Console Kit Contents
You should have the following items in your HYDRA kit, referring to Figure 1:2 (which shows
most of the kit). So, take inventory and make sure you have everything you should have with
the kit, and once you have confirmed everything and are ready to have some fun, read on.
(1) HYDRA Game Console
(1) PS/2 Mouse
(1) PS/2 Keyboard
(1) 128 KB Game Cartridge Pre-Loaded with “Ball Buster” demo game
(1) Blank experiment card to build your own HYDRA projects on
(1) Mini-USB programming cable to connect from your PC to the HYDRA
(1) 9 V 500 mA, DC unregulated wall adapter with 2.1 mm plug and tip (+) positive, ring (-)
negative
(1) RCA A/V cable
(1) Nintendo-compatible controller
(1) CD ROM with all the software, demos, tools, and IDE
I The HYDRA Hardware
Page 30 Game Programming for the Propeller Powered HYDRA
1.2 HYDRA “Quick Start”
Demos
Your HYDRA is pre-loaded with a simple
“Asteroids”
clone demo programmed into
the on-board serial EEPROM at U4 (top left of
the Propeller chip), a screen shot is shown in
Figure 1:3. We will use this to test your
system out.
The following are a series of steps to try the
demo out and make sure your hardware is
working and a stray high energy neutron
didn’t damage your EEPROM!
Step 1: Place your HYDRA on a flat surface,
no carpet! Static electricity!
Step 2: Make sure the power switch at the front is in the OFF position, this is to the
RIGHT.
Step 3: Plug your wall adapter in and plug the 2.1 mm power connector into the female
port located at the top-left corner of the HYDRA.
Step 4: Make sure the XTAL marked 10 MHz is inserted into the XTAL port, top-center
above the Propeller chip at J13. It’s possible that during transport the XTAL came loose and
isn’t inserted all the way and/or is loose in the packaging, so make sure the XTAL is inserted.
Step 5: If you have plugged the cartridge into the system, then UNPLUG it – we want to
run the code off the serial 128K EEPROM memory which is on-board (located top-left above
the Propeller chip).
Step 6: Insert the A/V cable into the yellow (video) and white (audio) port of the HYDRA
located top-right of the board, insert them into your NTSC/Multi-System TV’s A/V port, and
then switch your TV set to “Video Input” mode.
Step 7: Plug the mouse into the PS/2 mouse port (it’s labeled “Mouse”), make sure to hold
the port socket as you insert and be careful not to “force” the male into the female, ease it in
and take your time. If it won’t go in, try pulling it out and then putting it back in a couple
times to loosen up the connection. You don’t want to break the port off the PCB, as these
boards can be cracked and some of the parts are a little tight in some cases.
Step 8: Turn the power ON by sliding the ON/OFF switch to the RIGHT.
Step 9: You will see the logo/splash screen. Use the left mouse button to start the game
and fire, right mouse button to thrust, left/right to rotate!
The Parallaxaroids
Demo Running Figure 1:3
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 31
You should see something like that shown in Figure 1:3. The actual program that is loaded
into the Propeller chip is located on your CD here:
CD_ROOT:\HYDRA\SOURCES\ASTEROIDS_DEMO_013.SPIN
Next, let’s have some fun, let’s “hot-plug” another game in! Simply take your game cartridge
and while the HYRDA is ON and running
Parallaxaroids
, plug the game cart into the system
with its orientation such that the text and serial EEPROM chip are
facing you
. This is shown
in Figure 1:4.
Figure 1:4
Inserting the game
cartridge the right
way.
If all goes well, nothing will happen, but you will see the LED to the right of the cartridge
port turn ON, and the power LEDs on the cartridge itself will illuminate; this indicates a
cartridge is in the system.
Now, press the RESET button located next to the power switch and the HYDRA will re-boot
from the CARTRIDGE rather than the on-board serial EEPROM (the cartridge always has
priority). The cartridge basically overrides the onboard serial EEPROM and electrically
disconnects it, so that the system feeds from the cartridge if it’s inserted. Additionally, if you
were to download a program to the HYDRA with the cartridge in, the cartridge would be
programmed with the new program not the base board EEPROM. In any event, with the new
cartridge in you should see a “Breakout/Arkanoid” like game running on screen named “Ball
Buster” Now, plug in your mouse and/or gamepad (left port) and both input devices will
move the paddle. The controls are listed in Table 1:1 on the next page.
I The HYDRA Hardware
Page 32 Game Programming for the Propeller Powered HYDRA
Table 1:1 Ball Buster Demo Controls
for Each Input Device
Device Action Control
Launch Ball Left Button
Move Left Motion Left
Mouse
Move Right Motion Right
Launch Ball A/B
Rotate Left Dpad Left
Gamepad
Rotate Right Dpad Right
Feel free to hot pull the cartridge out as well, just hit the Reset button again and the HYDRA
will boot the Parallaxaroids game once again – cool huh! This concludes our little demo of a
couple games, powering the unit, resetting the unit, and inserting a cartridge.
The actual top level file for the “Ball Buster” demo is located on the CD here:
CD_ROOT:\HYDRA\SOURCES\JTC_B_Buster_005.spin
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 33
1.3 The Propeller Chip
The Propeller chip comes in 40 pin DIP (dual inline package) or a 44 pin LQFP (low quad
flat pack) as well as a 44-pin QFN (quad flat no lead) type package. Figure 1:6 shows the
packaging and pinout of the chip. The Propeller chip was designed by
Chip Gracey
of
Parallax Inc. as a low cost, high performance microcontroller with multiprocessing
capabilities.
The Propeller chip has 8 cores and is, simply put, a symmetrical multiprocessing
microcontroller supporting a
“round robin”
non-pre-emptive shared memory access
scheme; however, all cores, called
“cogs”
run simultaneously and independently when not
accessing main memory.
Figure 1:5 shows the Propeller chip architecture in block diagram form, and Table 1:2 lists
the pins and their function for the Propeller chip.
Propeller Chip Block Diagram Figure 1:5
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
I The HYDRA Hardware
Page 34 Game Programming for the Propeller Powered HYDRA
P8X32A-D40 40-pin DIP
P8X32A-Q44 44-pin LQFP
P8X32A-M44 44-pin QFN
Propeller Chip Package Types Figure 1:6
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 35
Table 1:2 Propeller Chip Pin Names and Functions
Pin Name Direction Description
P0 – P27 I/O General purpose I/O. Can source/sink 30 mA each at 3.3 vdc. Do not
exceed 100 mA source/sink total across any group of I/O pins at once.
P28 I/O
I2C SCL connection to external EEPROM (General purpose I/O after
boot up).
P29 I/O
I2C SDA connection to external EEPROM (General purpose I/O after
boot up).
P30 O, I/O Tx to host (General Purpose I/O after boot up/download).
P31 I, I/O
Rx from host (General Purpose I/O after boot up/download sequence,
if not connected to host).
VDD --- 3.3 v power (2.7 – 3.3 vdc).
VSS --- Ground (0 vdc).
BOEn I
Brown Out Enable (active low). Must be connected to either VDD or
VSS. If low, RESn becomes a weak output (delivering VDD through 5
K) for monitoring purposes but can still be driven low to cause reset.
If high, RESn is CMOS input with Schmitt Trigger.
RESn I/O Reset (active low). When low, resets the Propeller chip: all cogs
disabled and I/O pins floating. Propeller restarts 50 ms after RESn
transitions from low to high.
XI I
Crystal Input. Can be connected to output of crystal/oscillator pack
(with XO left disconnected), or to one leg of crystal (with XO
connected to other leg of crystal or resonator) depending on CLK
Register settings. No external resistors or capacitors are required.
XO O
Crystal Output. Provides feedback for an external crystal, or may be
left disconnected depending on CLK Register settings. No external
resistors or capacitors are required.
I The HYDRA Hardware
Page 36 Game Programming for the Propeller Powered HYDRA
The Propeller chip is a 32-bit RISC-like architecture (without pipelining) chip with a
fixed
instruction size of
32 bits
. The on chip memory is
64 Kbytes
and is organized as two
32 Kbyte
(8192 LONGs) banks as shown in Figure 1:7.
Figure 1:7
Structure of
the Propeller
Chip’s Memory
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
The first 32K from [0x0000 - 0x7FFF] is RAM, the second 32K from [0x8000 - 0xFFFF]
is ROM. These memories are physically different, but logically addressed with a simple 0-64K
address. The ROM contains the interpreter, data tables (sine, log, character data etc.) and
other run-time objects needed for the Propeller chip’s operation. The RAM is used for
program memory, data, and video memory and is shared among all cogs. The Propeller chip
doesn’t differentiate between RAM and ROM, it is simply an address space from [0x0000 -
0xFFFF]. Additionally, there is no dedicated external memory interface integrated into the
Propeller chip’s architecture, therefore, memory is at a premium when programming, so care
must be taken to conserve memory (especially when doing graphics since you must use a
portion of the internal 32K for video buffers). The Propeller chip is programmed using either
Assembly Language (which you will find reminiscent of a fusion of ARM/SX/PIC/6502
assembly code) or a high-level language called
“Spin.”
A snippet of ASM is shown next:
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 37
' Plot pixel at px,py
'
plotd mov px,dx 'set px,py to dx,dy
mov py,dy
plotp tjnz pwidth,#wplot 'if width > 0, do wide plot
mov t1,px 'compute pixel mask
shl t1,#1
mov mask0,#%11
shl mask0,t1
shr t1,#5
cmp t1,xlongs wc 'if x or y out of bounds, exit
if_c cmp py,ylongs wc
if_nc jmp #plotp_ret
mov bits0,pcolor 'compute pixel bits
and bits0,mask0
shl t1,#1 'get address of pixel long
add t1,basesptr
mov t2,py
rdword t1,t1
shl t2,#2
add t1,t2
rdlong t2,t1 'write pixel
andn t2,mask0
or t2,bits0
wrlong t2,t1
plotp_ret
plotd_ret ret
The above ASM snippet is an excerpt from the graphics driver and is the plot pixel function.
Additionally, the High-Level Interpreted Language (HLL) used to program the Propeller is
called
Spin
(which is reminiscent of Pascal\BASIC), a snippet is shown below:
' move asteroids
gr.colorwidth(1,0)
repeat i from 0 to NUM_ASTEROIDS-1
base := i*ASTEROIDS_DS_LONG_SIZE
x := asteroids[base+ASTEROID_DS_X_INDEX] += asteroids[base+ASTEROID_DS_DX_INDEX]
y := asteroids[base+ASTEROID_DS_Y_INDEX] += asteroids[base+ASTEROID_DS_DY_INDEX]
' test for screen boundaries
if (x > SCREEN_WIDTH/2 )
I The HYDRA Hardware
Page 38 Game Programming for the Propeller Powered HYDRA
asteroids[i*ASTEROIDS_DS_LONG_SIZE + ASTEROID_DS_X_INDEX] := - SCREEN_WIDTH/2
elseif (x < -SCREEN_WIDTH/2 )
asteroids[i*ASTEROIDS_DS_LONG_SIZE + ASTEROID_DS_X_INDEX] := SCREEN_WIDTH/2
if (y > SCREEN_HEIGHT/2 )
asteroids[i*ASTEROIDS_DS_LONG_SIZE + ASTEROID_DS_Y_INDEX] := - SCREEN_HEIGHT/2
elseif (y < -SCREEN_HEIGHT/2 )
asteroids[i*ASTEROIDS_DS_LONG_SIZE + ASTEROID_DS_Y_INDEX] := SCREEN_HEIGHT/2
This snippet is from the “Parallaxaroids” demo game and shows a loop construct along with
some assignments, array access, and conditional code, notice there is
no
begin/end
construct, thus the loop block/nesting level is defined by indention, this is definitely an area
that can cause problems (so the Propeller Tool IDE has special align and display modes to
help you with this), but keep it in mind that a single space can change the nesting level!
When we discuss the Spin language we will cover this quirk in more detail.
The Propeller chip’s native Assembly Language is the best way to get performance and save
memory; however, if you are not concerned with speed or need ultra high performance then
the Spin HLL is the way to go. Now, a caveat – Spin HLL code must reside in main memory,
while memory containing assembly code may be used for other purposes after the cog
running that code has been launched. This extra memory consumption may become
important when video buffers are used as well.
So for very large programs where speed is critical Assembly is a better choice, or you could
write a FORTH or other HLL interpreter and run it then feed it from the EEPROM using a
caching scheme. Of course, these limitations are consistent with most microcontrollers.
There is currently no debugger built into the IDE. However, it’s possible to
access the USB TX/RX lines after boot etc. and a packet protocol to send back
debug information like “printf’s” etc. could be developed on the PC side to send
information. Additionally, a simple RS232 interface can be made that hooks to
the PC as well with the same idea in mind. Therefore, the trick is to use Spin/ASM
with a graphics driver and then send it debug information from your application
through a shared memory and let it print on the screen or simply to print debug
information on the screen for your graphic applications. So “old school”
debugging is what has to be used here. For example, when we start developing
applications and games, I will show you how to connect a VT100 terminal
program and then send debugger information to it in real-time from the HYDRA.
1.3.1 System Startup and Reset Details
Although it’s early in our discussion to get too technical, you might want to know what
exactly happens with the HYDRA/Propeller chip is booted. On startup/reset the Propeller chip
looks at the TX (P31) / RX (P30) lines connected from the PC host, these serial lines are
interfaced via the USB connection and from the Propeller chip’s point of view are standard
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 39
serial connections and from the PCs point of view are a standard serial port COMx
(implemented as a VCP or “Virtual COM Port” in Windows-speak).
In any event, if there is activity on these lines, the Propeller chip will try to negotiate a link
with the PC host using a very complex serial communication scheme that guarantees the PC
is trying to talk and there isn’t noise on the lines (a pattern-matching protocol is used). If the
PC host is present then the Propeller chip will load the 32 Kbyte program image from the
host and either copy it directly into RAM or the Propeller chip’s firmware will copy the
program into the EEPROM connected on lines P28 (Serial Clock SCK) and P29 (Serial Data
SDA) respectively and then reset the chip which then pulls the program from the EEPROM
and execute. Its important to realize that the
“binary image”
created on the PC by the
Propeller compiler is 32 Kbytes and it is exactly copied into the RAM of the Propeller chip 1:1,
this is a nice feature since you know that everything is always contained in this exact 32
Kbyte image no matter what the size is of the actual program/data (as long as its less than
or equal to 32K), that is, if you have a small or large program the IDE will always create a 32
Kbyte image for the Propeller chip.
Once the program is download the Propeller chip launches Cog 0, runs the internal
interpreter on it, and starts executing code at the very first PUB, that is, “public” Spin
statement, more on this later.
1.4 Installing the Software
The Propeller Tool IDE used to develop all programs for the Propeller chip is shown in Figure
1:8 on the next page, it’s a Delphi based application that you will use to develop applications
for the Propeller chip/HYDRA. The Propeller tool only supports Windows XP, 2000, and 2003.
It should work on Windows XP/64-bit versions as well. If you are a Windows 95/98 or NT
user you will have to install one of these new variants of Windows over your old OS or as a
dual boot setup if you want to use the Propeller IDE.
The Propeller Tool is the primary programming tool for the Propeller chip/HYDRA and allows
editing and viewing of the various files and statistics as builds are performed. Propeller chip
programs can be composed of both ASM and Spin code both with the extension “.spin” and
are compiled and assembled into their final form by the tool as a “binary” image that is
composed of a single 32 Kbyte image. However, you can code completely in Spin if you
wish, ASM is not necessary. But, you will find that 90% of all the drivers we have written for
the HYDRA/Propeller chip use ASM. Moving on, the tool has a number of standard Windows
IDE features, so the best thing to do is play with it as well as read the online Help.
I The HYDRA Hardware
Page 40 Game Programming for the Propeller Powered HYDRA
The Propeller Tool IDE for the Propeller Chip Figure 1:8
Also of note, there is a syntax highlighting technology that you may like or dislike, but it can
be disabled and customized via the menu options. The idea of the syntax highlighting is to
change the color of both the foreground and the background of your code to signify various
code blocks.
As noted, with this tool you can write programs in both Spin and ASM; however, when doing
so extra care must be taken when creating blocks or nesting levels since the HLL uses white
space to define “blocks”.
You can program the Propeller chip in a mixture of both HLL and Assembly, but
only
ASM or
HLL can run on a core at a time. However, the interesting thing is that all your code for you
final application is coalesced into a SINGLE 32 Kbyte binary image object that is loaded
directly into the Propeller chip’s RAM or onto an EEPROM for permanent storage when power
goes down. In the next section, we will install the software tool itself and cover the use of
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 41
the Propeller IDE is some detail, so you know your way around the menus and functionality
of the tool.
1.4.1 Installing the Propeller Tool and all the Software
Before we can do anything with the HYDRA we have to install all the sources for the HYDRA
along with the Propeller Tool software. First, you need to have all the sources on your
system, so step one is to simply copy the entire source tree from the CD to your PC. Insert
the
“HYDRA Software and Tools”
CD that came with your HYDRA into your CD ROM
drive, there is no Autoplay, so use Explorer or My Computer to access your CD ROM and
open up the CD drive. Inside you will find the following directory structure (more or less):
CD_ROOT:\
HYDRA\
SOURCES\
DESIGNS\
DRIVERS\
DEMOS\
TOOLS\
MEDIA\
DOCS\
EBOOKS\
GOODIES\
README.TXT
The contents of each of the directories is are follows:
HYDRA\ This is the main root directory of the entire CD, everything is within this
directory, thus to copy the entire CD, simply right click on this directory,
“copy” and then you can paste it anywhere you like on your hard drive, I
suggest placing it at the root of C:\ so the paths are short to the files within.
DESIGNS\ This directory contains electronic design schematics.
SOURCES\ This directory is the source directory that contains the entire source for the
book.
DRIVERS\ This directory contains any 3rd party drivers for the HYDRA and/or Propeller
chip.
DEMOS\ This directory contains copies all the HYDRA demos as well as any other
demos from the book. Some of this data is copied from the SOURCES\
directory, but is copied here to find more directly if you want to play with
demos.
I The HYDRA Hardware
Page 42 Game Programming for the Propeller Powered HYDRA
MEDIA\ This directory contains stock media and assets you can use for your game
and graphics development. All the media is royalty free and can be used for
anything you wish, even in commercial applications. However, you can not
license, sell, or otherwise transfer the files in the MEDIA\ directory as a
product.
DOCS\ This directory contains documents, tutorials, articles all relating the HYDRA,
Propeller chip, and game development.
EBOOKS\ In this directory you will find complete eBooks. Included specifically with the
HYDRA is
“The Black Art of 3D Game Programming”
which can be used
as a companion guide to this book for more advanced DOS game
programming techniques and PC development that are similar to working
with the HYDRA – a $60 value!
GOODIES\ This directory contains all kinds of cool little extras, so check it out and see
what made it on the CD!
README.TXT This is the README.TXT file for the CD, please read it carefully it has many
last minute changes, errata, and anything else you need to know.
Copying the Files to your Hard Drive
The best way to “install” all the HYDRA book materials is to simply drag and drop the entire
CD to your hard drive. There are a number of ways to do this: you can right click the HYDRA\
directory on the CD and select “Copy” then paste it into your hard drive at the desired
location, or you can “drag” the HYDRA\ directory to the desired location on your hard drive
and select “Copy Here.” However you do it, I suggest that you copy the files somewhere
“close” to the root of your hard drive, C:\, D:\, etc. so that if you do have to type in
command line instructions or file names they will be short. I suggest dragging HYDRA\ right
onto the root of your main drive, “C:\” for example, then you can work within the HYDRA\
directory directly.
Whenever copying files from a CD ROM directly to your PC’s hard drive, you may
have to reset the “Archive” or “Read-Only” flag(s) on the copied files, that is, if
you right click on a file or directory on a CD ROM and select “Properties” you
will see that the “Read-Only” flag is selected in the “Attributes” area of the
dialog. You can’t do anything about this on the CD, but when you copy the CD to
the hard drive you must reset this flag otherwise Windows won’t allow you to
“write” on top of a file or edit it.
To reset the read-only flag of your sources, simply select the HYDRA\ directory
after you have copied it to the hard drive, right click, select properties, then
uncheck the “Read-Only” flag, then click “Apply” and “OK”. Now, all the files
should have their read-only flags reset and you are ready to go.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 43
1.4.2 Installing the FTDI USB Drivers
The first thing you need to do is make sure you have the latest copy of the FTDI drivers
available on your PC. You can find the latest drivers for your particular Windows OS at:
http://www.ftdichip.com/Drivers/VCP.htm
The USB chip used on the HYDRA is the FT232RL model, so download the VCP (virtual COM
port) drivers for this particular chip and save them to a location on your hard drive. To keep
things organized, you might want to download the driver files into the
CD_ROOT:\HYDRA\DRIVERS\ directory on your hard drive and decompress them into
directories within to keep things organized.
Additionally, you will find that I have already provided you with the latest drivers at the time
this book was printed. They are located in the directory:
CD_ROOT:\HYDRA\DRIVERS\FTDI\
Note that in general throughout the book, I will refer to file paths with the
CD_ROOT:\HYDRA\... notation, this simply means the HYDRA\ directory on your
CD-ROM or hard drive, wherever it is, that’s the one I want!
Within the FTDI\ sub-directory you will find two more directories:
WINDOWS\
WINDOWS64\
The WINDOWS\ directory has the FTDI drivers for Windows XP, 2000, and 2003 while the
WINDOWS64\ directory has the drivers for the Windows XP 64-bit Edition (if you’re lucky
enough to have a computer this powerful). In any event, please read the release info.doc file
as well as any readme files within these directories, it will save you headaches if something
goes awry.
Now, here’s the tricky part. Depending on your PC, your OS, and your luck, you may or may
not have to do anything to install the drivers. In the best case, Windows will install the
hardware for you and you won’t have to do a thing, in the worst case you may have to install
the drivers, two times over in some cases. So, let’s hope for the best. The basic plan is that
we will power up the HYDRA, then insert the USB cable from the PC into the mini-B port on
the HYDRA (right side, top, above the PS/2 ports), when we do this Windows will detect the
hardware and “hopefully” have drivers for it already, if not, Windows will ask to install the
drivers and the usual dialogs will come up. Here are the steps to install the drivers, of course,
your particular PC/Windows setup might display varying dialogs, but this should give you a
good idea of what to expect.
I The HYDRA Hardware
Page 44 Game Programming for the Propeller Powered HYDRA
FTDI Driver Installation Steps
Step 1: I suggest shutting down all programs, performing a restart on your PC to make sure
that any pending software updates are complete and any lost resources or crashed programs
are reset, this way we have a fresh PC to work with.
Step 2: Power up the HYDRA and insert the black USB cable that came with the HYDRA kit
into a free USB port on your PC, then insert the other end of the USB cable into the mini-B
port on the HYDRA. The PC should detect the USB connection. If it doesn’t make sure the
HYDRA is powered, if you still have problems chances are you have a bad or unconnected
USB port on your PC, move the cable to another USB port on the PC.
Step 3: In the system tray to the bottom right of the Window’s desktop, you should see a
“new hardware found” alert and Windows will either install the drivers automatically, or it will
launch the Hardware Installation Wizards beginning with the “Found New Hardware Wizard”
as shown in Figure 1:9, select the “No, not at this time” search option and click <Next>.
Figure 1:9
The Found New
Hardware Wizard
Step 4: The next wizard asks you if you want to install the software automatically or from a
specific location. This is shown in Figure 1:10. Select the option “Install from a list of specific
location (Advanced)” option and click <Next>.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 45
Figure 1:10
The Software
Installation Origin
Step 5: The next dialog that comes up is the search path selection dialog as shown in Figure
1:11, select the top option “Search for the best driver in these locations.”, and only check the
“Include this location in the search” checkbox, then navigate with the <Browse> button to
find the location of the FTDI drivers as installed on your drive. They should be in this
directory:
CD_ROOT:\HYDRA\DRIVERS\FTDI\WINDOWSxx
...where “xx” denotes either the WINDOWS\ or WINDOWS64\ directory. Simply, select one of
these directories (or the directory of the freshly downloaded drivers if you downloaded them
from FTDI’s site) and hit <Next>.
Figure 1:11
Search Path
Option Dialog
I The HYDRA Hardware
Page 46 Game Programming for the Propeller Powered HYDRA
Step 6: The FTDI drivers may or may not have been Windows Logo certified yet, thus, if you
see the alert box shown in Figure 1:12, simply click “Continue Anyway”. The FTDI drivers
are under constant updates, so typically they are updated so frequently that they are never
stable enough to Windows Logo test.
Figure 1:12
The Windows Alert
for Non-Certified
Drivers
Step 7: If everything went right then you should see the file installation process start as
shown in Figure 1:13, nothing to do here, but cross your fingers and follow the white rabbit.
Figure 1:13
The FTDI Drivers
Installing
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 47
Step 8: If everything installed properly, you will see the hardware installation completed
dialog as shown in Figure 1:14, simple click <Finish> and you are done (hopefully).
Figure 1:14
The successful
installation of the FTDI
USB drivers
Step 9: Give the PC a moment, you
may
see it discover yet more USB hardware, if you do
then simply follow steps 1-8 again, and that should do it. When complete, give you your PC a
restart to make sure everything took and then you are ready to go!
1.4.3 Installing the Propeller Tool IDE
The Propeller Tool installer/Setup program is named PROPELLER_SETUP.EXE and is located
on the CD-ROM within the directory:
CD_ROOT:\HYDRA\TOOLS\PROPELLER\PROPELLER_SETUP.EXE
Either navigate to the CD-ROM or your local copy on your hard drive and launch the installer.
I The HYDRA Hardware
Page 48 Game Programming for the Propeller Powered HYDRA
When you launch the installer, you should see and installation splash logo and welcome
screen something like that shown in Figure 1:15. Simply click <Next> and continue. During
the installation, you will be prompted where to install the Propeller Tool, I suggest you install
it near the root of your drive preferably where you copied all the source files from the book.
Figure 1:15
Installing the
Propeller Tool IDE
Of course, you can always install it in the \Program Files directory, but many times your main
C:\ drive gets so full of application files that performance slows down quite a bit, so I prefer
to install applications on a drive other than my OS drive to optimize performance.
When the installer is complete you will be shown a standard finished alert, simply click
<OK>, <Done> and exit.
1.4.4 Testing the Propeller Tool IDE
Before we get into any discussions of the tool itself, let’s
confirm that everything is working. On the Windows
desktop, you should see an icon to launch the Propeller
Tool, as shown in Figure 1:16.
Double-click the icon and the Propeller Tool should launch. If you do not see and icon, then
click <Start Menu All Programs Parallax Inc Propeller Tool v1.0> to launch the
program. When the program launches, if it gives any warnings or alerts just click <OK> or
<Next> and ignore them. You should then see the main IDE interface shown in Figure 1:8
without any files open of course.
Figure 1:16
The Propeller
Tool Icon
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 49
Loading a Program in the HYDRA
Now, for the fun part, let’s try and load something into the HYDRA. Make sure the HYRDA is
powered up and the USB cable is plugged into the HYDRA itself from your PC. Plug your
game controller into the left port. And of course have your HYDRA’s A/V cables plugged into
your TV set and the input on your TV set to “Video Input.” Also, you might want to take out
the game cartridge if you have it plugged in, doesn’t matter, but let’s all stay on the same
page.
Now, we are going to load a game into the HYDRA. Here’s the steps:
Step 1: From the main menu go to <File Open> and browse your hard drive or CD-ROM
for the HYDRA sources, they are located in CD_ROOT:\HYDRA\SOURCES\*.*.
Step 2: Locate the file REM_ALIENINVADER_013.SPIN and open it. The program should
load into the editor and you will see the source. The game is composed of a number of
objects.
Step 3: Press <F10> on the keyboard, this will compile all the files (you will see it happen),
then the Propeller Tool will search through all the COM ports and see if it can find the
HYDRA/Propeller chip connected to it, once it does it will start a RAM only download, that is
the program will be programmed into the Propeller chip RAM, but not the EEPROM.
Figure 1:17
Alien Invaders
running on the HYDRA
Step 4: If everything went well, the HYDRA will reboot, then you will see the game start
running and something like that shown in Figure 1.12 will display on your TV set.
Try the game out for a moment, then hit the RESET button on the HYDRA, notice that
Parallaxaroids reloads? This is because it’s still on the onboard EEPROM. If you wanted to
overwrite the EEPROM then you could have pressed <F11>.
I The HYDRA Hardware
Page 50 Game Programming for the Propeller Powered HYDRA
Now that you have successfully installed the IDE and loaded a program and ran it, it’s time to
learn a little bit more about the Propeller Tool itself.
If you had trouble then look below for some trouble shooting tips based on messages from
the IDE and what you see on the screen:
Trouble Shooting Tips
IDE Message - “Propeller Chip Not Found” – This means either you have the power off
on the HYDRA, the USB cable is not plugged in, or you didn’t install the USB driver.
No Video – If the program downloaded fine, then make sure you have the video output and
audio output from the HYDRA plugged into the correct ports on the TV’s video input, also,
make sure you have the TV set for external video input mode.
No Audio – Good! There is none, this demo is so big, we couldn’t fit sound in!
1.5 Propeller Tool IDE Primer
In this section we are going to briefly discuss the Propeller IDE and its functionality. This is
by no means a complete treatise on the Propeller tool and is not an introduction to
programming, but simply to familiarize you with the use of the tool and its various functions,
menus, and short cuts. For a more information please read the Propeller tool’s online help.
Editor’s Note: You may also refer to the
Propeller Manual v1.0
, which is the source of the
information in this section. It is available for purchase or free PDF download from
www.parallax.com/propeller.
1.5.1 Propeller Tool Interface Overview
Referring to Figure 1.13, the IDE is composed of a number of panes. Panes 1, 2, and 3 are
all part of the “Integrated Explorer”. The Integrated Explorer is the region to the left of the
main text Editor pane (pane 4) that provides views of the project you’re working on as lists
of the folders and files on disk.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 51
The Propeller Tool’s main window contains
four major sections or “panes.” Figure 1:18
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
We’ll take a look at each of the four panes in turn in a moment:
Pane 1: Object View Pane
Pane 2: Recent Folders Field and Folder List
Pane 3: File List and Filter Field
Pane 4: Editor Pane
I The HYDRA Hardware
Page 52 Game Programming for the Propeller Powered HYDRA
The Integrated Explorer and its components
can be resized via the splitter bars. Figure 1:19
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
The Integrated Explorer is separated from the Editor pane by a tall, vertical splitter bar that
can be resized with the mouse at any time by simply dragging. The Integrated Explorer can
even be hidden by resizing it down to nothing (left click and drag its vertical splitter bar), by
selecting <File Hide Explorer> from the main menu bar, or by using the keyboard shortcut
<CTRL + E>. The menu and shortcut options toggle the Integrated Explorer between the
following modes:
1. Visible (set to its last known size)
2. Invisible (completely collapsed into the left edge of the Propeller Tool
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 53
Pane 1: Object View Pane
Pane 1 is the Object View pane. Spin, the Propeller chip’s native language is a loosely
“object-based” language, where objects are external files that contain executable source
code and even other objects. Thus, a Propeller Project can be made up of multiple objects or
in other words multiple source files, the concept is similar to including source files in C/C++
with the pre-processor. The Object View displays the hierarchical view of the most recently
compiled project providing visual feedback on the structure of your project. Using the Object
View, you can determine what objects are included in your project, how they fit together
with other objects, their physical location on disk (working folder, library folder or editor
only), and potential circular references.
Pane 2: Recent Folders Field and Folder List
Pane 2 contains two components:
1. The Recent Folders field
2. The Folder List
These two components work together to provide navigational access to the disk drives
available on your PC. The Folder List displays a hierarchical view of folders within each disk
drive and can be manipulated in a similar fashion as the left pane of the Windows Explorer.
The Recent Folders field (above the Folder List) provides a drop-down list of the most recent
folders you’ve loaded files from. Selecting a folder from the Recent Folders field causes the
Folder List to immediately navigate to that folder. In addition, if you select a folder in the
Folder List which exists in the Recent Folders list, the Recent Folder field will automatically
update itself to display that item.
Pane 3: File List and Filter Field
Pane 3 contains two components:
1. The File List
2. The Filter field (bottom)
The File List displays all the files contained in the folder selected from the Folder List which
match the filter criteria of the Filter field. The File List can be used in a similar fashion as the
right pane of Windows Explorer.
The Filter field (below the File List) provides a drop-down list of file extensions or filters to
apply to files in the File List. Typically it will be set to show Spin files only (those with “.spin”
file extensions) but can also be set to show text files (.txt) or all files (*.*). If you navigate
to a folder and don’t see the files you expect to see, make sure that the current filter in the
Filter field is set appropriately.
I The HYDRA Hardware
Page 54 Game Programming for the Propeller Powered HYDRA
Files in the Files List can be opened and viewed in the editor by double clicking on the file,
dragging it into the Editor pane itself, or right clicking and selecting Open from the shortcut
menu.
Pane 4: Editor Pane
Pane 4 is the Editor pane. The Editor pane provides a view of the open Spin source code
files and is the general work area where you can review and edit all the source code objects
for your project. Each file (source code object) you open is organized within the Editor pane
as an individual tab named after the file it contains. The currently active editor tab is
highlighted differently than the rest (bolded). You can have as many files open at once as
you wish, limited only by memory. As the number of files increases and the tab control runs
out of screen space, scroll arrows will appear on the right hand side of the tab control
allowing you to navigate through the off-screen files.
You can switch between open tabs by:
1. Clicking on the desired tab with the mouse.
2. Pressing <ALT + Left Arrow> or <ALT + Right Arrow>
3. Pressing <CTRL+TAB> or <CTRL+SHIFT+TAB>
Figure 1:20
Hover the mouse
over an edit tab to
see the full path and
file name of the
contained file.
If you hover the mouse pointer over a tab long enough it will display a hint message with the
full path and filename of the file it represents as shown in Figure 1:20.
The source code inside each file being edited is automatically syntax highlighted. Both, the
foreground and background colors are highlighted to help distinguish block types, element
types, comments vs. executable code, and so forth. You can turn this off if you wish by
selecting the Tools/Option menu item from the main menu and altering the editor syntax
highlighting settings.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 55
Each file opened in an edit tab can display source code in one of four views:
1. Full Source view
2. Condensed view
3. Summary view
4. Documentation view
The view mode can be changed individually for each file edit tab by either:
1. Selecting the respective radio button with the mouse (located in a row under the tab
control).
2. Pressing <Alt + Up Arrow> or <Alt + Down Arrow>.
3. Pressing <Alt+ [letter] > where [letter] is the underlined hot key of the desired view.
4. Pressing <Alt> and rotating the mouse wheel (if you have one) up or down.
The Documentation view can not be entered if the object can not be fully
compiled at that moment.
Since a project can consist of many objects, developing a project can be awkward unless you
can see both the object you’re working on and the object you’re interfacing to at the same
time. The Editor pane helps here by allowing its edit tabs to be dragged and dropped to
different locations as shown in Figure 1:21. For example, once multiple objects are open,
you can use the left mouse button to select and drag the tab of an object down towards the
bottom half of the Editor pane and simply drop it there. The display changes to show you a
new tab region where you just dropped that edit tab. You can continue to drag and drop
edit tabs to this new region if you wish.
I The HYDRA Hardware
Page 56 Game Programming for the Propeller Powered HYDRA
Figure 1:21
Step 1: To see more than one object’s
source code simultaneously, left click and
drag an edit tab to a lower region of the
Editor Pane.
Step 2: Release the button to drop the
edit tab. The edit tab and its contents now
appear in the new region.
Step 3: Repeat steps 1 and 2 as necessary
for other edit tabs and resize both regions
using the horizontal splitter between them.
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 57
The vertical size of each of the edit regions can be changed by dragging the horizontal
splitter separating them. Of course, the objects you’re interfacing to can be viewed in
whatever mode is convenient at the moment (Full Source, Condensed, Summary, or
Documentation) while the object you’re developing remains in the Full Source view (the only
editable view).
The Editor pane also allows undocking its tabs and for them to be dragged and dropped
completely outside of the Propeller Tool as shown in Figure 1:22. When an edit tab is
undocked, the new tabs occupy a new window that can be manipulated independently of the
main Propeller Tool application window. This is particularly useful for development on multi-
monitor systems.
Figure 1:22
Step 1: If desktop space allows, you can
even drag edit tabs outside the
application itself; left click and drag an
edit tab to a region outside the Propeller
Tool.
Step 2: Release the button to drop the
edit tab; it will drop into a form of it’s
own that can be moved and sized
independent of the Propeller Tool. You
can drag and drop more edit tabs into
this new form also.
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
I The HYDRA Hardware
Page 58 Game Programming for the Propeller Powered HYDRA
Figure 1:23
The Status Bar
The Status Bar at the bottom of the Propeller Tool is separated into six panels as shown in
Figure 1:23. Each panel displays useful information at various stages of the development
process.
Panel 1 – Displays the row and column position of the editor’s caret in the currently active
edit tab.
Panel 2 – Displays the “modified” status of the current edit tab; if it’s blank then the current
line hasn’t been modified, if the panel reads “modified” then the current line has been
modified, lastly the panel can indicated “read-only.”
Panel 3 – Display the current edit mode:
1. Insert (default)
2. Align (available for “.spin” files only)
3. Overwrite mode
The edit modes can be toggled through by pressing the Insert key.
Panel 4 – Displays the compilation status of the current edit tab; blank, meaning uncompiled
or “Compiled” meaning the source has recently been compiled. This panel indicates whether
or not the current source code is still in the form it was in when it was last compiled. If the
code has not been changed since the last compile operation, this panel will say “Compiled.”
Panel 5 – Displays context sensitive information about the current edit tab’s source code if
that code has not been changed since the last compile operation. Move the edit tab’s cursor
to various regions in the source such as CON, DAT, or PUB/PRI blocks to see information
relating to that block.
Panel 6 – Displays temporary messages about the most recent operation(s). This is the
area of the Status Bar where error messages, if any, from the last compile operation are
displayed until another message overwrites it. This area also indicates successful
compilations, font size changes, and other status information.
The entire Status Bar displays hints describing the function of each menu item
on the menu bar as well as various other items when you let the mouse pointer
hover over those items.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 59
1.5.2 Propeller Tool Menu Items
The following lists outline the various menu items and options controlled via the application
menu items.
File Menu
New Create a new edit tab with a blank page. Any existing edit
tabs are unaffected.
Open… Open a file in a new edit tab with the Open file dialog.
Open From… Open a file in a new edit tab from a recently accessed folder
using the Open file dialog.
Save Save current edit tab’s contents to disk using the existing file
name, if applicable.
Save As… Save current edit tab’s contents to disk with a new file name
using the Save As dialog.
Save To… Save current edit tab’s contents to disk in a recently
accessed folder using the Save As dialog.
Save All Save all unsaved edit tab’s contents to disk using their
existing names, if applicable.
Close Close current edit tab (will prompt if file is unsaved).
Close All Close all edit tabs (will prompt for any files unsaved).
Select Top Object File… Select the top object file of current project. This setting is
used for all of the Compile Top… operations and remains
until changed.
Archive
Project… Collect all objects and data files for the project shown in
Object View and store them in a compressed (.zip) file along
with a “readme” file containing archive and structure
information. The compressed file is named after the
project’s top file with “Archive” plus the date/time stamp
appended and is stored in the top file’s work directory.
Project + Propeller Tool Perform the same task as above but add the entire Propeller
Tool executable to the compressed file.
I The HYDRA Hardware
Page 60 Game Programming for the Propeller Powered HYDRA
Hide/Show Explorer Hide or show the Integrated Explorer panels (left side of the
application window).
Print Preview… View a sample of the output before printing.
Print… Print the current edit tab’s contents.
<recent files> The menu area between the Print… and Exit items displays
the most recently accessed files, up to ten. Selecting one of
these items opens that file. Point the mouse at a recent file
menu item to see the full path and file name in the status
bar.
Exit Close the Propeller Tool.
Edit Menu
Undo Undo the last edit action on the current edit page. Each edit
page retains its own undo history buffer until closed.
Multiple undo actions are allowed, limited only by memory.
Redo Redo the last undone action on the current edit page. Each
edit page retains its own redo history buffer until closed.
Multiple redo actions are allowed, limited only by memory.
Cut Delete the selected text from the current edit page and copy
it to the Windows clipboard.
Copy Copy the selected text from the current edit page to the
Windows clipboard.
Paste Paste text from the Windows clipboard to the current edit
page at the current caret position.
Select All Select all text in the current edit page.
Find / Replace… Open the Find/Replace dialog; see Find/Replace Dialog on
page 49 for details.
Find Next Find the next occurrence of the last search string entered
into the Find/Replace dialog.
Replace Replace the current selection with the string entered into the
Replace field of the Find/Replace dialog.
Go To Bookmark Go to bookmark 1, 2, 3… (visible only when bookmarks are
shown).
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 61
Text Bigger Increase the font size in every edit page.
Text Smaller Decrease the font size in every edit page.
Preferences… Open the Preferences window. Users can customize many
settings within the Propeller Tool using this feature.
Run Menu
Compile Current
View Info… Compile source code in current edit tab and, if successful,
display Object Info form with the results. The Object Info
form displays many details about the resulting object
including object structure, code size, variable space, free
space and redundancy optimizations.
Update Status Compile source code in current edit tab and, if successful,
update the status info on the Status Bar for every object in
the project.
Load RAM Compile source code in current edit tab and, if successful,
download the resulting application into Propeller chip’s RAM
and run it.
Load EEPROM Compile source code in current edit tab and, if successful,
download the resulting application into Propeller chip’s
EEPROM (and RAM) and run it.
Compile Top
View Info… Same as Compile Current View Info except compilation is
started from the file designated as the “Top Object File.”
Update Status Same as Compile Current Update Status except
compilation is started from the file designated as the “Top
Object File.”
Load RAM Same as Compile Current Load RAM + Run except
compilation is started from the file designated as the “Top
Object File.”
Load EEPROM Same as Compile Current Load EEPROM + Run except
the compilation is started from the file designated as the
“Top Object File.”
I The HYDRA Hardware
Page 62 Game Programming for the Propeller Powered HYDRA
Identify Hardware… Scan available ports for the Propeller chip and, if found,
display the port it is connected to and the hardware version
number.
Help Menu
Propeller Tool… Display on-line help about the Propeller Tool.
Spin Language… Display on-line help about the Spin language.
Assembly Language… Display on-line help about the Propeller Assembly language.
Example Projects… Display on-line help containing example Propeller Projects.
View Character Chart… Display the interactive Parallax Character Chart. This
character chart shows the Parallax font’s character set in
three possible views: Standard Order, ROM Bitmap and
Symbolic Order.
View Parallax Website… Open up the Parallax website using the computer’s default
web browser.
E-mail Parallax Support… Open up the computer’s default email software and start a
new message to Parallax support.
About… Displays the About window with details about the Propeller
Tool.
1.5.3 Object View Pane Details
The Object View displays a hierarchical view of the project you most recently compiled
successfully. There are two Object Views in the Propeller Tool:
1. The Object View at the top of the Integrated Explorer in the main application’s
window
2. The Object Info View in the upper left of the Object Info form.
Both of these Object Views function in a similar fashion. The Object View provides visual
feedback on the structure of the most recent compilation as well as information for each
object within the compiled project.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 63
Figure 1:24
Example Object View
display showing the
structure of the
“JTC_B_Buster_005”
compilation.
Referring to Figure 1:19, the Object View indicates the structure of the “JTC_B_Buster_005”
game application. In this example, the “JTC_B_Buster_005” object is the top object file and
it includes a number of sub-objects including; “cop_drv_010x”, “NS_sound_drv_040”,
“bbuster_tiles_001”, etc. Notice that the file names of the top level object and sub-objects do
not include the file extension, its assumed to be “.spin” unless they are data files.
The icons to the left of each object name indicate the folder that the object exists in. There
are the four color coded possibilities:
Yellow Object is within the Work Folder.
Blue Object is within the Library Folder.
Stripe Object is in Work Folder, but another object with the same name is also
being used from the Library Folder.
Hollow Object is not in any folder because it has never been saved.
The following paragraphs describe the folder types.
Work Folder
The Work Folder (yellow) is the folder where the top object file exists. Every project has
one, and only one, work folder.
Library Folder
The Library Folder (blue) is where the Propeller Tool’s library objects exist, such as those that
came with the Propeller Tool software. The Library Folder is always the folder that the
Propeller Tool executable started from, and every object (file with .spin extension) within it is
considered to be a library object.
I The HYDRA Hardware
Page 64 Game Programming for the Propeller Powered HYDRA
Striped Folders
Objects with striped icons indicate that an object from the work folder and an object from
the library folder each refer to a sub-object of the same name and that sub object happens
to exist in both the work and library folders. This same-named object may be:
1. An exact copy of the same object,
2. Two versions of the same object, or
3. Two completely different objects that just happen to have the same name.
Regardless of the situation, it is recommended that you resolve this potential problem as
soon as possible since it may lead to problems later on, such as not being able to use the
Archive feature.
Hollow Folders
Objects with hollow icons indicate that the object was created in the editor and has never
been saved to any folder on the hard drive. This situation, like the one mentioned above, is
not an immediate problem but can lead to future problems if it is not addressed soon.
Using the mouse to point at and select objects can provide additional information as well.
Clicking on an object within the Object View opens that object into the Editor pane. Left
clicking opens that object in Full Source view, right clicking opens it in Documentation view
and double clicking opens it, and all its sub-objects, in Full Source view. If the object was
already open, the Editor pane simply makes the related edit tab active and switches to the
appropriate view; Full Source for a left click or double click, or Documentation for a right
click.
1.5.4 Info Object View (F8)
The Info Object View shown in Figure 1:25 works exactly like the Object View with a few
exceptions:
1. Clicking on an object within the Info Object View updates the Object Info display
with information pertaining to that object.
2. Double-clicking on an object within the Info Object View opens that object in the Edit
pane.
3. Data files are not selectable in the Info Object View.
RAM Usage Panel
The RAM Usage panel displays statistics about RAM allocation of the object currently selected
in the Info Object View. The horizontal bar gives a summary view of the entire RAM with a
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 65
color legend and numerical details below it. For example, Figure 1:25 shows that the
“JTC_B_Buster_005” object consumes 6057 LONGs (24228 bytes) for program space and 253
LONGs (1012 BYTEs) for variable space, leaving only 1878 LONGs (7512 BYTEs) free.
Figure 1:25
Object Info Form Showing
information about the
“JTC_B_Buster_005.Spin”
Project
Clock Panel
The clock panel, under the RAM Usage panel, displays the clock/oscillator settings of the
object currently selected in the Info Object View. For example, Figure 1.20 shows that the
“JTC_B_Buster_005” object configured the clock for XTAL2 + PLLX8 mode, at 80,024,000 Hz
and an XIN frequency of 10,003,000 Hz.
I The HYDRA Hardware
Page 66 Game Programming for the Propeller Powered HYDRA
Hex View
The Show/Hide Hex button shows or hides the detailed object hex view, as shown below in
Figure 1:26. The hex view shows the actual compiled object data, in hexadecimal, that are
loaded into the Propeller’s RAM/EEPROM upon download.
Example Object Info Form display with the Object
Hex View Open, Showing the Hex Values of the
“JTC_B_Buster_005” Compilation
Figure 1:26
The buttons under the hex display allow for downloading and saving of the currently
displayed hex data. The first three buttons, <Load RAM + Run>, <Load EEPROM + Run>,
and <Load EEPROM>, perform the same function as the similarly named menu items under
the <Run Compile Current> main menu item. It’s important to note that they use the
current object (the one selected in the Info Object View) as the source to download. In
other words, you can actually select a sub-object from the project and download just that; a
practical procedure only if that object were designed to run completely on its own.
The last two buttons, <Save Binary File>, and <Save EEPROM File>, each save the hex data
from the currently selected object to a file on disk. <Save Binary File> saves only the
portion actually used by the object; the program data, but not variable or stack/free space.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 67
<Save EEPROM File> saves the entire EEPROM image, including variable and stack/free
space. Use <Save EEPROM File> if you wish to have a file that you can load into an
EEPROM programmer for production purposes.
1.5.5 The Character Chart
The Character Chart window is available from the <Help View Character Chart…> menu
item. It shows the entire character set for the Parallax Font that is used by the Propeller
Tool and is also built into the ROM of the Propeller chip. There are three views in the
Character Chart: Standard Order, ROM Bitmap, and Symbolic Order.
In each of the three views, the mouse, left mouse button, cursor keys and enter button can
be used to highlight and select a character. If clicked (or enter pressed), the highlighted
character will be entered into the current edit tab at the current cursor location. As a new
character is highlighted, the title bar and info bar of the window updates to show the name,
size and address information for that character. Moving the mouse wheel up or down
changes the font size displayed in this window.
Standard Order
Figure 1:27 displays the characters in the standard ANSI numerical order. The exponent (-1)
in the first row of the display is selected in this example (light grey highlight).
Parallax Character Chart
(Standard Order) Figure 1:27
The information at the bottom of the window shows the font size, in points, and the
character’s location in the character set in decimal, hexadecimal, and Unicode.
I The HYDRA Hardware
Page 68 Game Programming for the Propeller Powered HYDRA
The Unicode value is the address of the character in the True Type® Font file that
is used by the Propeller Tool. The decimal and hexadecimal values are the
logical addresses of the character in the character set within the Propeller chip
and correspond to that location in the ANSI character set used by most
computers.
ROM bitmap
ROM Bitmap, Figure 1.23 shows the characters in a way representative of how they are
stored in the Propeller’s ROM.
Figure 1:28
Parallax Character
Font Chart
(ROM Bitmap)
This view uses four colors, white, light gray, dark gray, and black, to represent the bit
pattern of each font character. Each character, in the Propeller’s ROM, is defined with two
bits of color (four colors per row in each character cell). The rows of each pair of adjacent
characters are overlapped in memory for the purpose of creating the run-time characters
used to draw 3D buttons with hot key and focus indicators. The information at the bottom of
the window shows the font size, in points, and the selected character’s pixel data address
range in the Propeller’s ROM.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 69
Symbolic Order
Symbolic Order orders the characters arranged categorically as shown in Figure 1.24. This is
useful for finding the special characters in the Parallax font for depicting timing diagrams,
lines, arrows, and schematics.
Parallax Character Font Chart
(Symbolic Order) Figure 1:29
I The HYDRA Hardware
Page 70 Game Programming for the Propeller Powered HYDRA
1.5.6 View Modes, Bookmarks and Line Numbers
While developing objects, or conversing about them with other users, it may sometimes be
difficult to quickly navigate to certain regions of code simply because of the size of the file
itself or because large sections of code and comments obscure the desired section. There
are a number of features built into the Propeller Tool to assist with this problem, including
different View Modes, Bookmarks and Line Numbers.
View Modes
Each edit tab can display an object’s source in one of four view modes:
1. Full Source mode
2. Condensed mode
3. Summary mode
4. Documentation mode
Full Source view displays every line of source code within the object and is the only view
that supports editing.
Condensed view hides every line that contains only a code comment as well as contiguous
lines that are blank, showing only compilable lines of code.
Summary view displays only the block heading lines (CON, VAR, OBJ, PUB, PRI, and DAT);
a convenient way to see the entire object’s structure at a glance.
Documentation view displays the object’s documentation generated by the compiler from
the source code’s doc comments.
By briefly switching to another view you may be able to locate the routine or region of code
desired. For example, Figure 1:30 (top) shows the Graphics object open in an edit page. If
you were having trouble finding the “plot” routine within the source code, you could switch to
the Summary view (middle) locate the “plot” routine’s header line and click the mouse on
that line to place the cursor there, then switch back to Full Source view (bottom). Keep your
eye on the line with the cursor because the code will expand to full view above and below
the line where the cursor is. The view mode can be changed a number of ways.
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 71
Figure 1:30
Can’t find a routine in an object?
Step 1: Select Summary Mode.
Step 2: Click on the routine’s line.
Step 3: Select Full Source mode again; the
code re-expands around the cursor’s line.
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
I The HYDRA Hardware
Page 72 Game Programming for the Propeller Powered HYDRA
Bookmarks
You can also set bookmarks on various lines of each edit page’s source code to quickly jump
to desired locations. Figure 1:31 shows an example of two bookmarks set in the Graphics
object’s edit tab. To enable bookmarks, press <Ctrl+Shift+B> to make the Bookmark
Gutter visible; a blank area to the left of the edit page. Then click the mouse in the
Bookmark Gutter next to each line you want to be able to navigate to quickly. Finally, from
anywhere in the page, press <Ctrl+#> where # is the bookmark number that you want to
go to; the cursor will instantly jump to that location. Up to 9 bookmarks (1 – 9) can be set in
each edit tab. The bookmarks are not saved in the source code; however, the bookmark
settings of the last 10 files accessed are remembered by the Propeller Tool and restored
upon reopening those files.
Figure 1:31
Edit tab with Bookmarks
Enabled and two Bookmarks
Set
Images on this page from Propeller Manual v1.0 courtesy of Parallax Inc.
Line Numbers
At any time, you can enable or
disable line numbers in the edit
tab. Line Numbers show up in the
Line Number Gutter, next to the
Bookmark Gutter as shown in
Figure 1:32. Lines are
automatically numbered as they
are created; they are a visual item
only and are not stored in the
source code. Line Numbers and
Bookmarks are independent of
each other and can be enabled or
disabled individually.
Figure 1:32
Edit tab with
bookmarks and
line numbers
enabled
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 73
Edit Modes
There are three edit modes provided by the Editor pane:
1. Insert (default)
2. Align (available for “.spin” objects only)
3. Overwrite
You can switch between each mode by using the <Insert> key. The current mode is
reflected by both the caret/cursor shape and panel 3 of the lower status bar.
Figure 1:33
Insert Edit Mode: Caret is the standard
blinking, vertical bar and the status bar
shows “Insert.”
Align Edit Mode: Caret is a blinking
underline and the status bar shows
“Align.”
Overwrite Edit Mode: Caret is a blinking,
solid block and the status bar shows
“Overwrite.”
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
I The HYDRA Hardware
Page 74 Game Programming for the Propeller Powered HYDRA
Insert and Overwrite Modes
The Insert and Overwrite modes are similar to that of many other text editors. These are the
only two modes available to edit tabs containing files other than Propeller “.spin” objects,
such as “.txt” files.
Align Mode
The Align mode is a special version of the Insert mode designed specifically for maintaining
source code. To understand Align mode, we first need to consider common programming
techniques. There are two very common practices used when writing modern source code:
indention of code and alignment of comments to the right of code. It is also common for
source code to be viewed and edited using more than one editor application. Historically,
programmers have used either tabs or spaces for indention and alignment purposes, both of
which prove problematic. Tab characters cause alignment issues because some editors use
different sized tab settings than others. Both tab and space characters cause alignment
issues because future edits cause right-side comments to shift out of alignment.
For Spin code, the Propeller Tool solves this problem first by disallowing tab characters (Tab
key presses emit the proper number of space characters), and second by providing the Align
edit mode. While in the Align mode, characters inserted into a line affect neighboring
characters but not characters separated by more than one space. The result is that
comments and other items separated by more than one space maintain their intended
alignment for as long as possible.
Since the Align mode maintains existing alignments as much as possible, much less time is
wasted realigning elements due to future edits by the programmer. Additionally, since
spaces are used instead of tab characters, the code maintains the same look and feel in any
editor that displays it with a mono-spaced font.
The Align mode isn’t perfect for all situations, however. We recommend you use Insert
mode for most code writing and briefly switch to Align mode to maintain existing code where
alignment is a concern. The Insert key rotates the mode through Insert Align
Overwrite and back to Insert again. The Ctrl+Insert key shortcut toggles only between
Insert and Align modes. A little practice with the Align and Insert modes will help you
program more time-efficiently.
Note that non-Spin source (without a .spin extension) does not allow the Align mode. This is
because, for non-Spin source, the Propeller Tool is designed to maintain any existing tab
characters and to insert tab characters when the Tab key is pressed in order to maintain the
original intent of the file, which may be a tab-delimited data source for a Spin program or
other use where tab characters are desired.
Block Selections
HYDRA System Overview 1
Game Programming for the Propeller Powered HYDRA Page 75
In addition to normal text selections made with the mouse, the Propeller Tool allows block
selections (rectangular regions of text). To make a block selection, first press and hold the
Alt key, then left-click and drag the mouse to select the text region. After the selection is
made, cut and copy operations behave as they do with other selections. Figure 1:34
demonstrates block selection and movement of the text block with the mouse.
Figure 1:34
Original code. We’d like to
move the “LCD Screen Addr’’
comments to the right of the
PrintMode routine.
First press and hold the Alt
key. Next left-click and drag
the mouse to make the
selection.
Finally, click and drag (from
anywhere in the selected
block) and drop the selection
in the desired location.
Image from Propeller Manual v1.0 courtesy of Parallax Inc.
I The HYDRA Hardware
Page 76 Game Programming for the Propeller Powered HYDRA
1.5.7 Keyboard Shortcuts and Propeller Quick Reference Guide
There are many keyboard shortcuts built into the Propeller Tool. Complete shortcuts lists in
two formats, one categorically organized and one listed by key, are available through the
Propeller Tool’s Help menu.
Also available through the Help file is a 4-page condensed guide to the Spin and Propeller
Assembly programming languages organized in table format for quick reference.
1.6 Summary
In this chapter we inventoried the HYDRA, tried some games and demos, got the software
and drivers loaded onto your PC an took a look at the Propeller Tool IDE. In the next chapter
and the chapters to follow we are going to take a look at each of the hardware sub-systems
of the HYDRA, so you can at least have a general idea of how they work and how to make
modifications and hacks to them if you want to void your warranty! See you in Chapter 2.
5V & 3.3V Power Supplies 2
Game Programming for the Propeller Powered HYDRA Page 77
Chapter 2: 5V
& 3.3V Power
Supplies
The HYDRA, like any embedded system, needs power, so what better place to start
discussing the hardware than with the power supply design? In this chapter, we are going to
cover the following topics:
The 3.3V power supply.
The 5.0V power supply.
The HYDRA Power Supply Design Figure 2:1
I The HYDRA Hardware
Page 78 Game Programming for the Propeller Powered HYDRA
2.1 General Power Supply Overview
The HYDRA game console has a dual 3.3 V/ 5.0 V power supply system that is fed by a single
9 VDC unregulated input from a wall adapter. The supply designs are shown in Figure 2:1 for
reference.
The HYDRA is a mixed voltage system since the Propeller uses 3.3 V, but the keyboard and
mouse need 5.0 V, as do potential future peripherals; thus both supplies are available and
can each supply up to 500 mA for all your needs. Additionally, the power supplies are
exported to the 20-pin expansion port for plug-in cartridges. Initially, the power is fed in from
a 2.1 mm female power jack at J1, the voltage should be from 9-12 VDC, but does NOT need
regulation, unregulated DC is fine and hopefully there is a fat 2,000 – 20,000 µF filter cap on
the output to smooth the DC.
The wall adapter that comes with the HYDRA is something like that shown in Figure 2:2, it’s
a standard 300-500 mA 9 V DC adapter you can find almost anywhere, the only important
detail is that the TIP is
positive
and the RING must be
negative
. If you are having trouble
seeing the schematic of the power supplies, you can find an electronic version of it in higher
resolution here (as well as all the other circuits discussed in the upcoming chapters):
CD_ROOT:\HYDRA\DESIGNS\hydra_power_01.gif
Figure 2:2
The 9 VDC wall adapter that
comes with the HYDRA kit
5V & 3.3V Power Supplies 2
Game Programming for the Propeller Powered HYDRA Page 79
2.2 The 3.3 V Power Supply
The 9 V raw power is fed through the power jack at J1 and into the power switch at J2 then
into the regulation circuit based on a standard UA78M33 linear regulator. The UA78M33 is a
very hearty regulator with built-in protection so we don’t have to add diodes and other
assorted protection components to it. Referring back to Figure 2:1, the capacitors C1, C2,
and C3 provide filtering on the input and output. The large 10 µF tantalum on the output
helps provide large currents on demand. When powering the HYDRA up, R1 and D1 provide
a “power good” indicator, and you should see the LED illuminate to indicate the supply is
working. Of course, there is no substitute for a voltmeter if you really want to check the
voltage and be sure if you are having power problems.
The Propeller chip is a 3.3 V device, so this supply is the main supply of the system that
powers the Propeller; however, add-in cards plugged into the expansion slot might want to
use a lot of current, thus a regulator that can provide at least 500 mA of current is desired
just in case.
2.3 The 5.0 V Power Supply
Many people supply the 3.3 V supply from the 5 V supply; this is a mistake. Any power
supply designer will tell you that, not only do you cut your output load of your 5 V supply
down since it’s constantly working to supply your 3.3 V supply, you add the entire path of the
5 V supply into your 3.3 V system’s final output since whenever the 3.3 V supply pulls, it pulls
through the 5.0 V which can lead to pulling your 5.0 V supply down many hundreds of
millivolts. Moreover, if you want to rate your 3.3 V at 500 mA and your 5.0 V at 500 mA, you
can’t! You need to rate your 5.0 V at 1 A(!) since it is responsible for supplying both front
ends to the power. Finally, if the 5 V goes bad, then they both go bad, with two separate
paths; if one supply goes bad, you still have the other and many vital systems may still
operate.
With that in mind, the 5.0 V supply is identical to the 3.3 V supply, but instead of a 3.3 V
linear regulator, the 5.0 V supply uses a 5.0 V regulator, the UA75M05. Again, this is a very
robust regulator with built-in protection, so we can save parts. Also, the input and output
filtering is very forgiving and as long as you have 0.1 µF – 1.0 µF on both the input and
output, the regulator will work great, but I like to throw a nice 10 µF tantalum on all my
power supplies’ outputs for a low-impedance path for current sourcing.
Lastly, the 5.0 V supply has a “power good” indicator constructed of R2 and D2 that provides
some indication the supply is working. Both power indicators are of course up front on the
HYDRA by the power switch.
I The HYDRA Hardware
Page 80 Game Programming for the Propeller Powered HYDRA
2.4 Summary
The power supplies for the HYDRA are rather simplistic; all the work is done by the
regulators. Also, you might wonder “Can the HYDRA can be powered from battery?”
Absolutely, a 9 V transistor battery “will” work, for a while, but I suggest getting a series 6-
AA cell battery pack to create a total of 9 V (6 × 1.5 V), and then connect a 2.1 mm power
connect into the end of the cable and connect it to your pack (most battery packs like this
have a 9 V transistor battery clip, so I usually just solder on a cable to my 2.1 mm jack). I
have found that using standard rechargeable batteries, I can run the HYDRA for hours in this
configuration. Figure 2:3 shows a picture of my little battery pack I use for the HYDRA.
Figure 2:3
An ad-hoc HYDRA battery pack
Reset Circuit 3
Game Programming for the Propeller Powered HYDRA Page 81
Chapter 3:
Reset Circuit
In this incredibly short chapter we are going to discuss the HYDRA’s reset circuitry including:
Reset circuit design
Resetting the HYDRA manually
Resetting the HYDRA via the USB/USB2SER interfaces
Figure 3:1
The HYDRA Reset Circuit
3.1 Reset Circuit Design
The Propeller chip can be reset externally via the USB hardware (via the DTR line) or by
pressing the Reset button located at the front of the HYDRA. The reset circuitry on the
Propeller chip doesn’t require much conditioning, thus the manual reset circuit is nothing
more than a switch (as shown in Figure 3:1) that pulls the RESn line to ground when
depressed. If you do want to reset the Propeller chip with some external hardware then you
call pull LOW on the
RESn
line; however, make sure that you place a weak HIGH on the line
with a 2.2-100 K resistor on your circuit, so there is a HIGH on the line if your device is not
actively pulling the
RESn
low.
The Propeller chip keeps a weak HIGH on the RESn line itself via a 5 K pull-up
resistor, thus you technically do NOT need to pull up the reset circuit, but it
won’t hurt if you wish to. Additionally, the brown-out circuit will pull RESn low if
a brown-out condition occurs.
I The HYDRA Hardware
Page 82 Game Programming for the Propeller Powered HYDRA
3.2 Manual Reset of the HYDRA
To reset the HYDRA manually, simply press the momentary Reset switch located in the front
of the HYDRA and the system will reset. During reset, the Propeller chip will look for
communication from the PC host, and if there is none, the Propeller will then commence to
load from an external EEPROM. If there is no EEPROM, the Propeller chip will go into a low
power shutdown state until reset again. If an external EEPROM is found (which is always the
case on the HYDRA), the first 32 KB of the EEPROM are loaded in the SRAM of the Propeller,
then the Spin interpreter is launched and the code is executed. More details on this process
later in Part II.
3.3 Reset Via DTR
Historically, the DTR or
data terminal ready
line on the serial interface was commonly
used to initiate a reset on serial controlled hardware (modems etc.). The HYDRA is designed
so that if DTR is pulled HIGH or asserted then RESn will be pulled LOW on the Propeller chip
and the entire HYDRA will reset. Referring to the circuit in Figure 3:2, Q5 is normally OFF,
thus no current flows in the collector-emitter circuit. However, when the signal USB_DTRn is
driven HIGH with a pulse, Q5 conducts and pulls RESn LOW, therefore resetting the system.
DTR Reset Circuit Figure 3:2
3.4 Summary
This was a pretty straightforward chapter; the HYDRA is reset either manually with the Reset
switch or electronically via the DTR line or via the RESn line coming in from the secondary
backup USB2SER programming port. The one thing to remember is that the RESn line on the
Propeller is internally pulled HIGH by a 5 K resistor to 3.3 V, so technically you do not need
a pull-up on it, but if you want a really robust design, it can’t hurt!
USB Serial Programming Port 4
Game Programming for the Propeller Powered HYDRA Page 83
Chapter 4:
USB-Serial
Programming
Port
In this chapter, we are going to discuss the USB to serial hardware. The HYDRA ultimately
uses a simple serial protocol to communicate with the PC, but due to the lack of old style
9-pin serial ports, the HYDRA has both a built-in USB interface as well as a port that supports
the Parallax USB2SER device in case you only have a single USB port and you want to
program both the HYDRA and other serial devices on your workbench. In any event, here’s
what we are going to cover:
General USB serial overview
Parallax USB2SER USB serial interface
Onboard USB interface
Communicating with the serial interface
4.1 General USB Serial Overview
If you are at all a hardware hacker then you are more than familiar with the tried-and-true
RS-232 serial standard. RS-232 is both an electrical as well as protocol standard that has
been around for a long time. In the 70’, 80’s and even 90’s every single computer on the
planet had a standard DB9 serial port on it and most PCs had two. From a standpoint of
interfacing, RS-232 is nearly the simplest of all standards to get up an running, based on a
±12V system to transmit data/receive data a minimal system can operate on a subset of the
specification with only the TX (transmit), RX (receive) and GND (ground) lines.
However, since the proliferation of the USB interface, standard serial interfaces have
disappeared; in fact, many new PCs do NOT have a single DB9 serial port! This is really bad
news for hardware hackers and embedded system enthusiasts, since interfacing to USB is
NOT trivial; moreover, the protocol for USB is just as complex as Ethernet! Sure, there are
chips that do it, but what used to take a DB9 and a couple resistors now takes a chip, a
driver on the PC side, and a lot of trial an error. Nevertheless, we are stuck with USB
interfaces, so we have to deal with it.
However, some manufactures have acknowledged the need for “simple” serial interfaces
through USB and designed a number of chips that facilitate this transparent to the user. That
is, you use the chip in your design, load the manufacturer’s driver into the PC, and then
either through an API or virtual COM port, you can communicate to your hardware via the
I The HYDRA Hardware
Page 84 Game Programming for the Propeller Powered HYDRA
USB interface as if the hardware were a simple serial interface. On your hardware itself, the
chip does the entire protocol interface for USB, and at the end of the day when you send a
BYTE to your hardware, the chip sends out on the USB to serial interface coming from the
chip the data on the TX line. So in most cases, these special USB-to-serial chips have a
“serial” like modem interface on them that you use on your design as if it came from a
standard old style RS-232 interface. Figure 4:1 shows the entire data flow from the PC to the
embedded hardware, so you can get an idea of everything in between.
From PC to Embedded Hardware Figure 4:1
So the point is that even if you only have a new USB port, you can still write old-style serial
code that talks to COMx on the PC and with one of these USB-to-serial chips, the chip plus
driver from manufacturer will make it all work for you. Of course, you still have to design the
chip into your system and this can be hard or easy depending on the chip you select. In the
case of the HYDRA I opted to use the new FTDI FT232R shown in Figure 4:2.
USB Serial Programming Port 4
Game Programming for the Propeller Powered HYDRA Page 85
Block Diagram of the FTDI FT232R
Single Chip USB Solution Figure 4:2
The FT232R is a pretty slick little chip, and with nothing more than a few resistors, caps, and
the physical interface for the USB connector, you have a complete USB solution that outputs
a standard serial interface. Referring to Figure 4:2, this is a block diagram of the chip; as you
can see at the end of the day, there is a UART-like interface on the top right hand side of the
design and this is what you connect to your serial interface on your hardware after you have
the chip all hooked up.
I The HYDRA Hardware
Page 86 Game Programming for the Propeller Powered HYDRA
Momentarily, we will discuss the hardware around the FT232R chip in the HYDRA itself, but if
you want to take a look at the datasheet and a reference design for the chip, I have included
them on the CD here:
CD_ROOT:\HYDRA\DOCS\DS_FT232R_v104.pdf
CD_ROOT:\HYDRA\DOCS\USB232R.pdf
Summing up, the HYDRA uses a USB interface physically, but through the use of the FT232R
USB to serial interface chip and their associate virtual COM port driver, from the PC’s point of
view (and the Propeller IDE) the HYDRA interface is a standard serial port. Moreover, from
the point of view of the Propeller chip on the HYDRA, the USB port is a simple RS-232 style
interface, so everyone is happy and we can use simple serial communications protocols, etc.
riding inside of complex USB protocols!
4.2 Parallax USB2SER USB Serial Interface
The HYDRA has a onboard USB chip as noted, so you simply connect your PC to the HYDRA
and you are off and running; however, as I was working with the design of the HYDRA and
experimenting myself, I started with the Parallax USB2SER device to get my first Propeller
designs up and running then I embedded the USB solution into the HYDRA itself.
Nonetheless, when I finished the HYDRA, I was about to remove the 4-pin USB2SER
interface header (1 penny worth of hardware) when I realized that I want to keep it. The
reason why is simple: in many cases, you might only have a single USB port for hardware
hacking, if you’re a Parallax customer then you might already have a USB2SER device that
you like to use to connect your other hardware to your PC, then when you want to play with
the HYDRA, you would have to unplug the USB cable and plug the HYDRA into the USB port.
So for the small percentage of users that have only a single USB port and use the USB2SER
device already on their workbench, leaving the little USB2SER header is a good thing, so I did
it. Thus, let’s start briefly by talking about this interface to the HYDRA.
Figure 4:3
The USB2SER Interface Pinout
USB Serial Programming Port 4
Game Programming for the Propeller Powered HYDRA Page 87
Figure 4:3 shows the hardware pinout and design of the USB2SER interface on the HYDRA.
One end of the USB2SER connects to the PC via a USB mini-B cable, the other plug or
header has 4 signals on it as shown in Table 4:1.
Table 4:1 The USB2SER Header Pinout
USB2SER Pin # Description Propeller Chip Connection
1 GND GND
2 RX P30
3 TX P31
4 Reset RESn
The USB2SER header interface is simply connected to the appropriate lines on the Propeller
chip and HYDRA and the communications are handled transparently during programming etc.
Additionally, once the Propeller chip is programmed and running, the TX/RX lines connected
to the USB port at pins P30/P31 respectively can be used to communicate with the PC via the
USB connection, thus one can use these to do upstream communication and/or talk with
third-party tools you create.
For example, say the HYDRA is connected via the USB2SER to the PC host, and the Propeller
IDE is not running, and the HYDRA boots with some onboard program on the EEPROM or
cart. There could potentially be an app listening on the PC to the USB (serial port COMx) and
with software you write you could download assets from the PC, or whatever. So the
important point is that the USB serial connection to the host is freely available
after
programming is done, and the IDE has released the serial port resource connected to the
USB port.
I The HYDRA Hardware
Page 88 Game Programming for the Propeller Powered HYDRA
4.3 Onboard USB Interface
Refer to Figure 4:4; this is the complete design for the onboard USB interface. As you can
see, the center of the design is of course the FTDI FT232R chip. The design is more or less
based on their reference design along with consideration for some Propeller-specific issues.
Of course there are transmit and receive LEDs for example! Anyway, let’s briefly discuss
some of the issues when interfacing with USB. First, the USB lines are “transmission lines”
and thus they must be damped by a terminating network on the receiver end otherwise you
will get ringing and reflections. Normally, this means either a serial or parallel termination
network; USB specs usually call for a simple 33 in series with each of the data lines D- and
D+. However, the FTDI chip comes with series terminating resistors, so you don’t need them.
Secondly, the USB interface starts up in either slow or fast mode; this is controlled by a
pull-up resistor connected to the D+ or D- line. To initiate high speed mode, a pull-up from
the D+ line should be made through a 1.5 k resistor to 3.3 V; similarly for low speed mode
a 1.5 k pull-up should be connected to the D- line 3.3 V. The FTDI chip handles this for us
as well and starts out in high speed mode.
USB is a differential signaling standard; that is, the difference in voltage is the
code, rather than the absolute value. This helps cancel out noise since:
[ ((D+) + noise) – ( (D-) + noise) ] = (D+ - D-)
That is, the noise cancels out.
Alas, there isn’t much for an EE to do with the FTDI chip, it does everything for us. About the
only thing you should add to the design are the filtering caps to the interface and power and
that’s about it. As far as the HYDRA is concerned, the DBUSxx I/O lines on the FTDI chip are
all that we are concerned with. In fact, we only need the TX, RX, and DTR line for the
HYDRA; however, the rest of the lines are there if you were to ever need them, but they are
not exported to the expansion port, so you would have to piggy-back on them if you wanted
access.
Do not connect both the USB2SER interface and the onboard USB cable at the
same time. Although this will not damage the HYDRA or the USB chips, the USB
chip on the USB2SER and the onboard USB chip on the HYDRA would both
potentially be driving the serial TX and RX lines on the HYDRA, and that will
cause errors on the system during programming, etc.
USB Serial Programming Port 4
Game Programming for the Propeller Powered HYDRA Page 89
HYDRA Onboard USB Interface Figure 4:4
I The HYDRA Hardware
Page 90 Game Programming for the Propeller Powered HYDRA
4.4 Communicating with the Serial Interface
The USB interface TX and RX lines always go to Propeller chip pins P31 and P30 respectively,
as shown in Table 4:1 on page 84. So, all communicating you wish to do will end up on those
lines from the Propeller chip’s point of view. Now, to communicate with the HYDRA/Propeller
chip via the USB interface on the PC, all you have to do is install the VCP (virtual COM
drivers) from FTDI (which we already did in Chapter 1) and you can simply open a COM port
to whatever COM port the USB is connected to and then use it like you would any COM port
with standard C, Visual Basic, or whatever your tool of choice is.
For example, after the Propeller tool is done programming the Propeller chip on the HYDRA,
or if you just connect the HYDRA to a USB port with a program already in it, then you can
communicate to the HYDRA via serial communications. This is very useful for more advanced
applications, tools, and of course debugging. You can write a simple serial driver on the
HYDRA that communicates with P31/P30 using a standard serial protocol like N81 at a
reasonable speed like 56 or 115 K bits and then send strings to the PC; just run
HyperTerminal and you will see the characters on the screen. We will actually do this later in
the book.
4.5 Summary
The USB interface is one of the most complex interfaces I have ever worked on, and to write
drivers, design hardware, etc. is a nightmare, but with a single chip like the FTDI chip and
the drivers they supply all these problems go away. Additionally, the problem of DB9 serial
ports disappearing the way of the dinosaur isn’t an issue. Of course, if you only do happen to
have an old-style DB9 serial port, then you can probably find a serial to USB converter and
still make things work! In any event, if you want to explore USB interfacing in more detail, I
suggest reading through the FTDI docs, datasheets, and reference designs, and you also
might try picking up a copy of
“USB Complete”
by Jan Axelson.
Debug Indicator Hardware 5
Game Programming for the Propeller Powered HYDRA Page 91
Chapter 5:
Debug Indicator
Hardware
The Propeller chip has no debugging facilities as of yet. Plans are in place to add debugging
to the IDE as well as an API that runs on a cog to help with the debugging, but with the
current release of the IDE and tools there is no formal debugging support. Thus, debugging
has to be done old school. But, this isn’t that bad – I like old school! There are numerous
options for this which I will describe momentarily. However, at very least I have put in a
single debugging LED, so you can at least use it to indicate “something” is working in your
code, and use it for an indicator and debugging tool. In this chapter, we are going to discuss
the debugging support on the HYDRA and some ideas to further extend debugging. The
topics included are:
The debug LED design
Additional debugging techniques
5.1 Debug LED Design
The only “hardware” for debugging
on the HYDRA is the single LED
circuit shown in Figure 5:1. The LED
is connected to the Propeller chip via
port P0 through a current-limiting
resistor. To turn the LED on/off,
simply write a 1 or 0 to the port P0
(you will learn about the I/O port
communications and more in Part II
of this book).
The LED has its cathode to ground, thus a 1 or HIGH on I/O port P0 results in the LED
turning ON, a LOW or 0 results in the LED turning OFF.
Some TTL/CMOS (especially CMOS) circuitry can’t source a lot of current, but
can sink a lot of current, thus it’s a better idea to connect the cathode to the I/O
port in that case and use reverse logic to turn the LED on/off. However, this isn’t
a problem with the Propeller chip since it can source/sink 30 mA per I/O. Of
course, you wouldn’t want to drive all 32 I/Os at 30 mA, that might be too much
current for the chip to handle at one time.
Figure 5:1
The LED
Debugging
Indicator
Design
I The HYDRA Hardware
Page 92 Game Programming for the Propeller Powered HYDRA
5.2 Additional Debugging Techniques
If you are “old school” then you are a master of debugging and can think of 1000 ways to
debug code. Using debuggers to debug programs hasn’t been around for that long. In fact,
many people still don’t know how to use the debugger in VC++! In any event, it’s “nice” to
step through code and watch registers, but there is no “direct” way to do this with the
language, IDE, or processor. However, with some clever software we can do this more or
less. The first step is to get a simple graphical app working that acts like a “terminal” and
runs on a single cog (or the PC), then as you are trying to experiment and debug code you
can print to the terminal to “watch” variables. In fact, you can potentially watch single
instruction execution by placing hooks in your code to call your terminal update every single
instruction. Additionally, you can “synthesize” breakpoints in your code by making a call to
your “terminal” or debugger program so that when called it dumps what the cog is doing or
memory or whatever and doesn’t return until you hit a key or press the joystick or something
like that. So more or less, to debug, think graphically, and think “printf” – try and visualize
your code execution by printing state out and using the debugging LED where possible.
A PC-hosted Debugging Application Figure 5:2
Another possibility is to write a PC-hosted app that talks to the Propeller chip over the USB
port TX/RX lines, using a single cog to send information to the application as shown in Figure
5:2. For example, you can write an object/program that runs on a cog as a debug client,
then you make calls to it and pass it variables to watch something, like this:
Debug.Add_Watch(&x, "X position", UNSIGNED_BYTE, DEFAULT_X, DEFAULT_Y, 1000)
Debug Indicator Hardware 5
Game Programming for the Propeller Powered HYDRA Page 93
The intent of this hypothetical call might be to “add” a watch variable to a list with the
address of the variable “x”, and indicate that “x” is to be displayed as an unsigned 8-bit
value, and on the debugging display print the text “X Position” next to the output and simply
place the watch variable at the next available x,y location, finally the 1000 might mean to
update every 1000 milliseconds. The debugging client running on a cog would simply add
this information to a local list and then it would access global memory or whatever and send
it to the PC and the PC host program would do all the display. This way you can have a
completely asynchronous debugger running “hidden” on a cog that for the most part does
NOT interfere with your game or demo code. Of course, you can’t read a cog’s local memory
unless the cog shadows it to global memory.
If you want to you “can” run the Propeller chip at DC and pulse the clock
yourself with a single-step button (with debouncing of course), this way you can
potentially put probes or whatever on the pins of the chips, or control it.
Additionally, you could surround the Propeller chip with some extra debugging
hardware that via the PC, you could single-step the chip and so forth. Of course,
if you do this then you need to run the Propeller chip’s clock input mode as
straight clock in “XIN” mode, without any XTAL reference or PLL modes; more
on this later.
Lastly, a really slick way to add a little bit of debugging I/O is with a serial or quasi-parallel
LCD. You can buy a number of very simple LCDs from DigiKey or other online vendors and
interface them to the HYDRA through the expansion port (which will be discussed later in
Part I). Typically, the LCDs take a simple stream of commands to print characters on the LCD
and some LCDs even have bitmap displays. Common sizes for monochrome LCDs are 20x2,
40x2, 20x4, and 40x4 characters. Hantronix is one of my favorite vendors, they also make
full-color LCDs with entire graphics engines built in, so you could potentially make a plug-in
card that had a full color LCD and print debug information to that and forgo the complex PC
serial interface.
5.3 Summary
In this chapter, we discussed probably the simplest piece of hardware on the HYDRA – the
debug LED, but one thing is for certain, a single LED can work wonders when debugging
ASM code! Also, we discussed some ideas to get some more advanced debugging techniques
online, I highly suggest taking the time and effort to invest in getting your debugging
techniques down before you start into heavy coding (in ASM at least) on the Propeller chip, it
will definitely save you time in the long run.
I The HYDRA Hardware
Page 94 Game Programming for the Propeller Powered HYDRA
Game Controller Hardware 6
Game Programming for the Propeller Powered HYDRA Page 95
Chapter 6:
Game Controller
Hardware
Originally I was going to use Atari 2600 joysticks for the HYDRA; however, due to their
scarcity and the lack of extra controls on them, the decision was made to go with classic NES
(Nintendo Entertainment System) controllers. The primary reasons are that NES controllers
are abundant, easy to interface to, have lots of nostalgia, can be interfaced via 4 signal lines,
third-party models look really cool, and most importantly, if the HYDRA interfaces to the NES
controller then any “NES compatible” device can be interfaced since they all use the same
connector! Thus, light guns, VR gloves, and any and all manner of bizarre NES hardware
from the 80’s/90’s can be interfaced to the HYDRA through the controller ports, so it’s a good
plan. With that in mind, in this chapter we are going to discuss the following topics:
Overview of the NES hardware
NES controller protocol and interfacing
Supporting Super NES controllers
6.1 The Classic NES Controller (1983)
If you have never heard of Nintendo, then may I be the first to greet you from Earth,
because you must be from another planet! The Nintendo Entertainment System or NES, also
known as the Nintendo Family Computer (Famicom) was released in Japan in 1983 and
shortly after in the USA in 1985. The system was even more successful than the Atari 2600
and more or less put the last stake in the heart of Atari home consoles forever. The NES sold
more than 60,000,000 units worldwide in its heyday and still sells to this day (I just bought
4 of them from eStarland.com)! There are over 200 clones of the system in circulation and
the word “Nintendo” is used in many cultures as a youth slang term with many “varied
meanings.
The system itself was nothing compared to the Propeller chip’s computing power, the NES
was powered by the 8-bit 6502 running at 1.79 MHz, but the NES did have quite a bit of
dedicated graphics hardware making it quite a contender in the 8-bit era, it sported multiple
tile maps, graphics planes, sprites, sound, and a lot more. In any event, as noted I opted to
use the NES controllers for the aforementioned reasons, plus being an Atari guy, sometimes
its nice to jump ship and see how the other side lives, so all in all I am very happy with the
NES controllers on the HYDRA. They give the system a retro feel, but are powerful enough to
use as serious input devices for more than just games. Plus, the final controllers shipped with
the HYDRA look very cool.
I The HYDRA Hardware
Page 96 Game Programming for the Propeller Powered HYDRA
Figure 6:1
NES Controller
(front)
The classic NES controller / gamepad is shown in Figure 6:1, and internal shot is shown in
Figure 6:2. As you can see there isn’t much to the NES controller electronics (a single 4021
serial chip), but that’s the beauty of it. The interface is so simple, we can use 4 lines to
interface to the NES controller and read all 8 inputs (Up, Down, Left, Right, A, B, Select,
Start).
Of course, we aren’t using these collectors’ item controllers on the HYDRA, that would be
sacrilege; but all NES controllers must be compatible with the original standard, so we are
going to discuss NES controllers with the original in mind, but the controller that comes with
your HYDRA will be from the 21st century and a bit more sleek in its design.
NES Controller (inside) Figure 6:2
Game Controller Hardware 6
Game Programming for the Propeller Powered HYDRA Page 97
Pinout of the 4021 NES Controller Chip Figure 6:3
The NES controller is based on a parallel to serial shift register internally that “latches” the
button states and then shifts them out to the host. The shift register used in the original NES
control is the
CMOS 4021 shift register
. Figure 6:3 shows the pinout of the 4021 and the
complete data sheet is on the CD located at:
CD_ROOT\HYDRA\DOCS\cd4021b.pdf
I The HYDRA Hardware
Page 98 Game Programming for the Propeller Powered HYDRA
Figure 6:4 shows the HYDRA controller interface for the right and left controllers. As
mentioned, all the signals are paralleled except for the JOY_DATAOUT_0 and
JOY_DATAOUT_1 lines since these are the independent data streams from each controller.
Also, notice that the LEDs that are connected to the data out lines, the resistors are large
enough to minimize current drain, and thus the signals are not degraded, but when the NES
controllers are plugged in the weak pull ups on the outputs of these lines power the LEDs
and indicate that the controller is plugged in.
The HYDRA Gamepad Interface Ports Design Figure 6:4
The actual pinouts and colors (for the classic NES controller) are shown in Table 6:1.
Referring to the table, you can see that the original spec for the NES controllers uses +5 for
power. I was a bit worried that the old 4021’s wouldn’t work at 3.3 V and I would have to
Frankenstein the 5 V supply into the NES controller, but then make sure the levels match the
outputs and inputs to interface to the Propeller, but the 4021 is a CMOS device and works
fine at 3.3 V. Of course, running any CMOS device rated for 3-7 V at lower voltages lowers
the maximum clocking rate, but in this context it’s irrelevant, since we can read the controller
bits at a rate of 200 ns each.
Game Controller Hardware 6
Game Programming for the Propeller Powered HYDRA Page 99
Table 6:1 NES Controller Pinout
Pin # Function Wire Color* Pin on Propeller Chip/Design Designator
1 Ground Brown GND
2 Clock Red JOY_CLK (P3)
3 Latch Orange JOY_SH/LDn (P4)
4 Data Out Yellow JOY_DATAOUT_0 (P5), JOY_DATAOUT_1 (P6)**
5 No Connect None
6 No Connect None
7 + 5 Power White
Notes * Colors on original NES Nintendo controllers only; 3rd party controllers have different colors.
** Where JOY_DATA_OUT_0|1 are the left and right controller ports respectively.
*These colors are on “stock” controllers ONLY, in fact many third-party
manufacturers of NES/SNES controllers not only get the colors wrong, but
sometimes use the correct colors and connect them to the wrong pins! The best
thing to do is rip the connector apart and see what color is connected to what
pin on the 4021 and power supply rails.
6.2 Interfacing to the NES Controllers
Interfacing to the NES controllers is a completely digital affair; on the HYDRA for example,
we can run the clock, latch, and power lines in parallel, then send the data from each
controller (if its plugged in) to the Propeller chip. To read the state of the NES controllers,
you must perform the following steps:
Step 1: Set the Latch line (P3 on Propeller chip) to LOW (this is connected to the
parallel/serial select on the 4021).
Step 2: Set the Clock to LOW.
Now, we are in a known state.
Step 3: Pulse the Latch line HIGH for at least 200 ns, this will latch the data into the shift
register.
Step 4: Read the bits in from the Data Out lines at P5 and P6, the first bit will be available
after the latching process. To read the remaining bits, pulse the Clock line 7 times, as you
are doing this you can shift each bit read from the Data Out line into a BYTE, so that the first
bit ends up in the bit7 position and the last bit in the bit0 position. Realize that the HYDRA
reads the controllers in parallel, so you can perform the read operation once with some
clever bit manipulation.
I The HYDRA Hardware
Page 100 Game Programming for the Propeller Powered HYDRA
Step 5: The button states are all inverted; that is, pressed is digital 0, released is 1, so you
might want to invert the results so 1 means “pressed”, just personal preference.
After performing these steps you simply use bit operations to determine which buttons are
pressed. The button encodings are shifted out in the following sequence starting from left to
right, where the left-most bit is available on the data out lines after the initial latching
operation as shown in Figure 6:5.
Figure 6:5
NES Data Format
Also, a bonus feature of the NES controller is that when you read it on the HYDRA, if the
controller is NOT plugged in then the value $FF will be returned, thus we can use this
sentinel to determine if a controller is plugged in or not!
When you latch and clock the bits, remember that the 4021 chip has a maximum
clocking rate. I suggest keeping the clocks 200 ns or greater to allow for settling
and propagation delays, you don’t want to loose the fire button bit under a high
stress condition if you are reading the controller too fast!
6.3 Super NES Controller Interfacing (1990)
Again for a quick history lesson: the new 16-bit system, Super Nintendo (SNES), was
released in Japan in 1990 and 1991 in the USA. The system once again became an instant hit
and sold a total of 50,000,000 units worldwide, thus making the combined sales for NES and
SNES in excess of 100,000,000 units!!! The SNES had better graphics and a much more
powerful 65816 processor (basically a 16-bit version of the 6502) running at 1.79 – 3.58 Mhz
in a “variable” speed mode of operation. The overall design of the SNES was a little more
sleek and updated, and of course they updated the controllers as well. The new controller
has a few more buttons, but the underlying protocol for reading the controller is the same.
Additionally, the mechanical interface for the SNES controller (shown in Figure 6:6) is even
more bizarre than the NES controller.
Game Controller Hardware 6
Game Programming for the Propeller Powered HYDRA Page 101
Figure 6:6
Super Nintendo
Controller Pinout
The Super NES controller is almost identical to the NES controller as far as the protocol goes,
so the techniques here are applicable to the SNES controller as well. Figure 6:6 shows the
pinout of the Super NES controller and Table 6:2 lists the pinout.
Table 6:2 Super NES Controller Port
Pinouts
Pin # Function Wire Color
1 + 5 power White
2 Clock Yellow
3 Latch Orange
4 Data Out Red
5 No Connect None
6 No Connect None
7 Ground Brown
The only difference is that the Super NES streams out 4 more bits representing X, Y, R (right
shoulder button), and L (left shoulder button) which makes for a total of 12 bits. However,
Nintendo opted to add 4 more cycles for future expansion and made the read protocol a total
of 16 bits as shown in Figure 6:7; notice the last 4 bits are always HIGH, or 1s.
SNES Data Format Figure 6:7
I The HYDRA Hardware
Page 102 Game Programming for the Propeller Powered HYDRA
6.4 Summary
In conclusion, the NES controllers are pretty slick internally since they simplify the HYDRA’s
need for support hardware due to their built in serializing chips. Also, hopefully you can
appreciate how simple and brilliant they were. A piece of software or hardware is seen
through its interfaces or GUI; this is true with Windows and true with game consoles, so
considering that, any idea that helped sell 100,000,000 units is worth taking a closer look at!
Composite NTSC / PAL Video Hardware 7
Game Programming for the Propeller Powered HYDRA Page 103
Chapter 7:
Composite
NTSC / PAL
Video Hardware
In this chapter, we are going to take a look at the composite video hardware for the HYDRA
and take a brief look at basic NTSC concepts. This is by no means a treatise or even a tidbit
about NTSC video generation, later in the chapter I will give you some good book titles and a
website to read about NTSC/PAL video engineering. For the HYDRA though, we are for the
most part simply going to use the drivers that Parallax, myself, and other coders have written
in ASM to generate video and use them as black boxes, as objects, or as functions included
in our programs. So without any further ado, here’s what’s in store this chapter:
HYDRA composite video hardware
The Propeller chip’s video streaming unit hardware
Brief NTSC primer
7.1 HYDRA Video Hardware
Figure 7:1
The HYDRA’s Video
Hardware
The HYDRA has very little hardware for video. In fact, all the video generation and timing is
done within the Propeller chip itself via a mixture of software and hardware; there is no
I The HYDRA Hardware
Page 104 Game Programming for the Propeller Powered HYDRA
dedicated GPU, no VRAM, or frame buffer of any kind. Later we will discuss this in detail in
Part II, but for now realize that each cog has what’s called a
“Video Streaming Unit”
or
VSU. The VSU of each cog can run independently and more or less simply serializes a stream
of data that you pass it in 32-bit chunks. The data is formatted in such a way that it either
assumes you are driving a NTSC/PAL device (with a resistor summing network on the output
port) or an RGB device (BYTE device with no electronics on the output port) like VGA. The
hardware you place on the outside of the Propeller chip to make the internal hardware work
is minimal at best. Figure 7:1 shows the actual video hardware for the composite NTSC/PAL
signal.
It’s more or less a simple 3-bit D/A resistor network (R16, R17, R18) and the 4th bit (R15) is
for audio modulation when the cog is in RF modulation mode (yes, the cogs can transmit
video via RF if you hook a wire to the output at J4!). The resistors are selected such that with
a 3.3 V supply and the signal terminating into a 75 load (TV load) the maximum voltage
will be approximately 1.0 V when all the lines are HIGH (P26..P24), this is WHITE and 0.0 V
is SYNC level.
Referring to the circuit, the cog’s internal hardware assumes that you have hooked up a
resistor network such as that shown in Figure 7:1 to a 4-bit port of the cog and then you use
a couple of special instructions to set up the video configuration registers and “feed” the VSU
with pixel and color data. So you could say that the Propeller chip uses hardware to stream
pixel data out to a 3-bit DAC, that you feed it. The pixel data might be
sync, black
, or
luma, chroma
data (more on this in the NTSC primer below), the cog will output the proper
voltage via the DAC along with the proper phase delay for chroma (color) since it knows you
are driving NTSC/PAL video hardware (if you configure it this way), but that’s all the VSU
does.
Additionally, the VSU can work in “dumb” byte-oriented data mode and simply send out
BYTEs of data, this mode is used to drive VGA of the format RGB (2.2.2) plus Hsync and
Vsync, that’s a total of 8 bits or one BYTE per output. In this mode, you basically pass the
VSU VGA values and it sends them out each clock at 25.175 MHz (VGA clock rate). The
NTSC/PAL hardware is very minimal since the cog does all the work. The only downside is
that the timing and data feed to the cog’s VSU unit must be done with software, and a
“feeder”
loop more or less can only be done with very tight ASM code. Moreover, the cog’s
video hardware formats that output to the 3-bit DAC only allow 16 colors with a 3-4 shades
depending how close you want to go to the sync and white rails. And there is
no
general
control on saturation, but there are some tricks to get extra saturated colors in addition to
the standard colors (more later during graphics programming in Part III). Therefore, you can
control luma and chroma, but not saturation. Nonetheless, you will find that the saturation of
colors generated is very pleasing.
Composite NTSC / PAL Video Hardware 7
Game Programming for the Propeller Powered HYDRA Page 105
Generating NTSC or PAL is not a matter of hardware, but a matter of software,
that is, how you send data to the VSU and time the signal.
SECAM (a French standard loosely meaning “sequential color with memory”) on
the other hand is a whole other ball park, but can be generated with the VSU as
well if you really want to do it.
It’s worth mentioning that the VSU is nothing more than a serial streaming unit (not
necessarily only for video), it can generate video of any rate at the output, so there are no
real limits to the speed you can update video. The downside is that you must use the internal
32K program RAM for video memory. This can be quite disturbing in Spin code, since Spin
BYTE codes must reside in main memory, so you will find the demos and games you can
make that drive bitmapped video are very constrained since you eat up so much RAM to
support double buffering etc. However, in ASM, you have quite a bit of room and crazy
demos and games can be made.
Lastly, even though the HYDRA only has one video output, each cog has its
own
VSU that
can work independently of other cogs, thus you could potentially drive 8 TV’s at the same
time with different displays or demos if you wanted to add the resistor networks to each!
7.2 Brief NTSC Primer
The NTSC standard) is technically referred to as the RS-170 and was ratified in 1941, later
color was added and the full standard was updated to RS-170A. NTSC (National Television
Systems Committee) is an analog standard designed to be easy to generate and easy to
decode. Also, the standard had to be very forgiving. It’s amazing that over a half century has
passed and NTSC still gets the job done. To cover NTSC is any detail would take a whole
book, therefore, we are only going to briefly discuss it, and take more of a hands-on, black
box approach when we get to graphics programming. Rather than worrying about generating
NTSC signals yourself, the drivers I will provide you with will take care of it. With that in
mind, let’s take a quick look at NTSC and its underlying principles.
7.2.1 Basic Monochrome NTSC
NTSC is designed to be displayed by a raster device, that is, a CRT (cathode ray tube) that
draws images a frame at a time, where each frame is composed of a number of horizontal
lines.
The rendering device, usually a CRT’s electron gun, starts at the top left corner of the screen
and draws a line or row of pixels by emitting a stream of electrons toward the phosphor-
coated CRT, then when the electron(s) strikes the phosphors they give off light and you see
a pixel (monochrome or color, depending on the type of phosphor).
I The HYDRA Hardware
Page 106 Game Programming for the Propeller Powered HYDRA
Figure 7:2 shows how the NTSC signal is drawn. As the beam of electrons reaches the right
side of the screen, a sync pulse referred to as the
horizontal sync
or
Hsync
instructs the
CRT to retrace back to the left to draw another line. When the screen is completely drawn
then another sync pulse referred to as the
vertical sync
or
Vsync
instructs the raster beam
to make its way back up to the top left and the process starts again.
Figure 7:2
A Raster Screen Setup
The standard NTSC screen is composed of 525 lines, where each line consists of about 227
“pixels”
(picture elements). The 525 lines are broken into two interlaced
“frames”
, where
each frame is 262.5 lines and the frames are drawn at a rate of 60 frames per second
(FPS); interlacing these two frames together results in a “fused” display at 30 frames a
second. However, for graphics and games, we don’t use interlacing typically, and we simply
draw only 262.5 lines at 60 FPS.
The NTSC signal itself is composed of an analog voltage from 0 to 1.0 V or sometimes from 0
to 1.4 V. The voltage represents different things to the decoder on the TV. A voltage of 0 V
means “sync,” 0.25 means
blanking level
or
“blacker than black”
and a little bit above
this (say 0.3 V) is black, and anything from black to the maximum voltage of 1.0 (or 1.4 V)
creates shades of gray, and the maximum voltage (1 or 1.4 V) is white. Thus, the NTSC
signal is more or less an amplitude-modulated “luminance” signal with syncing information
embedded into it as well as color (more on this in a moment).
Composite NTSC / PAL Video Hardware 7
Game Programming for the Propeller Powered HYDRA Page 107
7.2.2 Dissecting a Video Line
Figure 7:3 depicts a standard NTSC video line) (not to scale of course), there are a number
of specific regions that make up the signal. First, an entire NTSC video line is always 63.5 µs,
that means that each line is rendered at a rate of (63.5 µs)-1 = 15.748 kHz. Now, let’s inspect
the video line carefully: it starts off with a
horizontal blanking period
, this is the time
when the electron gun is sweeping back from the right edge back to the left after drawing a
line of video.
The horizontal blanking period is composed of 5 major elements:
Front porch (1.5 µs)
Sync tip (4.7 µs)
Breezeway (0.6 µs)
Color burst (2.5 µs)
Back porch (1.6 µs)
A Single Line of Video Figure 7:3
I The HYDRA Hardware
Page 108 Game Programming for the Propeller Powered HYDRA
Front Porch (1.5 µs) – The front porch is really just the end of the last video line or the
beginning of the current line; it’s 1.5 µs in length and should be set to the blanking level or
blacker than black. In practice the blanking level and black can usually be the same value
and 0.25-0.3 V works fine.
Sync tip (4.7 µs) The sync tip, or Hsync to be more precise, is very important; this
instructs the TV to initiate the horizontal retrace. The signal itself has a frequency of
15.748 kHz, but is very short, just a sliver really, but the TV electronics are looking for it. The
sync tip should be at 0.0 V.
Breezeway (0.6 µs) – The breezeway is the period right before the “
color burst
(which
we will discuss shortly) and simply gives the TV a moment to catch its breath before the very
important color burst reference tone is sent. The color burst enables the transmission of color
in the old black and white signal in a very ingenious way, more on this shortly. The
breezeway should again be at the blanking or black level.
Color burst (2.5 µs) – The color burst is 9-10 cycles of a 3.58 MHz reference tone, this is
locked onto by a phase locked loop in the tuner of the TV and then used as a reference for
the color signal. The color burst itself should ride on the blanking level with a peak to peak
value of about 0.25 V.
Back porch (1.6 µs) – The back porch follows the color burst, and is more or less simply
the time after the color burst, but before the active video signal.
Ok, that’s the horizontal blanking signal in its entirety, this must be sent at a rate of
15.748 kHz and the entire length of the signal is simply the sum of the constituent parts. The
next portion of the video line is the “active video” and this is where all the action happens.
The active video portion of the video line is 52.6 µs long and is nothing more than an
amplitude-modulated signal where the luminance, referred to as “luma” in literature, is
encodes as the amplitude of the signal at any one time from black (0.25 V) to white (1.0 V).
Now, when talking about a monochrome or black-and-white signal, you could change this
signal at any rate you want; however, you are band-limited to about 4.5 MHz on an average
TV. In other words, the maximum number of luma changes that the TV can keep up with is
about 52.6 µs / (4.5 MHz)-1 = 234 per active video line! Ouch! And it gets worse with color,
so prepare yourself. Thus if you are trying to map a 640 pixel screen to the TV, you are way
out of luck, at most you will be able to see 234 pixels and in reality a lot less, they tend to
blend into each other.
Composite NTSC / PAL Video Hardware 7
Game Programming for the Propeller Powered HYDRA Page 109
You may have noticed that in the TV signal diagram there is a unit of measure
called “IRE” this stands for “Institute of Radio Engineers.” There are a total of
140 IRE units in a TV signal from sync to white.
Now here’s the clincher: depending on what reference you use and what set you
use, 140 IRE units are usually mapped to 1.0 V OR 1.4 V – that’s where this
1.0 -1.4 V discrepancy comes into play. However, for all intents and purposes, I
have never found a set that wouldn’t work with either scale.
In other words, NTSC is so forgiving and so adaptive that whether you use 1.0 V
for white or 1.4 V for white, the entire system will work just fine. The HYDRA for
example uses a 1.0 V scale for video.
Additionally, the resolution is not only limited by the input bandwidth to the set, but
physically by how many phosphors are actually on the front of the TV screen and how fine
the “mask” is that lets the electrons through, and so forth. There are lots of factors, but
these all new sets are very resolute and can handle even higher resolutions than the NTSC
spec specifies.
Anyway, the image is composed of 262 of these video lines, you simply generate the
blanking signal at the beginning (end) of each line (however you want to think of it) then
stream your pixels out of your D/A and amplitude modulate them based on their brightness
in your image buffer from black to white. When you have drawn all 262 lines of video
(remember for games and graphics we typically do not interlace) then you need to tell the
electron gun to retrace back for another frame; this is called the
“vertical blanking
period”
and we need to generate a vertical sync pulse to make this happen.
7.2.3 Vertical Blanking Period
If you know anything about video game programming then you have heard about the
“vertical blank” – this is the time when the electron gun is retracing from the bottom of the
screen to the top, and a literal “eternity” of time to do graphics and game processing. In fact,
on early systems like the Atari 2600, 800, C64, Apple II, NES, etc. if it weren’t for the
“vblank”
many games would be impossible since there is so little time between feeding the
video hardware pixels to do game computations.
I The HYDRA Hardware
Page 110 Game Programming for the Propeller Powered HYDRA
A Close-up of the Vertical Blanking Period Figure 7:4
Figure 7:4 shows the complete NTSC spec for what’s called a
“super frame.”
In reality, as
the 525 interlaced lines are being drawn as 2 frames there are actually 4 different flavors of
slightly different frames then it repeats, but this is irrelevant unless we are making a DVD
player or broadcasting CBS. In our case, all we care about it is following the spec close
enough. With that in mind, take a look at the shaded area in the figure near field 4, which
shows a typical vertical blanking signal. The vertical blanking interval is composed of three
major parts that make up a total of 18 lines of video. Thus, given a screen is 262 lines
total: with 18 for the vertical sync, there are 26218 = 244 lines of
“visible video.”
Given
that, the different phases of the vertical blanking period are:
Pre-equalization pulses (6 lines of video)
Vertical sync pulse (6 lines of video)
Post-equalizing pulses (6 lines of video)
Pre-equalization pulses – These pulses are nothing more than Hsync-only pulses that
prepare the vertical retrace circuitry for the upcoming vertical sync pulse while keeping the
Hsync circuitry locked. There are 6 lines of video that make up these pulses, and they are
nothing more than 6 blank lines with just Hsync in them, no color burst, no video.
Vertical sync pulse – This is where the action takes place. There is a 6-video-line-long
sequence of nothing but Hsync pulses, but they are inverted, that is instead of being at black
Composite NTSC / PAL Video Hardware 7
Game Programming for the Propeller Powered HYDRA Page 111
and dropping to sync for 4.7 µs, these pulses, referred to as
“serration pulses”
are at sync
the entire video line, then for 4.7 µs come back to the blanking or black level. This is filtered
by the Vsync filter on the set and gets through to the vertical retrace hardware, but at the
same time keeps the Hsync hardware synchronized as well.
Post-equalization pulses – These pulses are nothing more than Hsync -only pulses that
allow the horizontal sync hardware to catch back up with the signal after the large vertical
sync pulse. There are 6 lines of video that make up these pulses, and they are nothing more
than 6 blank lines with just Hsync in them, no color burst, no video.
When it’s all said and done the total number of wasted lines is 18 for the entire vertical
blanking process, so you have the remaining 244 lines to draw your video. However, there is
another issue to address – overscan. Overscan is the portion of the screen both vertically and
horizontally that you can’t see. This anomaly is due to mechanical interfacing, the CRT itself,
and other manufacturing issues. Thus, typically, the top and bottom 10-20 lines of video on
most TVs are unviewable, thus most game systems center the video and display 192-200
lines of video. Of course, you can render on the overscan area if you wish, but then just
make sure to not put scoring information or other vital stats there, since on some TVs users
won’t be able to see the data, considering that most graphics engines stick to 192-200 lines
with 224 being the max (224 is used since it’s a multiple of 8 and 16 and those are common
bitmap tile sizes).
Additionally, since you don’t need to send out active video luma information during the
vertical blank and overscan periods, these are the best times to update game logic and/or
prepare the next frame of video data. For example, when developing graphics and TV drivers
for the Propeller, the vertical blank and overscan times can be used to pre-process video data
and get it ready for rendering during the active scan portion of the screen rendering. The
reason why is that during the actual rasterization of the screen there is little time between
pixels to do calculations, so pre-computing addresses, buffering data, and so forth can be
done in the blanking periods then passed on during the rasterization periods.
Let that all sync in (pun intended), and let’s talk about color!
7.2.4 Adding Color to NTSC
Adding color to the NTSC signal is probably one of the greatest hacks in electronics history.
After the initial format specification for RS-170 in 1941, engineers, doing what they do best,
improved the system and added color to both the cameras and the CRTs. The only problem
was that they simply couldn’t tell the USA and other adoptive countries to just change the
signal specifications overnight. Moreover, hundreds of thousands of B/W TVs were already in
use if not millions, so a new broadcast signal format was out of the question. However, color
would be added, it had to be “hidden” in the current NTSC B/W luma only signal and it had
to not interfere with a standard B/W set. Thus, if a broadcast was sent in full color a B/W set
could still pick it up and display it and it would look good, but at the same time, anyone
I The HYDRA Hardware
Page 112 Game Programming for the Propeller Powered HYDRA
dishing out the big dollars for a color TV would be able to see the Technicolor version of
“Wizard of OZ” in all its glory. The first color TVs and systems were deployed in the USA
around 1953 and it went flawlessly. The question is how did they do it?
Referring back to Figure 7:3, you see the section of signal after the Hsync pulse, this is called
the color burst. In a luma-only NTSC signal from the 40’s you wouldn’t see this, but in a color
signal from 1953 and on, you would. This little region in the original NTSC signal wasn’t used
for anything, just a few microseconds before the actual luma signal was sent, but it was
enough time for a brilliant hack for the color. The idea was that in this color burst region, the
NTSC signal would modulate onto the blanking signal 9-10 cycles of a 3.58 MHz sine wave.
This 3.58 MHz signal was decided to be the carrier frequency of “color.” So the new color TVs
would look for this 3.58 MHz signal via a signal trap tuned to 3.58 MHz, if present then the
signal is a color signal and an internal phase locked loop (basically a method to lock onto the
frequency and phase of a signal) locks onto and synchronizes the TVs internal color hardware
to the signal. So by the time the luma signal portion of the NTSC signal is received the TVs
tuner is locked onto the 3.58 MHz color burst as well.
Now comes the ingenious part: the 3.58 MHz signal is above (for the most part) the
maximum bandwidth of the luma signal, so anything at 3.58 MHz and above is usually
filtered out of the luma and ignored (I know I said most sets have a bandwidth of about 4.5
MHz, but bear with me), so if a 3.58 MHz signal is modulated on the luma signal then we can
filter it and look at the signal. So what though? Well, the trick is that instead of the amplitude
of the 3.58 MHz that is modulated on the luma encoding color, the phase shift or difference
encodes color. Take a look at Figure 7:5 to see this.
Figure 7:5
Color Burst
Signal
Encoding
Composite NTSC / PAL Video Hardware 7
Game Programming for the Propeller Powered HYDRA Page 113
In real-time as the luma signal is sent, the phase of the initial color burst after the Hsync is
used as a reference point for color, so you basically continually send the 3.58 MHz signal
modulated on your luma signal, and the phase difference from the color burst reference
signal and the current 3.58 MHz signal is the actual color! Moreover, the saturation of the
color or is richness is the local amplitude of the 3.58 MHz signal modulated on the luma. The
color signal overall is called the chroma signal. Again, Figure 7:5 has the vertical scale in IRE
units, but depending on what the overall range is the chroma saturation usually ranges from
0.1 - 0.3 V, where 0.1 V is washed out and 0.3 V is deep color.
Now, taking all this into consideration, the maximum number of pixels you can have color
changes on a standard NTSC TV can be calculated as follows. Given:
Color burst frequency = 3.58 MHz, or 279 ns per cycle.
The visible portion of the active video is 52.6 µs.
Therefore, the total number of individual perceivable colors changes per active video
line is, or
“Color Clocks”
is:
Color Clocks = 52.6 µs / 279 ns = 188.
That’s it! Not, 320, not 256, but a measly 188! Of course, you can overdrive the color, and
maybe people do. In fact, on the HYDRA, many demos drive the color at 256 pixels per line,
however, if you were to take a magnifying lens and look at each pixel individually, you
couldn’t see the color, you need a couple pixels next to each other before the color stabilizes.
This is why on old game systems you see resolutions like 160 or 184 across (both multiples
of 8), they are both within the bandwidth limit of the color on NTSC. On the other hand if
you are writing bitmap games and want higher resolution, it surely won’t hurt to have 224 or
256 pixels per line (which are common), you simply won’t be able to make out single pixel
colors, but when many pixels are combined you get a “free” blurring / anti-aliasing effect
which makes things look really good. But do not try this with text, you will see lots of “color
artificating,” that is, you have one pixel with one color, then try and put another next to it,
and they both change color! This is caused by over-driving the color bandwidth of the TV.
Therefore, if you want really crisp text, try suppressing the color signal altogether (which is
easy with the HYDRA and Propeller chip) then only using color with games and graphics.
7.3 Summary
The composite video hardware on the HYDRA is almost embarrassing since the Propeller
does all the work for us, in fact, the Propeller really doesn’t have much video hardware
either, it’s all in the software that generates video. The only hardware the Propeller has is the
VSU unit which is a glorified serial shift register, but this is all we need to generate NTSC,
PAL, or whatever since we can use software to synthesize the various timings and analog
voltages needed for video.
I The HYDRA Hardware
Page 114 Game Programming for the Propeller Powered HYDRA
If you are interested in learning more about NTSC and all the myriad of video standards in
the word (there are dozens of variants of PAL for example), be sure to pick up
“Video
Demystified”
by Keith Jack as well as
“Video Engineering”
by Luther and Inglis, neither
are for the faint of heart, but
Video Demystified
is a bit easier to read. Also, there are
numerous websites online about NTSC standards, one of the most complete, albeit ugly, is:
www.ntsc-tv.com
VGA Hardware 8
Game Programming for the Propeller Powered HYDRA Page 115
Chapter 8:
VGA Hardware
In this chapter, we are going to take a look at the VGA hardware on the HYDRA. The VGA
hardware is a little more exciting that the composite video hardware, in fact, the VGA design
actually uses an external chip and a few more components than just resistors, so I am
excited. Also, in this chapter we are going to briefly take a look at the VGA spec, so you have
a conversational understanding of it and why VGA is both good and bad from a video
generation point of view. So, here’s what’s in store:
VGA origins
HYDRA VGA hardware design
VGA signal primer
8.1 Origins of the VGA
Before we start into the design, let’s get some history and terminology correct. First, the last
time I saw a real VGA monitor was about 20 years ago, the new 21st century monitors that
you are used to are super-sets of VGA; they are typically multisync, variable refresh, and can
go up to 2400×2400 or more. The “VGA” specification is more of a base point than anything
anyone actually uses anymore. IBM released the VGA or “Video Graphics Array” technology in
1987 roughly. It was touted to change the world (definitely an improvement from CGA and
EGA), but it was doomed from the start with not enough resolution. Shortly after, higher
resolution monitors were available and the VGA specification was enhanced with the Super
VGA standard, but this was only a momentary hold on its execution; what was needed was a
more progressive standard that could change at any time, and thus the VESA “Video
Electronics Standard Association” graphics cards and drivers were created and the rest is
history. However, the original specs for the VGA are shown below.
256 KB Video RAM
16-color and 256-color modes
262,144-value color palette (six bits each for red, green, and blue)
Selectable 25 MHz or 28 MHz master clock
Maximum of 720 horizontal pixels
Maximum of 480 lines
Refresh rates up to 70 Hz
Planar mode: up to 16 colors (4 bit planes)
Packed-pixel mode: 256 colors, 1 BYTE per pixel (Mode 13h)
Hardware smooth scrolling support
I The HYDRA Hardware
Page 116 Game Programming for the Propeller Powered HYDRA
Some "raster operations" (Raster Ops) support to perform bitmap composition
algorithms
Barrel shifter in hardware
Split screen support
Soft fonts
Supports both bitmapped and alphanumeric text modes
Standard graphics modes supported by VGA are:
640×480 in 16 colors
640×350 in 16 colors
320×200 in 16 colors
320×200 in 256 colors (Mode 13h, "chunky graphics mode")
I spent many years writing graphics algorithms and drivers for VGA cards, now my cell phone
has better graphics! However, the VGA spec is great for baseline computer displays and any
standard modern computer monitor will display old school 640×480 VGA modes and refresh
rates. This is the design focus on the HYDRA’s VGA output, to simply drive a standard VGA
monitor at 640×480 resolution at 60 Hz refresh rate.
8.2 VGA Design
The VGA hardware for the HYDRA is very minimal since the Propeller chip is doing all the
signal generation with the aforementioned VSU in the previous chapter. However, to facilitate
the use of the expansion port, I have added a buffer on the VGA output port to isolate it
when you are using the IO bus on the expansion port which shares the same I/O pins.
Otherwise, when not driving the VGA port, if you had a monitor attached your random I/O
activity would potentially drive or damage the VGA monitor. Figure 8:1 shows the final design
of the VGA hardware.
Referring to Figure 8:1, you see that P16 – P23 are connected to all the VGA signals and
there are 2 bits for each channel; Red, Green, and Blue, as well as a single bit for Hsync and
Vsync. These outputs are connected to the VGA buffer at U5 which is a 74HC244 8-bit
tri-state buffer. Its output is connected to the HD15 connector via a series of 2-bit D/A
converters that sum each 2-bit channel pair (R0, R1), (G0, G1), and (B0, B1) and directly
interface the sync bits. The VGA spec dictates that for each channel 0% intensity is 0.0 V and
100% intensity is 1.0 V (some references use 0.7 V). Also, each channel input to the VGA
monitor itself per input has a nominal impedance of 75 (similar to the NTSC input
impedance).
VGA Hardware 8
Game Programming for the Propeller Powered HYDRA Page 117
Figure 8:1
The VGA Interface
and Support Hardware
I The HYDRA Hardware
Page 118 Game Programming for the Propeller Powered HYDRA
Therefore, from the D/A’s perspective with both bits on, the circuit looks like that shown in
Figure 8:2 (for any particular channel; R, G, or B). Recall that the Propeller chip is a 3.3 V
device with both channel bits HIGH, that means that we have a 270 in parallel with a
560 and this combination in series with the intrinsic impedance of 75 of the VGA, thus,
we can do a simple computation to compute the voltage at the 75 VGA input realizing we
have a voltage divider configuration:
VGA_IN_RED = 3.3 V × 75 / ( (270 || 560 ) + 75 ) = 0.96 V
Figure 8:2
Electrical Model of
VGA Inputs and
2-bit D/A Channels
...which is what we desire; performing similar math for all 4 combinations of inputs we get
the results shown in Table 8:1 for codes. Considering there are 4 shades of each channel; R,
G, and B that means that there are a total of 4×4×4 = 64 colors available in VGA mode. Not
bad!
VGA Hardware 8
Game Programming for the Propeller Powered HYDRA Page 119
Table 8:1 VGA Input Voltages for all 2-Bit Inputs
B1 B0 Code VGA Voltage Description
0 0 0 0.0 V Black
0 1 1 0.30 V Dark Gray
1 0 2 0.64 V Gray
1 1 3 0.96 V White
Pay attention to the “VGA Enable” switch J10, it’s next to the 74HC244 chip on
the HYDRA and shown in the design (Figure 8:1 on page 117).
You must ENABLE this switch if you want the VGA buffer to send the VGA
signals to the VGA port. If you want to use the I/O port and do NOT want the VGA
port on then DISABLE the switch at J10.
For reference the VGA port has the following pinout shown in Table 8:2. The VGA port on the
HYDRA is a female HD15 (High Density) which is standard on the back of video card
hardware. It will connect to any VGA monitor.
Table 8:2 VGA Female Header Pinout (HD15)
Pin Function Color Code (Most Manufacturers)
1 RED Video BLACK
2 GREEN Video BLACK/WHITE
3 BLUE Video BROWN
4 RESERVED BROWN/WHITE
5 -Ground RED+SHIELD
6 -RED Ground ORANGE
7 -GREEN Ground YELLOW
8 -BLUE Ground MINT GREEN
9 NC NC
10 -GROUND GREEN
11 ID0 (Ground) BLUE
12 ID 1 (NC) PURPLE
13 VSYNC GREY
14 HSYNC WHITE
15 NC SHRIMP
I The HYDRA Hardware
Page 120 Game Programming for the Propeller Powered HYDRA
Looking at the VGA port on the HYDRA (the female), the pinout is as show in Figure 8:3.
Figure 8:3
Female HD-15
VGA port on HYDRA
8.3 VGA Signal Primer
The VGA standard is much easier to understand that the NTSC standard, in fact, using a
visual explanation (Figure 8:4) is usually all people need to see, but still there are some
gotcha’s so we are going to discuss them as well in the brief primer. To start, the actual
important signals you need to generate for VGA are (referring to Table 8:2) Red, Green, and
Blue video as well as Hsync and Vsync. The R,G,B signals are analog voltages representing
the instantaneous intensity of any particular channel and range from 0-1.0 V, but the Hsync
and Vsync are simply TTL signals, usually active LOW (but these can be inverted on most
monitors) where a logic LOW is sync, and a logic HIGH is no sync. Now, let’s look more
closely at the signal itself.
To begin with, the VGA standard as implemented is 640×480 pixels across as shown in
Figure 8:4(A). The image is rendered left to right, top to bottom, similar to the NTSC/PAL
signals, and thus a similar syncing scheme is used that is composed of both a horizontal sync
pulse each line and a vertical sync pulse each frame. However, there are no color burst
signals, serrations, pre-equalizations pulses, etc. and the interface is nearly digital as noted.
The main clock usually used in a VGA generation system is 25.175 MHz; all timing can be
derived from this base frequency. Typically, designers like to run the system dot clock at this
frequency and compute all events as a number of clocks.
For example, getting ahead of myself, take a look at Figure 8:4(B), the Hsync pulse which is
labeled “B” in the table (and a negative polarity), its 3.77 µs, therefore at a dot clock of
VGA Hardware 8
Game Programming for the Propeller Powered HYDRA Page 121
25.175 MHz, or inverting this to get the period time we get 39.72194638 ns. This is how long
a pixel takes, anyway, dividing this into our Hsync time we get:
Number of dot clocks for Hsync pulse = 3.77 µs/ 39.72194638 ns = 94.90 clocks.
The VGA Timing Specifications Figure 8:4
I The HYDRA Hardware
Page 122 Game Programming for the Propeller Powered HYDRA
Call it 95 dot clocks, thus you can simply use a counter and count 95 clocks, drive Hsync
LOW and that’s it. The entire VGA signal can be generated like this. Of course, the tough part
is when you get to video, here you only have roughly 39 nanoseconds to do whatever you
are going to do; this amounts to more or less doing nothing but accessing a video buffer as
fast as you can and getting the next data WORD ready to build the pixel. This is why the
Propeller’s VSU is so cool, it can do this for you and stream BYTEs to the VGA interface (more
on this later in Part II). Anyway, let’s take a closer look at the video portion of the signal as
well as the horizontal and vertical timing aspects of VGA.
8.3.1 VGA Horizontal Timing
Referring to Figure 8:4(B), each of the 480 lines of video are composed of the following
standard named regions:
A (31.77 µs) Scanline time
B (3.77 µs) Hsync pulse
C (1.89 µs) Back porch
D (25.17 µs) Active video time
E (0.94 µs) Front porch
As you can see even the names are similar to NTSC. However, unlike NSTC, VGA is very
unforgiving and you must follow the spec very closely. The next interesting thing is that all
the signals are riding on different lines. For example, the Hsync and Vsync both have their
own signal lines, and the R, G, and B signals do as well, so it’s much easier to generate all
the signals in a large state machine and then route them to the output ports.
Therefore, to generate a line of video (with a negative sync polarity), you start by turning off
all the R, G, B channels with a 0.0 V, and simply hold the Hsync line LOW for 3.77 µs (B).
Then you wait 1.89 µs (C) and the VGA is ready to take R, G, B data, now you clock out 640
pixels at 25.175 MHz for a total time of 25.17 µs (D) for the active video portion. You then
turn the video lines R, G, B off, and wait 0.94 µs (E) and then start the process again. And
that’s all there is too it. Perform this process 480 times then it’s time for a vertical sync and
retrace, so let’s look at that.
8.3.2 8.3.2 VGA Vertical Timing
The vertical sync and retrace is much easier than the horizontal timing since there is no video
to interleave in the signal. Referring to Figure 8:4(C) the various named timing regions of the
vertical timing are:
O (16.68 ms) Total frame time
P (64 µs) Vsync pulse
Q (1.02 ms) Back porch
R (15.25 ms) Active video time
S (0.35 ms) Front porch
VGA Hardware 8
Game Programming for the Propeller Powered HYDRA Page 123
The meaning of each is similar to that in the horizontal sync period, except the “event” they
are focused around is the 480 lines of active video, so the 480 lines are encapsulated in (R).
The most important thing to realize is that these times are measured in milliseconds for the
most part except for the Vsync pulse. So once again, the timing of an entire frame starts off
with the Vsync pulse (P) for 64 µs, after which comes the back porch (Q) for 1.02 ms,
followed by the active video (R) for 15.25 ms. During the active video you don’t need to
worry about the Vsync line since you would be generating 480 lines of video, when complete,
back to the Vsync timing region (S), the front porch for 0.35 ms, and then the frame is
complete.
The thing to remember is that unlike composite video, a VGA signal needs to be driven by
multiple signals for each of the constituent controls; R, G, B, Hsync, and Vsync, which in my
opinion is much easier than modulating and mixing them all together as in NTSC which is a
bloodbath of crosstalk and noise! Now that we have the horizontal and vertical timing for
VGA covered, let’s review the actual video data portion of the signal during the active video
and see what that’s all about.
8.3.3 VGA RGB Video
Generating RGB video is trivial on any system, there is no look-up, no math, just send out
BYTEs or WORDs that represent the RGB values and that’s it. On the HYDRA for example,
there are 2-bits per channel, so the encoding of the VGA data BYTE is as simple as
generating BYTEs in the format shown in Figure 8:5.
VGA Data BYTE Encoding Figure 8:5
For example, forgoing how to do I/O yet on the Propeller chip, let’s say that we have a BYTE
buffer called
vga_byte
and a function
Write_VGA(value, time_us)
that we use to send data
to the VGA port, given that, we can write all kinds of functions that send out different signals
as long as we stream the BYTEs to the port at the 25.175 MHz rate everything will work out
fine. For example, say that we are working with a positive sync system, that is a VGA monitor
that wants a TTL HIGH for sync, then to generate a Hsync pulse we could use some pseudo-
code like this:
vga_byte = %00000010;
Write_VGA(vga_byte, 3.77);
I The HYDRA Hardware
Page 124 Game Programming for the Propeller Powered HYDRA
Ok, now consider we want to draw 640 pixels from an array
video_buffer[ ]
that is storing
the pixel data in BYTE format already in the proper format for our hardware, then all we
would do is this:
byte video_buffer[640]; // pre-initialized video buffer
for (pixel = 0; pixel < 640; pixel++)
Write_VGA(video_buffer[pixel], 0.039721946);
Of course, you would need some mighty fast hardware to delay at a resolution of 39 ns, but
you get the idea. This is a “model” of the algorithm for a line of video, this coupled with the
model for the horizontal timing, vertical timing, and put it all together as a state machine and
you have a VGA generator!
8.4 Summary
Hopefully this chapter has shed some light on the VGA standard. It’s a very cool system, the
only downside being that it’s really fast at 25.175 MHz (39 ns per pixel) and difficult to drive
with a microcontroller that doesn’t have dedicated hardware (like the Propeller chip). But,
speed aside, the standard is “nearly” digital, doesn’t have any funny stuff with the color
encoding, and lends itself nicely to bitmap hardware designs based on RGB color space.
Audio Hardware 9
Game Programming for the Propeller Powered HYDRA Page 125
Chapter 9:
Audio Hardware
There is no dedicated audio hardware inside the Propeller chip or on the HYDRA itself,
therefore we have to rely on software audio generation techniques to create sound for the
system. However, knowing that software is going to be used to generate sound we can add a
little analog circuitry to “help” the audio software out and allow us to use certain common
techniques for generating sounds. In this chapter, we are going to take a look at the circuit
that is used for the audio output. Once again, the Propeller chip takes the fun out of it by
being powerful enough to do everything internally! Anyway, here’s what’s in store this
chapter:
Audio circuit design
Low-pass filters
Frequency modulation (FM)
Pulse code modulation (PCM)
Pulse width modulation (PWM)
Figure 9:1
The HYDRA
Analog Audio
Hardware
9.1 Audio Circuit Design and a Little Background on Low-Pass
Filters
The audio on the HYDRA is generated completely in software and the output is filtered
through a simple analog filter. The circuit is shown in Figure 9:1. Referring to the circuit, we
see that the signal AUDIO_MONO (P7 on the Propeller chip) generates the signal input into
the network. This signal is passed through a low-pass filter consisting of a resistor (R34 @
200 – 1 k) and a capacitor (C13 @ 0.1 µF). Note that these reference designators may
I The HYDRA Hardware
Page 126 Game Programming for the Propeller Powered HYDRA
change in the future, but the point is there is an R/C network here. Moving on, there is also
another AC coupling capacitor (C14 @ 10 µF) which leads to the final output via an RCA
connector and that’s it. The circuit has two sections and they each serve different purposes,
let’s follow the signal through these sections.
The input signal, call it Vin(t), comes in at the port and the low-pass filter made up of R34
and C13 passes low frequencies but blocks high frequencies. This is what’s called a
“single-
pole RC filter.”
The “gain” of the filter or the “transfer function” describes the relationship
between the output and the input signal, thus for a single with a gain of 1 or unity, the
output, (call it Vout(t), would be equal to the input (with some possible phase variance, but
this is irrelevant for our discussion). The single-pole RC filter acts like a voltage divider, but
we have to use more complex math to describe it based on imaginary numbers and/or
differential equations. This is tough to analyze with algebra, but there is a trick based on the
“Laplace Transform”
which transforms differential equations into algebraic equations, and
then we can work with the circuit as if it were made of resistors and transform back when
done. This is all not that important, but its fun to know a little about analog stuff, so let’s
continue.
The Laplace transform denoted by )]([ tfL which looks like this:
+∞
= 0 )(
)]
( [ dtetft f L st
...is a simple integral transform where more or less the function f(t) in the time
domain you want to work with is integrated against an exponential term. The
result of this is the transformation of the time domain function into the “S-
domain” written as F(s), where they are much easier to work with.
So given all that, we want to know what the voltage or signal is at the top of C13 (Vout)
since this signal or voltage will then affect the remainder of the circuit. Using a voltage
divider made of R34 and C13, we need to write a relationship between the input voltage at
AUDIO_MONO, call it Vin(t), and the output voltage of the RC filter at the top of C13, call it
Vout(t). Ok, here goes a few steps:
Vout(s) = Vin(s) × [ (1/sC) / (R + 1/sC)]
Then dividing both sides by Vin(s) we get,
Gain = H(s) = [ (1/sC) / (R + 1/sC)]
Simplifying a bit, results in,
Gain = H(s) = 1 / (1 + sRC)
Audio Hardware 9
Game Programming for the Propeller Powered HYDRA Page 127
Then transforming back from the S-domain to the frequency domain we get,
Gain = H(f) = 1 / (1 + 2 × PI × f × RC)
Note: Technically there is another term in there relating to phase, but it’s not important for
this discussion. In any event, now this is interesting, this equation:
Gain = H(f) = 1 / (1 + 2 × PI × f × RC)
...describes the amplification or more correctly the attenuation of our signal as a function of
frequency f. This is very interesting. Let’s try something fun. Let’s plug in some values really
quickly and see what happens, let’s try 0 Hz, 1 Hz, 100 Hz, 1000 Hz, 1 MHz and see what we
get. Table 9:1 shows the results.
Table 9:1 The Results of Passing Various Frequencies through
a Low-Pass Single-Pole RC Filter
Frequency (f Hz) Gain Comments
0 1/1 DC gain is 1.0 or no attenuation
1 1/(1+2 × PI × RC)
10 1/(1+2 × PI × 10 × RC)
100 1/(1+2 × PI × 100 × RC)
1,000 1/(1+2 × PI × 1000 × RC)
1,000,000 1/(1+2 × PI × 1,000,000 × RC)
This is very interesting; ignoring for a moment the actual values of RC, we see that larger
values of f (frequency) very quickly dominate the denominator and the quotient goes to 0.
This is why this filter is called
“single-pole”
, as the term in the denominator goes to infinity
the quotient goes to zero. Ok, so how does this help us? Well, if we select values of RC, we
can tune the frequency so that this “attenuation” effect gets really strong. This is typically
called the
“3dB point”
, that is the point where the signal is attenuated by 3 dB (decibels)
It’s not really important to know what a decibel is, it’s a measure of power or ratio of signals
more or less, but what is important is that 3 dB is about 70% of the signal. So, if you want to
filter out everything above 10 kHz you would set the 3dB point for about 10 kHz (maybe a bit
more) and you would see the signal gets filtered. Also, note that at DC, frequency f = 0, the
right-hand term in the denominator sum (1 + 2 × PI × 0 × RC) = 1, thus the gain is 1/1 or
1.0 which is exactly what it should be! Cool huh!
I The HYDRA Hardware
Page 128 Game Programming for the Propeller Powered HYDRA
Filters can be a lot of fun since you can chain them together; low-pass, high-pass to make a
band pass, or multiple low- and high-pass to make them fall off faster and so forth. Here’s a
cool tool on the web to get a “feel” for filters:
Low-pass:
http://www.st-andrews.ac.uk/~www_pa/Scots_Guide/experiment/lowpass/lpf.html
High-pass:
http://www.st-andrews.ac.uk/~www_pa/Scots_Guide/experiment/highpass/hpf.html
In any event, playing with the math, the 3dB point for our circuit is:
f3dB = 1/(2 × PI × RC)
Notice, f is not in there since we solved for it. Therefore, we have everything we need to use
the circuit and the equation. Let R and C in our circuit be 1 k and 0.1 µF respectively;
plugging them in we get:
f3dB = 1/(2 × PI × 1 k× 0.1 µF) = 1.59 kHz
...which might be a little low. To loosen this up, let’s make the resistor smaller – 200 :
f3dB = 1/(2 × PI × 200 × 0.1 µF) = 7.95 kHz
...which is a rather high frequency, about 50% of the max range of most human ears which
top out at 15-20 kHz.
Why is this important? Well, first off if you send a signal through our little low-pass filter to
the output (connected to the audio port on the TV) then the signal is going to attenuate at
high frequencies. We will get back to this momentarily; let’s move on to the second stage in
the audio circuit which is based on C14 and POT1. This stage of the circuit is an AC-pass
filter, which means that it will only pass AC and the DC component will be blocked.
In other words, say that the input was a sine wave or square wave with a peak-to-peak
voltage of 1 V, but it was riding on a 2 V signal, this would look like the top trace in Figure
9:2. However, after going through the AC coupling capacitor, the signal would look like the
bottom trace shown in Figure 9:2. So all C14 does is block the DC.
Audio Hardware 9
Game Programming for the Propeller Powered HYDRA Page 129
Figure 9:2
Sine Wave Riding on a Constant
DC Offset as it is Passed Through
a Coupling Capacitor
Now, let’s talk about the some more hardware-related concepts about making sounds with a
couple specific techniques with the HYDRA.
9.1.1 Pulse Code Modulation (PCM)
The most common method to make sound on a game console is to use
PCM
or
Pulse Code
Modulation
. This is really nothing more than storing a series of samples of the sound in
some resolution; 4,8,12,16 bit along at some playback rate. A Windows .WAV file for
example is PCM data, you simply output the data at the proper rate to a D/A converter with
an amplifier connected to a speaker and you will hear the sound. There are a number of
issues with this: first, it takes huge amounts of memory (even with compression), secondly
you need a D/A (digital to analog) converter on the hardware and there are no “synthesis”
opportunities really (of course you can always synthesize the samples). PCM is not an option
for the HYDRA since there is simply so little memory, even with the extended 128K EEPROM's
extra 96 K available to you for assets that wouldn’t get you very far, so PCM was decided to
not make the cut at least as a hardware interface, but you can actually synthesize PCM
through PWM (more on this in a moment).
9.1.2 Frequency Modulation (FM)
Frequency modulation with a fixed waveform is very easy to do electronically and the HYDRA
can do this no problem. The idea here is to output a square wave or sine wave directly to the
output device and then modulate the frequency. So if we use the Propeller chip’s internal
I The HYDRA Hardware
Page 130 Game Programming for the Propeller Powered HYDRA
timers we can do this (more on this later) or we can write a software loop to do it. For
example, if you wanted to hear a 500 kHz, 1 kHz, and 2 kHz signal you just write a software
loop that toggles the output AUDIO_MONO at that rate and you will hear the sound on the
attached output device. Figure 9:3 shows this graphically.
Figure 9:3
Synthesizing a
Single Frequency
Now, there are a couple problems with this: first it’s not readily apparent how to “add”
signals and play more than one sound at once. In fact, it’s nearly impossible directly using
this technique. Secondly, the only signal you can output is a square wave, you can’t output
sine waves. This tends to make the sounds have a “textured” sound since harmonics are in
the square wave. That is, if you output a square wave at frequency f then you will find that
there are harmonics at 3 f, 5 f, etc. all these sine waves are what really make up a square
wave. Take a look at Fourier transform theory to see this:
http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/OWENS/LECT4/node2.html
Of course our little low-pass filter is going to filter most of these harmonics, but you aren’t
going to hear a pure sine until you increase the frequency to about the 3 dB cutoff which
may be desired.
In any event, if all you need is a single channel, some noise, pure tones, then FM with the
AUDIO_MONO port at (P7) is more than enough. You can use software or the built-in timers
to do it on each cog and simply sweep the frequency to get different sounds since you can’t
change the amplitude.
9.1.3 Pulse Width Modulation (PWM)
Pulse width modulation or PCM is a very clever way to create ANY kind of sound with a single
bit of output! The bad news is that the relationships of the output and the algorithms are a
“bit” complicated and take a little bit of numerical analysis, but once you get it working it’s
Audio Hardware 9
Game Programming for the Propeller Powered HYDRA Page 131
not an issue and you can build libraries to create any sound you wish – in fact many
advanced synthesizers use PWM systems, so it’s very powerful.
To start with you might want to “Google” for PWM techniques and read up a bit. Watch out
since most PWM references are about using PWM for motor control. Here are a few PWM
articles to get your started:
http://www.freescale.com/files/32bit/doc/app_note/MC68EZ328PWM.pdf
http://www.freescale.com/files/32bit/doc/app_note/MC68EZ328DTMF.pdf
http://www.intel.com/design/mcs96/technote/3351.htm
http://ww1.microchip.com/downloads/en/AppNotes/00655a.pdf
After reading all these documents you should have a fairly good grasp of PCM techniques.
More or less, PCM is really a method of digital to analog conversion using a single bit output
along with a low-pass filter that acts as an “averaging” or “integration” device. A PCM
signal is at fixed output frequency usually many times the highest frequency you want to
synthesize, for example a good rule of thumb is that the PCM signal should be 10-100x
greater than the frequencies you want to synthesize. Also, the PCM period is
fixed
, and the
modulation of information in the PCM signal is in the duty cycle of the signal. Recall, duty
cycle is defined as:
Duty Cycle = Time Waveform is HIGH / Total Period of Waveform
Duty Cycle Modes (A) Figure 9:4
I The HYDRA Hardware
Page 132 Game Programming for the Propeller Powered HYDRA
Duty Cycle Modes (B) Figure 9:5
For example, say we had a 1 kHz signal, this means the period is 1/1 kHz = 1 ms = 1000 µs.
Now, let’s say we are talking about square waves in a digital system with a HIGH of 5 V and
a LOW of 0 V. Furthermore, let’s say that the duty cycle is 20%; what would the final
waveform look like? Figure 9:4 depicts this. As you can see the waveform is HIGH 20% of
the total period or 200 µs, and the waveform is LOW for 800 µs. Therefore, if you were to
average this signal f(t) over time you would find that the average is simply the area under
the HIGH part divided by the total AREA of the waveform which is:
Average Signal @ 20% duty cycle = (5 V) × [(200 µs)/(1000 µs)] = 1.00 V.
This is a VERY interesting result — by just varying the time we pulse a digital output HIGH
we can create an analog voltage! Thus, we can modulate the analog voltage in any shape we
wish to create a final waveform of any shape we want: sounds, explosions, voices, etc. Plus
since this is all digital we can synthesis as many channels as we wish, since at the end of the
day we need only a single bit as the output. Figure 9:5 shows another PWM-like technique
where instead of modulating the duty cycle, complete 50% duty cycle pulses are sent, but
they are interspersed with 0% duty cycles as a function of time. If the rate of these “pulses”
is high enough, they too create an “average” voltage over time. In Figure 9:5 there are 10
total cycles and in 2 of them we have 50% duty cycles for a total analog voltage per 10
clocks of:
Average Signal @ 20% duty cycle = (5V) × (50%) × [(100 ns)/(1000 ns)] = 0.25 V.
Audio Hardware 9
Game Programming for the Propeller Powered HYDRA Page 133
Notice we are dealing in nanoseconds in the second example; this technique needs to run at
a higher frequency to give the “average” enough time to change at the highest frequency
rate you want to synthesize in this method of D/A.
Now, the only mystery component to the D/A PWM converter is “averaging” of the signal.
Well, fortunately for us, a low-pass filter as used in the HYDRA’s sound circuit (shown in
Figure 9:1) acts as an averaging circuit, in fact, those of you with an EE background know
that 1/S is integral in the S-Domain and a low-pass filter has a 1/S term it in. Intuitively it
makes sense as well since a low-pass filter as shown in Figure 9:1 is really just a charging
circuit and as we send these pulses to it, the circuit charges a bit, then another pulse comes
and it charges a bit more. When a pulse doesn’t come or the duty cycle is smaller, then the
RC circuit discharges, so the PWM-modulated pulse train gets turned into a signal by the
averaging process and looks like a stair step where you can see the averaging period
superimposed on the signal. But, for now realize that the low-pass filter (LPF) that the
HYDRA uses on the audio circuit acts as an LPF as well as an averaging circuit for PWM, so it
has two uses – pretty cool.
Selecting the Filtering Frequency
Also, there are a couple of concerns with the actual values of the LPF so that you don’t get
too much noise. Noise is going to come from the PWM frequency itself. For example, say you
use a PWM frequency of 1 MHz, then your filter obviously needs to cut this frequency out,
but it also needs to cut in at the highest frequency you plan to synthesize. For example, if
you plan to have sounds all the way up to CD-quality at 44 kHz then you might set the 3dB
point at 50 kHz.
Also, we are using an “inactive” single-pole filter. You might want a “sharper” response in a
more high-end sound system like a 2- or 4-pole system. You can achieve this by daisy
chaining our little LPFs together OR you can use an “active filter” based on a transistor or
better yet a simple operational amplifier like the 741. Or even better yet, pick an 8-pole
switched capacitor filter by National, TI, or Linear Tech and the signal will hit a “brick wall” at
the cutoff .
But, for our purposes of games, simple music, sound effects, and explosions, a single-pole
passive filter will do fine. If there is one thing I know, most people can’t tell the difference
between Mozart and Snoop Dogg, so sound can be a little rough.
I The HYDRA Hardware
Page 134 Game Programming for the Propeller Powered HYDRA
PWM Setup Procedure
Let’s briefly digress a moment and work up an example with real numbers, so you can see
this all in your head. Many readers probably have worked with PWM, but may use more
experimental techniques to get results rather than a formal analysis, so this might be
interesting for you.
So to PWM modulate a signal we encode the signal onto the PWM carrier by means of
encoding the information or analog value of the signal onto the PWM carrier by modulating
the period or the duty cycle
of the fixed frequency PWM carrier. This is a VERY important
concept to understand – the PWM frequency/period NEVER changes, only the duty cycle of
any particular cycle. Thus by modulating the information onto the duty cycle we can then
later demodulate the signal by integrating or averaging the PWM signal with a RC circuit and
presto, we have an analog voltage!
Indexing into a Sine Look-up Table to Synthesize a
Signal at a Given PWM Rate Figure 9:6
Audio Hardware 9
Game Programming for the Propeller Powered HYDRA Page 135
The first thing we need to do is decide what kind of waveforms we want to synthesize,
remember they can be
anything
, they can be periodic and simple like sine, square wave
(redundant), triangle, saw-tooth, noise, or even digitized speech. But, to start simple, let’s
synthesize a single sine wave. So first we need a look-up table for sine wave, let’s call it
sinetable[ ] and assume it has 256 entries and we generate it such that a single cycle has
a low of 0 and a high of 255 and is encoded in 8 bits (similar to an example in the
references). Now, the algorithm is fairly simple, we need to index through the sine table a
rate such that we complete a single cycle of our sine wave at the desired output signal
frequency. As a quick and dirty example, let’s say that we use a PWM frequency of 256 kHz
and we want to play a 1 kHz sine wave, then this means that each second there are 256,000
PWM pulses. We want to index into our table and play 1000 iterations of our data which has
a length of 256 entries, thus we need to index into our table at a rate of:
256,000 / (1000 × 256) = 1
Interesting; so every cycle we simple increment a counter into the sine table and output the
appropriate duty cycle in the table look-up. This is shown in Figure 9:6. As another example,
say we want to synthesize a 240 Hz signal, then let’s see what we would need:
256,000 / (240 × 256) = 4.16
In this case, we would increment a counter until it reached 4, then we would increment our
index into our sine table. But this example as well as the last should bring something to your
attention: there is a max frequency we can synthesize and our signal synthesis is going to be
inaccurate for anything but integral divisors, so that’s an issue we need to address in a
moment. First, let’s look at the maximum signal frequency: if you want to play back all 256
sine samples then the maximum “signal” frequency is always:
Maximum Synthesis Frequency = PWM frequency / Number of Samples per Cycle
...which in this example is:
256,000 / 256 = 1000 Hz
So, you have two options: either increase the PWM frequency or index into your sample table
at larger intervals. This problem along with the lack of precision can be handled by use of
fixed-point arithmetic and a little numerical trick. We are going to scale all the math by 8 bits
(or in essence multiply by 256) then we are going to create two variables: one called a
phase accumulator
(PHASE_ACC) and one called a
phase increment
(PHASE_INC). Then
instead of using count-down algorithms, we are going to simply add the phase increment to
the phase accumulator and use the phase accumulator as an index into the sine table.
Therefore, what we have done is turned out 256 element sine table into a “virtual” 256×256
= 65536 element sine table for math purposes to give us more accuracy for slower, non-
integral waveforms as well as to allow fast waveforms to index and skip elements in the look-
up table, so a possible setup is something like this:
I The HYDRA Hardware
Page 136 Game Programming for the Propeller Powered HYDRA
The Phase Accumulator 16-Bit Figure 9:7
Now, we have two interesting properties: first, no matter what the index in the upper 8-bits
can never exceed 255, so we can never go out of bounds of our table; secondly, we can put
very small numbers into the phase accumulator via that phase increment variable.
So now the algorithm for PWM sound is simple:
Step 1: Run the PWM at the output frequency 256,000 Hz.
Step 2: Calculate the Phase Increment (PHASE_INC) to add to the Phase Accumulator
(PHASE_ACC) such that the final desired “signal” frequency is output via the look-up into the
sine or waveform table.
Step 3: Continually add the Phase Increment to the Phase Accumulator and every cycle use
the upper 8-bits of the Phase Accumulator as the index into the 256 element sine table.
Our Final PWM Setup Figure 9:8
Now, to recap, we still have a table that has only 256 elements, but we are going to pretend
it has 65536 elements, that is, 256×256 to improve our accuracy, this is nothing more than
Audio Hardware 9
Game Programming for the Propeller Powered HYDRA Page 137
using a shift << 8 and create a fixed point value in 8.8 format. Next, we are going to call out
a couple variables to make the algorithm easy, one is an accumulator called PHASE_ACC that
simply accumulates the current count, then we convert it back to an integer by shifting it >>
8 times OR just using the upper 8-bits at the index into our 256 element sine table (the later
is preferred). Then we simply need the magic number PHASE_INC that for a given PWM
frequency (256,000 in this case) and a desired output signal frequency along with a specific
number of data table elements will make the whole thing work. Here’s the final math:
Given,
A complete sine waveform has 65536 data entries in our virtual table and 256 in the
real table.
The PWM frequency is 256 K.
NUM_INCREMENTS = The number of times that the PWM signal increments through
the final signal table in ONE complete wave cycle. This is shown in Figure 9:8.
In other words,
NUM_INCREMENTS = signal period / PWM period
= PWM frequency / signal frequency
Now, let’s compute PHASE_INC:
PHASE_INC = 65536 / NUM_INCREMENTS
That is, the PHASE_INC is the rate at which we need to increment through the data table to
maintain the relationship so that the output is changing at the rate of the signal frequency.
Now, plugging this all in together and moving things around a bit:
PHASE_INC = 65536 × signal frequency / PWM frequency
And of course PHASE_ACC is simply set to 0 to begin with when the algorithm starts. As an
example, let’s compute some values and see if it works. First let’s try a 1 kHz signal and see
what we get:
PHASE_INC = 65536 × 1 kHz / 256,000 = 256
I The HYDRA Hardware
Page 138 Game Programming for the Propeller Powered HYDRA
So this means that we add 256 to the phase accumulator each PWM cycle, then use the
upper 8 bits of the phase accumulator as the index, let’s try it a few cycles as see if it works.
Table 9:2 Test of PWM Algorithm at 1 kHz with PHASE_INC of 256
Iteration PHASE_INC PHASE_ACC PHASE_ACC (upper 8 bits)
0 256 0 0
1 256 256 1
2 256 512 2
3 256 768 3
4 256 1024 4
5 256 1280 5
6 256 1536 6
7 256 1792 7
. .
. .
255 256 65280 255
Referring to Table 9:2, we see that for each cycle of the PWM the PHASE_ACC is
incremented by 1 and the next element in the 256 element sine table is accessed, thus the
table is cycled through at a rate of 256,000 / 256 = 1,000 Hz! Perfect! Now, let’s try another
example where the frequency is higher than what we could sustain with our more crude
approach at the beginning of the section with only a counter and not using the accumulator
and fixed point approach. Let’s try to synthesize a 2550 Hz signal.
PHASE_INC = 65536 × 2550 / 256,000 = 652.8
Now, this is a decimal number which will be truncated during the fixed point math to 652,
but this is fine, that’s only an error or:
Truncation error = 100 × (0.8 / 652.8) = 0.12%
I think I can live with that! Table 9:3 shows the results of the synthesis algorithm running
once again.
Audio Hardware 9
Game Programming for the Propeller Powered HYDRA Page 139
Table 9:3 Test of PWM Algorithm at 2500 Hz with PHASE_INC of 652
Iteration PHASE_INC PHASE_ACC PHASE_ACC (upper 8 bits)
0 652 0 0
1 652 652 2
2 652 1304 5
3 652 1956 7
4 652 2608 10
5 652 3260 12
6 652 3912 15
7 652 4564 17
. .
. .
255 652 65000 253
As you can see in this case, each cycle the sine table is accessed by skipping an entry or two
causing a bit of distortion, but since the table has 256 entries the amount of distortion is
1-2% at most, so once again we see that the technique works perfectly. Also, notice that it
takes only 100 cycles of the PWM clock to iterate through one complete cycle of the sine
table which makes sense as well.
In conclusion, the software is where the magic is here. The PWM audio circuitry couldn’t be
simpler than as shown in Figure 9:1. Additionally, you can synthesize multiple channels by
simply having multiple phase accumulators and phase increments; in fact, to synthesize a
64-channel system you would just need something like:
WORD phase_inc[64], phase_acc[64];
...and you simply run a loop over everything, sum up all the phase accumulators each cycle,
and use the sum as the index into the sine table. Of course, the sine table itself has to be
scaled in the amplitude axis and you must do an auto-scale so that the sum doesn’t overflow,
but you get the idea. Moreover, you can store other waveforms like square, triangle,
sawtooth, and so on and then mix various waveforms. Finally, you can easily overlay an
ADSR (attack-decay-sustain-release) envelope to a note-based system and create just about
anything. The only downside to PWM is that it must be VERY accurate, your ears are VERY
sensitive to frequency shifts, so the timing loops must be perfect, thus a hardware timer or a
tight loop needs to be used that doesn’t vary, otherwise you will hear it.
I The HYDRA Hardware
Page 140 Game Programming for the Propeller Powered HYDRA
9.2 Summary
Sound is always one of those things in game consoles and game development in general that
never gets the attention it deserves. Generating sound can be done in a number of ways: on
larger PCs, sound is always generated as PCM data with 8-16 bit D/A’s on the output, but on
small embedded systems they don’t have the memory to do this, thus, a different technique
has to generate the final output and limits must be placed on the types of sounds that can be
generated. PWM is perfect for sound effects, explosions, game sounds, and even music, but
if you want digitized explosions, voice, and so forth, you can use PWM to generate the actual
analog output, sure, but you still need to store all the data – and even at 11 kHz with 8-bit
samples huge amounts of memory can be eaten up for just a few seconds of digital sound.
Thus, on the HYDRA for example, we are going to stick to using FM and PWM techniques
with software-based algorithms for the most part to generate “procedural sounds” that fit
well into the domain of game sound-effects.
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 141
Chapter 10:
Keyboard &
Mouse Hardware
The goal of the HYDRA is to of course be a platform to learn the Propeller chip while at the
same time having fun with game development, but more importantly the HYDRA platform
itself was designed to be a completely stand-alone computing platform for educational,
hobby, and even industrial applications. For example, with a built-in BASIC interpreter or
other language, you can directly plug the HYDRA into your TV set, plug in a keyboard and
mouse, and use it like you would an Atari 800 or Apple II. Thus, the HYDRA has not one but
two PS/2 ports on it which are compatible with any PS/2 device. It just so happens that you
are typically are going to plug a PS/2 keyboard and mouse into these ports, but this is not a
necessity, you can plug any PS/2 device you wish into either port as long as you write a
driver for it. Currently there are drivers for both keyboard and mouse only, but you are free
to write whatever you wish; the hardware interface is robust enough to handle any device. In
any case, this chapter is about the PS/2 interfaces and we are going to focus on the
keyboard and mouse devices and take a brief look at the protocols of each. If you haven’t
ever written a driver for either, they are very interesting devices and support a lot more
functionality than you might believe. Thus, in this chapter we are going to discuss the
following topics:
Hardware interfaces for the mouse and keyboard on the HYDRA
Interfacing to the keyboard and the keyboard serial protocol
Interfacing to the mouse and the mouse serial protocol
10.1 PS/2 Hardware Designs
The Propeller chip is a 3.3 V device, but PS/2 keyboards and mice are 5 V devices, thus a
little bit of extra electronics had to be added to “buffer” or “isolate” the signals. Typically, to
interface to a keyboard or mouse you simply need two bi-directional data lines to connect to
the keyboard/mouse; these are referred to as DATA and CLOCK. PS/2 keyboards and mice
both use a simple 2-line serial protocol (similar to I2C). In the case of the keyboard there is a
microcontroller inside that scans the key matrix and handles the serial communications (in
fact it’s a full blown embedded system), and the mouse is similar, as it has a microcontroller
that tracks the movement of the mouse ball or (optical hardware) by counting pulses and
translating them into relative motions. Newer optical mice of course take pictures of the
mouse surface and compute image gradients to determine motion (pretty cool stuff), but the
idea is the same in that the data is translated into motion data and sent serially to the host.
I The HYDRA Hardware
Page 142 Game Programming for the Propeller Powered HYDRA
The HYDRA’s Keyboard and Mouse Interface Hardware Figure 10:1
The keyboard and mouse interfaces are identical, so we are only going to review the
hardware of one of these devices: the
keyboard
. Referring to Figure 10:1, the connector H1
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 143
is the female receptacle that a PS/2 keyboard plugs into. The pinout is shown in the figure
which we review in a moment, but the point is that there are only two connections we must
concern ourselves with: the DATA line at pin 1 and the CLOCK line at pin 5. Other than
that, we need to provide the keyboard with power at pin 4 (+5 V), and lastly, the ground
reference GND is at pin 3.
Normally, if we had a 5V-compatible system, we could use only 2 data lines from the
microcontroller (one for clock, one for data), but since the Propeller chip is 3.3 V device, the
original design of the keyboard and mouse interface drivers used two (2) lines each for
DATA and CLOCK with transistors to buffer the signals depending on direction. This is not
necessary, but a precaution. Technically, one could design hardware that interfaced the 2
lines from the keyboard or mouse to 2 lines on the Propeller chip (and save a total of 4 lines
between the keyboard and mouse), but the original software drivers used 4 lines per
interface and a buffer design, so I followed it.
To communicate, either the keyboard/mouse or the host (HYDRA) can initiate a conversation.
For example, the HYDRA can talk to the keyboard and instruct it to change settings, or the
keyboard can send scan codes to the HYDRA as well as status information. In most cases, we
can just let the keyboard boot and never worry about it, but if you want to send and receive
you
have
the hardware that allows this. The use of 4 lines to talk to the keyboard/mouse
along with some simple transistors facilitates this.
To begin with, let’s assume that the keyboard wants to talk to the Propeller chip; in this case,
the Propeller chip would need to set P13 and P15 to inputs and “listen” for the keyboard
protocol. The outputs P12 and P14 are unused and should be set LOW during this
transaction, so that transistors Q3 and Q4 are OFF. Now, in this configuration (READ
mode), the keyboard drives P13 and P15, the voltage swing is 0 V and 5 V, but this is fine
since we have the current limiters R10 and R13 in there, so when a 5 V HIGH is on either
the data or KB_DATA or KB_CLOCK lines the inputs of the Propeller chip will clamp to 3.3
V and the 22 k current limiters will make sure current isn’t driven too hard into the Propeller
chip. In this case, when DATA or CLOCK on the keyboard are driven to LOWs by the
keyboard they will drive LOW and pull the inputs to the Propeller chip LOW as well, so all is
good. Finally, if the keyboard places the outputs DATA or CLOCK into a tri-state or high
impedance mode then the 2.2 k pull-ups to +5, R11 and R14, will drive the inputs
KB_CLOCK and KB_DATA HIGH as well, so there is never a time when there is an
undefined logic state on the lines KB_DATA and KB_CLOCK. Of course, the same
arguments are valid for the mouse interface.
I The HYDRA Hardware
Page 144 Game Programming for the Propeller Powered HYDRA
On the other hand, if the Propeller chip wants to control the conversation then it can drive
the DATA and CLOCK lines either LOW or HIGH. When driving the lines HIGH, the
Propeller chip outputs a 3.3 V to either port P12 or P14, a LOW is desired on either CLOCK
or DATA then the transistor much be switched ON. To do this a HIGH must be gated to
the base of the transistor at P12 or P14, this will turn ON either transistor and connect
either KB_CLOCK or KB_DATA to ground which is what we want. If it’s desired that
KB_DATA or KB_CLOCK is driven HIGH then the pull-ups at R11 and R14 will do this for
us, and we only need to make sure the transistors are OFF and therefore the voltage at
either P12 or P14 is LOW respectively.
To review, the keyboard (and mouse) are controlled via two bi-directional data lines: CLOCK
and DATA. PS/2 mouse and keyboards are typically 5 V systems, so to interface them
safely to the Propeller chip and to use the drivers already written for keyboard (and mouse)
we use 4 lines, two each for the DATA and the CLOCK lines to allow bi-directional
communication and control of the lines while maintaining both the 3.3 V and 5 V systems
safely. We will discuss programming the keyboard at length later, but for now let’s briefly
review how the keyboard and mouse both send data.
10.2 Keyboard Operation
The keyboard protocol is straightforward and works as follows: for every key pressed there is
a
"scan code"
referred to as the
"make code"
that is sent; additionally when every is key
released there is another scan code referred to as the
"break code"
that in most cases is
composed of $EO followed by the original make code scan value. However, many keys may
have multiple make codes and break codes. Table 10:1 lists the scan codes for keyboards
running in default mode (startup).
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 145
Table 10:1 Keyboard Default Scan Codes
KEY MAKE BREAK KEY MAKE BREAK KEY MAKE BREAK
A 1C F0,1C 9 46 F0,46 [ 54 FO,54
B 32 F0,32 ` 0E F0,0E INSERT E0,70 E0,F0,70
C 21 F0,21 - 4E F0,4E HOME E0,6C E0,F0,6C
D 23 F0,23 = 55 F0,55 PG UP E0,7D E0,F0,7D
E 24 F0,24 \ 5D F0,5D DELETE E0,71 E0,F0,71
F 2B F0,2B BKSP 66 F0,66 END E0,69 E0,F0,69
G 34 F0,34 SPACE 29 F0,29 PG DN E0,7A E0,F0,7A
H 33 F0,33 TAB 0D F0,0D U ARROW E0,75 E0,F0,75
I 43 F0,43 CAPS 58 F0,58 L ARROW E0,6B E0,F0,6B
J 3B F0,3B L SHFT 12 F0,12 D ARROW E0,72 E0,F0,72
K 42 F0,42 L CTRL 14 F0,14 R ARROW E0,74 E0,F0,74
L 4B F0,4B L GUI E0,1F E0,F0,1F NUM 77 F0,77
M 3A F0,3A L ALT 11 F0,11 KP / E0,4A E0,F0,4A
N 31 F0,31 R SHFT 59 F0,59 KP * 7C F0,7C
O 44 F0,44 R CTRL E0,14 E0,F0,14 KP - 7B F0,7B
P 4D F0,4D R GUI E0,27 E0,F0,27 KP + 79 F0,79
Q 15 F0,15 R ALT E0,11 E0,F0,11 KP EN E0,5A E0,F0,5A
R 2D F0,2D APPS E0,2F E0,F0,2F KP . 71 F0,71
S 1B F0,1B ENTER 5A F0,5A KP 0 70 F0,70
T 2C F0,2C ESC 76 F0,76 KP 1 69 F0,69
U 3C F0,3C F1 05 F0,05 KP 2 72 F0,72
V 2A F0,2A F2 06 F0,06 KP 3 7A F0,7A
W 1D F0,1D F3 04 F0,04 KP 4 6B F0,6B
X 22 F0,22 F4 0C F0,0C KP 5 73 F0,73
Y 35 F0,35 F5 03 F0,03 KP 6 74 F0,74
Z 1A F0,1A F6 0B F0,0B KP 7 6C F0,6C
0 45 F0,45 F7 83 F0,83 KP 8 75 F0,75
1 16 F0,16 F8 0A F0,0A KP 9 7D F0,7D
2 1E F0,1E F9 01 F0,01 ] 5B F0,5B
3 26 F0,26 F10 09 F0,09 ; 4C F0,4C
4 25 F0,25 F11 78 F0,78 ' 52 F0,52
5 2E F0,2E F12 07 F0,07 , 41 F0,41
6 36 F0,36
PRNT
SCRN E0,12,
E0,7C
E0,F0,
7C,E0,
F0,12 . 49 F0,49
7 3D F0,3D SCROLL 7E F0,7E / 4A F0,4A
8 3E F0,3E PAUSE E1,14,77,
E1,F0,14,
F0,77 -NONE-
I The HYDRA Hardware
Page 146 Game Programming for the Propeller Powered HYDRA
The keyboard hardware interface is
either an old style male 5-pin DIN or
a new PS/2 male 6-pin mini-DIN
connector. The 6-pin mini DIN’s pinout
is shown in Figure 10:2 (referenced
looking at the computer’s female side
where you plug the keyboard into,
notice the staggering of the pin
numbering).
Table 10:2 lists the signals for
reference, and the descriptions of the
signals are as follows:
DATA – Bi-directional and used to send and receive data.
CLOCK – Bi-directional; however, the keyboard nearly always controls it. The host can pull
the CLOCK line LOW though to inhibit transmissions; additionally during host keyboard
communications the CLOCK line is used as a “request to send” line of sorts to initiate the host
keyboard transmission. This is used when commands or settings need to be sent to the
keyboard.
VCC/GROUND – Power for the keyboard (or mouse). Specifications state no more than
100 mA
will be drawn, but I wouldn’t count on it and plan for
200 mA
for “blinged-out”
keyboards with lots of lights etc.
When both the keyboard and the host are inactive the CLOCK and DATA lines should be
HIGH (inactive).
PS/2 6-Pin Mini Din Connector
at HYDRA Socket Figure 10:2
Table 10:2 Pinout of PS/2 6-Pin Mini
Din
Pin Function
1 DATA (bi-directional open collector)
2 NC
3 GROUND
4 VCC (+5 @ 100 mA)
5 CLOCK
6 NC
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 147
10.2.1 Communication Protocol from Keyboard to Host
When a key is pressed on the keyboard, the keyboard logic sends the
make scan code
to
the host computer. The scan code data is clocked out by the keyboard in an 11-bit packet;
the packet is shown in Figure 10:3. The packet consists of a
single LOW start bit
(35 µs)
followed by
8 data bits
(70 µs each),
a parity bit
, and finally a
HIGH stop bit
. Data
should be sampled by the host computer on the data line on the falling edge of the CLOCK
line (driven by keyboard). Below is the general algorithm for reading the keyboard.
Figure 10:3
Keyboard Serial Data Packet
10.2.2 Keyboard Read Algorithm
The read algorithm makes the assumption that the main host has been forcing the keyboard
to buffer the last key. This is accomplished by holding
CLOCK
LOW
. Once the host releases
the keyboard, the keyboard will start clocking the clock line and
drop the DATA line
with a
start bit
if there was a key in the buffer, else the
DATA line will stay HIGH
. So the
following steps are
after
the host releases the keyboard and is trying to determine by means
of polling if there is a key in the keyboard buffer.
Step 1: Delay 5 µs to allow hold on CLOCK line to release and keyboard to send buffered
scan code.
Step 2 (Start of frame): If both CLOCK and DATA are low (start bit) then enter into read
loop, else return, no key present.
Step 3 (Start of data): Wait until clock goes high...
Step 4 (Read data): Read data bits loop:
for t = 0 to t <= 7 do
wait for CLOCK to go low...
delay 5 us to center sample
bit(t) = DATA
next t
I The HYDRA Hardware
Page 148 Game Programming for the Propeller Powered HYDRA
Step 5: (Read parity and Stop Bits): Lastly the parity and stop bits must be read.
And that’s it! Of course, if you want to be strict then you should verify the parity bit, but you
don’t need to unless you want to perform error correction.
Both the keyboard and mouse use an “odd parity” scheme for error detection.
Odd parity is HIGH when the number of 1’s in a string is ODD, LOW otherwise.
Even parity is HIGH when the number of 1’s in a string is EVEN, LOW otherwise.
Note that parity only tells us there is an error, but not how to correct it.
10.2.3 Keyboard Write Algorithm
The process of sending commands to the keyboard or “writing” to the keyboard is identical to
that when reading. The protocol is the same except the host initiates the conversation. Then
the keyboard will actually do the clocking while the host pulls on the data line at the
appropriate times. The sequence is as follows:
Step 1: Wait for the keyboard to stop sending data (if you want to play nice). This means
that both the DATA and CLOCK lines will be in a HIGH state.
Step 2 (Initiate transmission): The host drives the CLOCK line LOW for 60 µs to tell the
keyboard to stop all transmissions. This is redundant if you waited for Step 1; however, the
keyboard might not want to shut up, therefore, this is how you force it to stop and listen.
Step 3 (Data ready for transmission): Drive the DATA line LOW, then release the
CLOCK line (by release we mean not to put a HIGH or a LOW, but to set the CLOCK into a
tri-state or input mode, so the keyboard can control it). This puts the keyboard into the
“receiver” state.
Step 4 (Write data): Now, the keyboard will generate a clock signal on the CLOCK line,
you retrieve your DATA, and when the CLOCK line is HIGH you send it on the DATA line.
The host program should serialize the command data (explained momentarily) made up of 8
bits, a parity bit, and a stop bit for a total of 10 bits.
Step 5 (End transmission): Once the last data bit is sent then the parity (odd parity) and
stop bit is sent then the host drives the DATA line (stop bit) and releases the DATA line.
10.2.4 Keyboard Commands
Table 10:3 illustrates some of the commands one can send to a generic keyboard based on
the 8042 keyboard controller originally in the IBM PC spec. This table is not exhaustive and
only a reference, many keyboards don’t follow the commands 100% and/or have other
commands, so be wary of the commands.
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 149
Table 10:3 Keyboard Commands
Code Description
$ED
Set/Reset Mode Indicators: keyboard responds with ACK then waits for a following
option BYTE. When the option BYTE is received the keyboard again ACK's and then sets
the LEDs accordingly. Scanning is resumed if scanning was enabled. If another command
is received instead of the option BYTE (high bit set on) this command is terminated.
Hardware defaults to these indicators turned off.
Keyboard Status Indicator Option BYTE
|7-3|2|1|0|
└──── Scroll-Lock indicator (0=off, 1=on)
└────── Num-Lock indicator (0=off, 1=on)
└──────── Caps-Lock indicator (0=off, 1=on)
└────────── reserved (must be zero)
$EE Diagnostic Echo: keyboard echoes the $EE BYTE back to the system without an
acknowledgement.
$F0
PS/2 Select/Read Alternate Scan Code Sets: instructs keyboard to use one of the three
make/break scan code sets. Keyboard responds by clearing the output buffer/typematic
key and then transmits an ACK. The system must follow up by sending an option BYTE
which will again be ACK'ed by the keyboard:
return BYTE indicating scan code set in use.
select scan code set 1 (used on PC & XT).
select scan code set 2.
03 select scan code set 3.
$F2 PS/2 Read Keyboard ID: keyboard responds with an ACK and a two-BYTE keyboard ID
of 83AB.
$F3
Set Typematic Rate/Delay: keyboard responds with ACK and waits for rate/delay BYTE.
Upon receipt of the rate/delay BYTE the keyboard responds with an ACK, then sets the
new typematic values and scanning continues if scanning was enabled.
Typematic Rate/Delay Option BYTE
|7|6|5|4|3|2|1|0|
└─┴─┴─┴─┴─ typematic rate indicator(A in period formula)
└─┴─────────── typematic delay(B is period formula)
└─────────────── always zero
delay = (rate+1) * 250 (in milliseconds)
rate = (8+A) * (2^B) *0.00417 (in seconds)
Defaults to 10.9 characters per second and a 500 ms delay. If a command BYTE (BYTE
with high bit set) is received instead of an option BYTE this command is cancelled.
$F4 Enable Keyboard: cause the keyboard to clear its output buffer and last typematic key
and then respond with an ACK. The keyboard then begins scanning.
(Table 10:3 is continued on the next page.)
I The HYDRA Hardware
Page 150 Game Programming for the Propeller Powered HYDRA
Table 10:3 Keyboard Commands (continued)
Code Description
$F5 Default w/Disable: resets keyboard to power-on condition by clearing the output buffer,
resetting typematic rate/delay, resetting last typematic key and setting default key types.
The keyboard responds with an ACK and waits for the next instruction.
$F6 Set Default: resets to power-on condition by clearing the output buffer, resetting typematic
rate/delay and last typematic key and sets default key types. The keyboard responds with
an ACK and continues scanning.
$F7
PS/2 Set All Keys to Typematic: keyboard responds by sending an ACK, clearing its
output buffer and setting the key type to Typematic. Scanning continues if scanning was
enabled. This command may be sent while using any Scan Code Set but only has effect
when Scan Code Set 3 is in use.
$F8
PS/2 Set All Keys to Make/Break: keyboard responds by sending an ACK, clearing its
output buffer and setting the key type to Make/Break. Scanning continues if scanning was
enabled. This command may be sent while using any Scan Code Set but only has effect
when Scan Code Set 3 is in use.
$F9
PS/2 Set All Keys to Make: keyboard responds by sending an ACK, clearing its output
buffer and setting the key type to Make. Scanning continues if Scanning was enabled.
This command may be sent while using any Scan Code Set but only has effect when Scan
Code Set 3 is in use.
$FA
PS/2 Set All Keys to Typematic Make/Break: keyboard responds by sending an ACK,
clearing its output buffer and setting the key type to Typematic make/Break. Scanning
continues if scanning was enabled. This command may be sent while using any Scan
Code Set but only has effect when Scan Code Set 3 is in use.
$FB
PS/2 Set Key Type to Typematic: keyboard responds by sending an ACK, clearing its
output buffer and then waiting for the key ID (make code from Scan Code Set 3). The
specified key type is then set to typematic. This command may be sent while using any
Scan Code Set but only has effect when Scan Code Set 3 is in use.
$FC
PS/2 Set Key Type to Make/Break: keyboard responds by sending an ACK, clearing its
output buffer and then waiting for the key ID (make code from Scan Code Set 3). The
specified key type is then set to Make/Break. This command may be sent while using any
Scan Code Set but only has effect when Scan Code Set 3 is in use.
$FD
PS/2 Set Key Type to Make: keyboard responds by sending an ACK, clearing its output
buffer and then waiting for the key ID (make code from Scan Code Set 3). The specified
key type is then set to Make. This command may be sent while using any Scan Code Set
but only has effect when Scan Code Set 3 is in use.
$FE Resend: should be sent when a transmission error is detected from the keyboard.
$FF Reset: Keyboard sends ACK and waits for system to receive it then begins a program
reset and Basic Assurance Test (BAT). Keyboard returns a one BYTE completion code
then sets default Scan Code Set 2.
There are software “objects” written by Parallax that do all this for us on the Propeller chip,
but if you want to write your own or optimize the current drivers then this information comes
in handy. Now, let’s briefly review the mouse protocol.
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 151
10.3 Communication Protocol from Mouse to Host
The mouse protocol is exactly the same as the keyboard protocol as far as sending and
receiving BYTEs with the 11-bit packet. The only difference of course is the data format the
mouse sends to the host and the commands the host (HYDRA) can send the mouse. Again,
we will see programming examples in Part II, but let’s just review the technical details briefly
to get acquainted with the commands and data.
10.3.1 Basic Mouse Operation
The standard PS/2 mouse interface supports the following inputs:
X (right/left) movement
Y (up/down) movement
Left, Middle, and Right buttons
The mouse has an internal microcontroller that translates the motion of the mouse
whether it be a mechanical ball, optical tracking system, or something else. These
inputs along with the buttons are scanned at a regular frequency and updates are made to
the internal “state” of the mouse via various counters and flags that reflect the movement
and button states. Obviously there are mice these days with a lot more than 3 buttons and 2
axes, but we are not going to concern ourselves with these (extensions), we just need to
read the X,Y position along with the state of the buttons for simple mousing and game
applications.
The standard PS/2 mouse has two internal 9-bit 2’s complement counters (with an
overflow bit each) that keep track of movement in the X and Y axis. The X and Y counters
along with the state of the three mouse buttons are sent to the host in the form of a 3-BYTE
data packet. The movement counters represent the amount of movement that has occurred
since the last movement data packet was sent to the host; therefore they are relative
positions, not absolute.
Each time the mouse reads its inputs (controlled internally by the microcontroller in the
mouse), it updates the state of the buttons and the deltas in the X, Y counters. If there is an
overflow, that is if the motion from the last update is so large it can’t fit in the 9 bits of either
counter, then the overflow flag for that axis is set to let the host know there is a problem.
The parameter that determines the amount by which the movement counters are
incremented/decremented is the
resolution
. The default resolution is
4 counts/mm
and
the host may change that value using the "Set Resolution" ($E8) command. Additionally,
the mouse hardware can do a scaling operation to the sent data itself to save the host the
work. The
scaling
parameter controls this. By default, the mouse uses 1:1 scaling, which
means that the reported motion is the same as the actual motion. However, the host may
select 2:1 scaling by sending the "Set Scaling 2:1" ($E7) command. If 2:1 scaling is
I The HYDRA Hardware
Page 152 Game Programming for the Propeller Powered HYDRA
enabled, the mouse applies the following mapping as shown in Table 10:4 to the counters
before sending their contents to the host in the data packet.
Table 10:4 Mouse Scaling reported Data
Mapping when in 2:1 mode
Actual Movement (delta) Reported Movement
0 0
1 1
2 1
3 3
4 6
5 9
delta > 5 delta × 2
So the scaling operation only takes affect when the actual movement delta is greater than 1,
and for delta > 5, the reported movement is always (delta × 2). Now, let’s look at the
actual data packet format for the mouse state.
10.3.2 Mouse Data Packets
The PS/2 mouse sends the movement information to the host which includes the position
counters, button state, overflow flags and sign bits in the format show in Table 10:5.
Table 10:5 Mouse Data Packet Format
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
BYTE 1 Y overflow
bit X overflow
bit Y sign bit X sign bit Always 1 Middle
Button Right Button Left Button
BYTE 2 X Movement (delta)
BYTE 3 Y Movement (delta)
The movement counters are 9-bit 2's complement integers; since the serial protocol only
supports 8 bits at a time, the uppermost sign bit for each 9-bit integer is stored in BYTE 1 of
the overall movement packet. Bit 4 holds the 9th bit of the X movement and Bit 5 holds the
9th bit of the Y movement. Typically, you don’t need to worry about the 9th bits since that
would be a lot of motion in one update, so just use BYTEs 2 and 3 to track motion.
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 153
The motion counters are updated when the mouse reads its input and movement has
occurred. As noted, the movement counters only record
differential
or delta motion rather
than absolute. With a 9-bit value recording each counter, a total amount of -255 to +256 can
be represented in 9-bit 2’s complement. If this range is exceeded, the appropriate overflow
bit is set for either the X or Y counter. Note that the movement counters are reset whenever
a movement data packet is successfully sent to the host. The counters are also reset after
the mouse receives any command from the host other than the "Resend" ($FE) command.
Next, let’s discuss the different mouse operation modes.
10.3.3 Modes of Operation
There are four standard modes of operation which dictate how the mouse reports data to the
host, they are:
RESET: The mouse enters
Reset
mode
at power-up or after receiving the
"Reset" ($FF) command. For this mode to occur both the DATA and CLOCK lines
must be HIGH.
STREAMING: This is the default mode (after Reset finishes executing) and is the
mode in which most software uses the mouse. If the host has previously set the
mouse to Remote mode, it may re-enter Stream mode by sending the
"Set Stream Mode" ($EA) command to the mouse.
REMOTE: Remote mode is useful in some situations and may be entered by sending
the "Set Remote Mode" ($F0) command to the mouse.
WRAP: This diagnostic mode is useful for testing the connection between the mouse
and its host. Wrap mode may be entered by sending the "Set Wrap Mode" ($EE)
command to the mouse. To exit Wrap mode, the host must issue the "Reset"
($FF) command or "Reset Wrap Mode" ($EC) command. If the "Reset" ($FF)
command is received, the mouse will enter Reset mode. If the "Reset Wrap Mode"
($EC) command is received, the mouse will enter the mode it was in prior to Wrap
mode.
RESET Mode - The mouse enters Reset mode at power-on or in response to the
"Reset" ($FF) command. After entering reset mode, the mouse performs a diagnostic self-
test referred to as BAT (Basic Assurance Test) and sets the following default values:
Sample Rate = 100 samples/sec
Resolution = 4 counts/mm
Scaling = 1:1
Data Reporting Disabled
I The HYDRA Hardware
Page 154 Game Programming for the Propeller Powered HYDRA
After Reset, the mouse sends a BAT completion code of either $AA (BAT successful) or $FC
(Error). The host's response to a completion code other than $AA is undefined. Following the
BAT completion code of $AA (ok) or $FC (error), the mouse sends its device ID of $00. This
distinguishes the standard PS/2 mouse from a keyboard or a mouse in an
extended
mode
.
After the mouse has sent its device ID of $00 to the host, it will enter
Stream mode
. Note
that one of the default values set by the mouse is
"Data Reporting Disabled."
This
means the mouse will not issue any movement data packets until it receives the
"Enable
Data Reporting"
command. The various modes of operation for the mouse are:
STREAM Mode - In stream mode, the mouse sends movement data when it detects
movement or a change in state of one or more mouse buttons. The rate at which this data
reporting occurs is the
sample rate
(defaults to 100 samples/sec on Reset). This
parameter can range from 10 to 200 samples/sec on most drivers. The default sample rate
value is 100 samples/sec, but the host may change that value by using the "Set Sample
Rate" command. Stream mode is the default mode of operation following reset.
REMOTE Mode - In this mode the mouse reads its inputs and updates its counters/flags at
the current sample rate, but it
does not
automatically send data packets when movement
occurs, rather the host must
“poll”
the mouse using the
"Read Data"
command. Upon
receiving this command the mouse sends back a single movement data packet and resets its
movement counters.
WRAP Mode - This is an
"echoing"
mode in which every BYTE received by the mouse is
sent back to the host. Even if the BYTE represents a valid command, the mouse will not
respond to that command — it will only echo that BYTE back to the host. There are two
exceptions to this: the
"Reset"
command and
"Reset Wrap Mode"
command, this is
obviously the only way to get the mouse back out of the Wrap mode! The mouse treats
these as valid commands and does not echo them back to the host. Thus Wrap mode is a
good diagnostic mode to test if a mouse is connected and if it’s working.
10.3.4 Sending Mouse Commands
A mouse command similar to a keyboard command in that it is sent using the standard 11-bit
serial protocol outlined in the Keyboard Write section. The commands supported are shown
in Table 10:6.
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 155
Table 10:6 Command Set for Standard PS/2 Mouse
Code Description
$FF Reset: The mouse responds to this command with "acknowledge" ($FA) then enters Reset
Mode.
$FE
Resend: The host can send this command whenever it receives invalid data from the
mouse. The mouse responds by resending the last packet it sent to the host. If the mouse
responds to the "Resend" command with another invalid packet, the host may either issue
another "Resend" command, issue an "Error" command, cycle the mouse's power supply to
reset the mouse, or it may inhibit communication (by bringing the Clock line low). The action
taken depends on the host.
$F6
Set Defaults: The mouse responds with "acknowledge" ($FA) then loads the following
values into its driver:
Sampling rate = 100
Resolution = 4 counts/mm
Scaling = 1:1
Disable Data Reporting
The mouse then resets its movement counters and enters Stream mode
$F5
Disable Data Reporting: The mouse responds with "acknowledge" ($FA) then disables
Data Reporting mode and resets its movement counters. This only effects data reporting in
Stream mode and does not disable sampling. Disabled Stream mode functions the same as
Remote mode.
$F4
Enable Data Reporting: The mouse responds with "acknowledge" ($FA) then enables Data
Reporting mode and resets its movement counters. This command may be issued while the
mouse is in Remote mode (or Stream mode), but it will only effect data reporting in Stream
mode.
$F3
Set Sample Rate: The mouse responds with "acknowledge" ($FA) then reads one more
BYTE from the host which represents the sample rate in unsigned 8-bit magnitude format.
The mouse saves this BYTE as the new sample rate. After receiving the sample rate, the
mouse again responds with "acknowledge" ($FA) and resets its movement counters. Most
mice accept sample rates of 10, 20, 40, 60, 80, 100 and 200 samples/sec.
$F2 Get Device ID: The mouse responds with "acknowledge" ($FA) followed by its device ID
($00 for the standard PS/2 mouse.) The mouse also resets its movement counters in most
cases.
$F0 Set Remote Mode: The mouse responds with "acknowledge" ($FA) then resets its
movement counters and enters Remote mode.
$EE Set Wrap Mode: The mouse responds with "acknowledge" ($FA) then resets its movement
counters and enters Wrap mode.
$EC Reset Wrap Mode: The mouse responds with "acknowledge" ($FA) then resets its
movement counters and enters the mode it was in prior to Wrap mode (Stream Mode or
Remote Mode.)
$EB Read Data: The mouse responds with acknowledge ($FA) then sends a movement data
packet. This is the only way to read data in Remote Mode. After the data packet has been
successfully sent, the mouse resets its movement counters.
(Table 10:6 is continued on the next page.)
I The HYDRA Hardware
Page 156 Game Programming for the Propeller Powered HYDRA
Table 10:6 Command Set for Standard PS/2 Mouse (continued)
Code Description
$EA Set Stream Mode: The mouse responds with "acknowledge" then resets its movement
counters and enters Stream mode.
$E9
Status Request: The mouse responds with "acknowledge" then sends the following 3-
BYTE status packet (then resets its movement counters) as shown below:
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
BYTE 1 Always 0 Mode Enable Scaling Always 0 Left
Button Middle
Button Right
Button
BYTE 2 Resolution
BYTE 3 Sample Rate
Right, Middle, Left button = 1 if button pressed; 0 if button is not pressed.
Scaling = 1 if scaling is 2:1; 0 if scaling is 1:1 (Refer to commands $E7 and $E6).
Enable = 1 if data reporting is enabled; 0 if data reporting is disabled (Refer to commands
$F5 and $F4).
Mode = 1 if Remote Mode is enabled; 0 if Stream mode is enabled (Refer to commands $F0
and $EA).
$E8
Set Resolution: The mouse responds with
acknowledge ($FA) then reads the next
BYTE from the host and again responds
with acknowledge ($FA) then resets its
movement counters. The BYTE read from
the host determines the resolution as
follows:
BYTE Read from Host Resolution
$00 1 count /mm
$01 2 count /mm
$02 4 count /mm
$03 8 count /mm
$E7 Set Scaling 2:1: The mouse responds with acknowledge ($FA) then enables 2:1 scaling
mode.
$E6 Set Scaling 1:1: The mouse responds with acknowledge ($FA) then enables 1:1 scaling
(default).
Lastly, the only
commands
the standard PS/2 mouse will send
to the host
are "Resend"
($FE) and "Error" ($FC). They both work the same as they do as host-to-device
commands. Other than that the mouse simply sends 3-BYTE data motion packets in most
cases.
If the mouse is in Stream mode, the host should disable data reporting
(command $F5) before sending any other commands. This way, the mouse won’t
keep trying to send packets back while the host is trying to communicate with
the mouse.
Keyboard & Mouse Hardware10
Game Programming for the Propeller Powered HYDRA Page 157
10.3.5 Mouse Initialization
During the mouse power-up both the DATA and CLOCK lines must be pulled HIGH and/or
released/tri-stated by the host. The mouse will then run its power-up self-test or BAT and
start sending the results to the host. The host watches the CLOCK and DATA lines to
determine when this transmission occurs and should look for the code $AA (ok) followed by
$00 (mouse device ID). However, you can forgo this step if you like and just wait 1-2
seconds and “assume” the mouse was plugged in properly. You do not have to respond to
this code in other words. If you wish to Reset the mouse, you can at any time send the
command code $FF, and the mouse should
respond
with $FA to acknowledge that
everything went well.
Once the mouse sends the $AA, $00 startup codes, it enters its standard default mode as
explained in the sections above. The only thing we need to do to get the mouse sending
packets is to tell the mouse to start reporting movement. This is done by sending the
command “Enable Data Reporting” ($F4); the mouse responds with $FA to acknowledge
the command worked and then will start streaming out 3-BYTE movement packets at the
default rate of 100 samples/sec. This step is necessary, since on start-up if the mouse simply
started streaming data packets the host could lose important data, thus the mouse “waits” to
be told to start streaming the data and reporting the motion.
The movement data packets are formatted as shown in Table 10:5 on page 152. You simply
need to read these packets and send them upstream to your application.
10.3.6 Reading Mouse Movement
Assuming that the mouse has been initialized and is in Streaming mode with Reporting mode
enabled, you simply loop and read each 3-BYTE movement packet. As you read the first
BYTE you use it to determine the state of the buttons as well as any overflows with the
counters. Then the next two BYTEs, the X and Y deltas, should be added to running counters
(16-bit) that track the absolute position of the mouse cursor. That’s it!
10.4 Summary
The amount of technology in a PC always amazes me; if you haven’t ever written a keyboard
or mouse driver, you are probably thinking, “I had no idea there was so much going on with
the mouse and keyboard!” That’s the thing about the PC, it’s truly a marvel of technology
and all the interfaces used are very well thought out (usually). This of course makes our lives
much easier since there is good documentation on how to interface to the mouse and
keyboard, which in turn makes writing drivers much less painful. Also, remember that for
games and specific applications you do not need a bulletproof driver as you might for a real
PC. The keyboard and mouse drivers provided by Parallax (which we will discuss later) are
fairly complete and definitely overkill. When you design games and applications on the
HYDRA (and Propeller chip), you will find that these drivers are a good starting point, but you
I The HYDRA Hardware
Page 158 Game Programming for the Propeller Powered HYDRA
will tend to strip them and simplify them to save memory so you can write larger and larger
programs. For example, I have written both keyboard and mouse drivers in about 20-30 lines
of ASM code, that’s all you really need to for the really baseline functionality.
Game Cartridge, EEPROM & Expansion Port 11
Game Programming for the Propeller Powered HYDRA Page 159
Chapter 11:
Game Cartridge,
EEPROM &
Expansion Port
Hardware
In this chapter we are going to discuss the
“expansion port
on the HYDRA as well as the
design of the onboard serial EEPROM since they are related. The expansion port is the most
powerful aspect of the HYDRA since it allows you to plug in enhancement products to
upgrade the HYDRA including more memory, I/O, extra processors, or whatever you can
think up! As is, the HYDRA comes with both a
128 K Game Card
as well as a
Blank Experimenter Card
. We are going to discuss all these topics and more, here’s
what’s in store:
Game expansion port design and signals.
Blank Experimenter Card design.
128 K Memory Card design.
Onboard 128 K serial EEPROM design.
11.1 HYDRA Expansion Port Design
Figure 11:1
The HYDRA Expansion Port
I The HYDRA Hardware
Page 160 Game Programming for the Propeller Powered HYDRA
The HYDRA has a 20 pin expansion port (J9) as shown in Figure 11:1 that can be used for a
number of expansion functions. The port itself is an industry standard female edge connector
interface with 0.1” contact spacing on both sides. Typically, the idea of an “expansion port” is
to export as much of the system busses and I/O as possible, so future upgrades and add-ons
can be built on the platform. With this in mind, the expansion port exports:
Power (for both the 3.3 V and 5.0 V
supplies)
Networking (the built in RJ-11 ad-hoc
serial network)
USB (serial TX and RX along with
ground)
8 I/Os (general I/Os from Propeller chip
also used for VGA interface)
System reset
Serial EEPROM interface (so an EEPROM
on the cartridge can be loaded rather
than the onboard EEPROM)
Loop-back signals to detect cartridge
insertions
Everything is self-explanatory except maybe
the
“loop-back”
power lines. There are
used to indicate a cartridge is plugged in.
The power lines are looped back on the
cartridge and then “sensed” back on the
HYDRA via the signal lines 33VCC_LOOP
and 5VCC_LOOP. This way the HYDRA
can tell if something is plugged in and your
code can take different execution paths, or
you can wire them directly to hardware
selection logic to gate in/out various
components. Referring to the image in
Figure 11:1 of the expansion port take a
look at Figure 11:2, it’s the actual design of
the expansion port and shows the lines that
are exported.
The Design of the
Expansion Port Figure 11:2
Game Cartridge, EEPROM & Expansion Port 11
Game Programming for the Propeller Powered HYDRA Ì Page 161
11.1.1 Expansion Port Signal Definitions
Table 11:1 below lists the actual signal names and their connections to the Propeller chip as
well as their functions for the expansion port.
Table 11:1 The Mapping of Expansion Port Signals to the Propeller Chipb
Expansion Port
Signal Expansion
Port Pin Propeller
Pin# / Name Description
I/O_0 1 21 / P16 General I/O (shared with VGA_VSYNC)
I/O_1 2 22 / P17 General I/O (shared with VGA_HSYNC)
I/O_2 3 23 / P18 General I/O (shared with VGA_BLUE_B0)
I/O_3 4 24 / P19 General I/O (shared with VGA_BLUE_B1)
I/O_4 5 25 / P20 General I/O (shared with VGA_BLUE_G0)
I/O_5 6 26 / P21 General I/O (shared with VGA_BLUE_G1)
I/O_6 7 27 / P22 General I/O (shared with VGA_BLUE_R0)
I/O_7 8 28 / P23 General I/O (shared with VGA_BLUE_R1)
NET_TX_DATA 9 3 / P2 HYDRA Net Transmit Line
NET_RX_CLK 10 2 / P1 HYDRA Net Receive / Clocking Line
RESn 11 11 / RESn System Reset Active LOW
SCK_CART 12 37 / P28 Serial Clock for Cartridge / EEPROM
SDA_CART 13 38 / P29 Serial Data for Cartridge / EEPROM.
33VCC 14 POWER Connects to 3.3 V Power Supply
3VCC_LOOP 15 POWER Optional Feedback Loop from Cartridge to HYDRA
5VCC 16 POWER Connects to 5.0 V Power Supply
5VCC_LOOP 17 POWER Optional Feedback Loop from Cartridge to HYDRA
USB_TXD 18 N/A USB Transmit Serial Line
USB_RXD 19 N/A USB Receive Serial Line
GND 20 POWER Connects to System GROUND
The only signals that deserve some extra explanation are the I/O_0..7 lines. These lines are
shared with the VGA interface, so when you are driving a VGA monitor, you can’t use these
lines on your plug-in card (unless of course that is the intent). The VGA Enable switch at J10
enables or disables the VGA outputs. So if you want to drive VGA with these lines, you would
place the VGA Enable switch into the “on” position. When you are not driving VGA, it’s best
to keep the VGA Enable in the “off” position. The VGA Enable switch as noted early in the
I The HYDRA Hardware
Page 162 Game Programming for the Propeller Powered HYDRA
book simply enables/disables the tri-state buffer logic and doesn’t let the I/O’s drive the VGA
interface if they are not meant to.
Additionally, you might be concerned with power draw from the cartridge port and how much
you can pull from the HYDRA? The HYDRA’s power adaptor is 300-500 mA, so as long as you
leave enough to power the HYDRA and the systems in use then there is no limit to the
power-up to the supply current of the power adaptor. However, I suggest that if you do
design an expansion card yourself, that you decouple the power coming in on the 3.3 V and
5.0 V supplies with a 0.01–0.1 µF cap, and a 1.0–10.0 µF tantalum cap to keep the power
clean. Both the experimenter card and the 128 K expansion card have power decoupling on
them already.
11.2 Blank Experimenter Card
To get you started on your own experiments, the HYDRA kit comes complete with a blank
experimenter card as shown in Figure 11:3.
The Blank Experimenter Card Figure 11:3
As you can see, the card has nothing on it but decoupling caps and power LEDs. The header
areas have a solder through-pin for each signal, so you can simply wire into them.
Additionally there is space on the surface to place a couple of DIP-style TTL chips along with
some passive components. There are 3 rows of 18 contacts, along with large “common” rails
along the top and bottom referring to the figure. This is a great way to start experimenting
with expanding the HYDRA and/or adding small boards to the Propeller chip’s functionality
via the expansion port. The 128 KB memory expansion game card was derived from this
design.
Game Cartridge, EEPROM & Expansion Port 11
Game Programming for the Propeller Powered HYDRA Page 163
11.3 128K Memory Card
Figure 11:4 shows the 128 KB memory expansion card that comes with the HYDRA kit. The
serial EEPROM is based on the 8-pin 24C1024 model which a number of manufactures’ sell
(Atmel is my favorite).
The 128 KB memory expansion card is more or
less a copy of the 128 KB serial EEPROM
design found on the HYDRA itself copied to an
expansion card. The 32 KB and 128 KB
expansion cards are similar, but simply have
smaller EEPROMs on them.
The magic of the card is that when plugged in,
the Propeller chip on the HYDRA reads the
card’s serial EEPROM rather than the onboard
serial EEPROM. This is facilitated via the
loop-back signals. When the card is inserted,
the loop-back signals, specifically the
3VCC_LOOP signals, are used to enable the
card’s EEPROM while disabling the onboard
serial EEPROM. This is possible since the serial
EEPROMs have addressing lines A0..2 that
allow up to 8 devices to be chained together
on the same buses as long as only one device
is selected at a time.
The 128 K
Memory Expansion
/ Game Card
Figure 11:4
I The HYDRA Hardware
Page 164 Game Programming for the Propeller Powered HYDRA
Figure 11:5 shows the design of the expansion card. Notice all 3 address selects are LOW;
this always selects the EEPROM, thus when plugged into the HYDRA it will always be
addressed. Therefore, it’s up to the design of the HYDRA’s onboard 128 KB serial EEPROM
design which we will take a look at next.
Figure 11:5
The Design for the 128 K
Memory Expansion/Game Card
11.4 Onboard 128 K Serial EEPROM Design
The Propeller chip works with a 32 KB “image” that the IDE/compiler generates. All your
code, assets, and data must fit into this 32 KB. However, after the Propeller chip is done
reading the 32 KB memory image from the serial EEPROM on boot, the lines are released and
you can still access the EEPROM device yourself. The HYDRA uses the largest available serial
EEPROMs which are 128 KB. This way you can fit your 32 KB Propeller program in the
Game Cartridge, EEPROM & Expansion Port 11
Game Programming for the Propeller Powered HYDRA Ì Page 165
EEPROM, but you have an additional 96 KB of storage for assets, data, real-time monitoring,
digitizing – you name it! Also, later when more tools are available from Parallax and others,
you will be able to access the expanded 96 KB of the serial EEPROM and place assets there
as part of the Propeller took itself. However, for now, we must as programmers write our
own tools to do this and write our own drivers to talk to the serial EEPROM’s expanded
memory.
aThe Onboard 128 K EEPROM Design Figure 11:6
Figure 11:6 depicts the design for the onboard serial EEPROM, pins 5 and 6 of the EEPROM
are connected to the system lines P28/P29 which are the
“serial clock”
(SCK) and
“serial data”
(SDA) respectively on the Propeller chip. Those connections are standard and
nothing exciting is going on there. The only action happens on the addressing lines, notice
there are 3 addressing lines A2..0. A0 and A2 are grounded, but A1 is driven by a weak
pull-down as well as the 3VCC_LOOP signal from the expansion port. Normally, when A1 is
grounded the serial EEPROM is selected and Propeller chip reads from it, but the moment a
game card is plugged in the 3VCC_LOOP is driven HIGH, disabling the onboard serial
EEPROM and the EEPROM that the game card is gated in! Presto, plug-and-play that works!
I The HYDRA Hardware
Page 166 Game Programming for the Propeller Powered HYDRA
If you’re interested in learning more about serial EEPROMs and designing around them as
well as programming them please review this file on the CD:
CD_ROOT:\HYDRA\DOCS\atmel 24c1024_datasheet.pdf
11.5 Summary
Having an open interface to expand any hardware device is the #1 feature as far as I am
concerned. The Atari 800 for example was a feat of engineering, 10 times more advanced
than the Apple II, but the Apple II sold 10 times more units because the Apple II allowed
users to build their own expansion cards for the device and also openly documented the
hardware interface. The Atari 800 had expansion slots as well, but they were very hard to
find information on to interface with. So the moral of the story is: the easier it is to build add
on cards the more useful hardware will be. I personally can’t think of a fraction of the cool
things that can be done with a Propeller chip, but I know that by having an expansion port
with a commonly found edge connector interface, others can create their own add-on
hardware and expand the HYDRA itself. At some point, I hope to see Ethernet interfaces,
LCD, IDE, flash drive, and even SRAM, CPU, and FPGA cards! At very least take the free
blank expansion card, throw a 7447 on there and a 7-segment display and use it for
debugging!
HYDRA-NET Network Interface Port12
Game Programming for the Propeller Powered HYDRA Page 167
Chapter 12:
HYDRA-NET
Network
Interface Port
The simplest interface in the world is the good old RS-232 standard; however, the physical
interfaces are usually DB9 or DB25 and are very bulky and expensive. Ethernet is great, but
very complex and very expensive as well. So when designing the HYDRA, I wanted to
facilitate networking but I didn’t want it to be expensive, bulky, or complex to program. On
the other hand, I wanted to be able to connect HYDRAs hundreds of feet from each other
with commonly available cabling – After thinking about it, I thought why not use phone
cables? They have 4 conductors (2-conductor products exist as well), act like twisted pairs,
cost nearly nothing (a 100-foot phone extension line is $5.00 USD) and they are very flexible
and look cool and come in colors to boot! So, I was sold. I therefore designed a physical
network interface on the HYDRA for RJ-11 standard phone connectors, and designed
electronics to help interface the HYDRA using standard RS-232 serial techniques. In this
chapter, we are going to look at the networking on the HYDRA, the hardwar