Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

FPGA BASED VGA DRIVER

AND ARCADE GAME

ARMANDAS JARUSAUSKAS
THIRD YEAR INDIVIDUAL PROJECT
2009/2010

SCHOOL OF ENGINEERING & DESIGN


UNIVERSITY OF SUSSEX
This work is licensed under the Creative Commons
Attribution 3.0 License. To view a copy of this license,
visit http://creativecommons.org/licenses/by/3.0/
Abstract

Field­Programmable Gate­Array (FPGA) technology is gaining popularity among Application­Specific 
Integrated Circuit (ASIC) designers. Ease of development and maintenance makes FPGAs an attractive 
solution to many speed and efficiency­critical applications. The purpose of this project is to explore the 
world of FPGAs by implementing an arcade game on top of a VGA driver. The project was implemented  
on Xilinx Spartan­3E development board using VHDL hardware description language.
The project was started by learning VHDL as well as familiarising with the Spartan­3E development  
board and Xilinx ISE WebPACK design software. A number of simple applications were developed in 
order to comfortably proceed on to investigation of working principles of a VGA driver. It turned out 
that the synchronisation logic was rather trivial and that the custom implementation would not add 
much value to the project.
VHDL implementation of the classic Pong game was the first major task of the project. Plong, as it was  
named, is a two­player game, where each player tries to to hit a ball towards the opponent. A number 
of basic features, such as acceleration of the ball, sound output and textual information display, have  
been   implemented.   As   this   game   was   developed   in   the   early   stage   of   the   project,   complexity   was  
consciously avoided.
The  objectives   the   second   game,  on  the  other   hand,  were  focused   on  technical  features  and  other 
improvements. Still monochrome images were exchanged for colourful animations, sound output was 
made more sophisticated by adding a tune player, Nintendo game pads replaced on­board switches as a 
user   input   interface   and   a   number   of   other   modules   were   developed.   The   theme   was   chosen   to 
resemble the Space Invaders game, but all graphic elements were designed from scratch.
To make the project more complete and self contained, the two games were combined into a single 
application, with a menu screen to allow user to choose which game to play.
Lastly, an adaptor board, for connecting NES game pads to the development board, was designed and 
built. It facilitates the communication between the controllers and the FPGA. The board also hosts a 
piezoelectric buzzer for sound output and a reset switch.
The project was complete and fully functional before the deadline. While there is still a lot of room for  
improvement, all set objectives, and more, were met.
Statement of originality
I hereby declare that this report is my own work and to the best of my knowledge it contains no
materials previously published or written by another person, or which have been accepted for the
award of any degree or diploma at any educational institution, except where due acknowledgement is
made in the report itself.
Acknowledgements
First supervisor: Dr Ahmet Aydin
Second supervisor: Dr Christopher Harland

I would like to thank the following people for all the help and support:
• Ahmet Aydin for his time and support during the project and for letting me borrow the FPGA
development board.
• Sam Beardsmore-Rust for general support and help with project proposal.
• Philip Watson for 100-pin connector design files and other help.
• Martin Nock for help with PCB manufacture.
• David Smith, from the mechanical workshop, for his excellent work on a plastic case for my
adaptor board.
Table of Contents

1 INTRODUCTION 9
1.1 About this report..............................................................................................................9
1.2 Project aims and plan.......................................................................................................9

2 BACKGROUND 9
2.1 Field-Programmable Gate Arrays....................................................................................9
Xilinx versus Altera..........................................................................................................................9
2.2 Hardware description languages...................................................................................10
VHDL...............................................................................................................................................10
Digital systems theory..............................................................................................................10
Other HDLs.....................................................................................................................................10
2.3 Development board........................................................................................................10
2.4 VGA...................................................................................................................................11
Hardware........................................................................................................................................11
Timing.............................................................................................................................................11
2.5 Nintendo controllers......................................................................................................12
2.6 Principles of game implementation..............................................................................12
Logic blocks....................................................................................................................................12
Objects............................................................................................................................................12

3 IMPLEMENTATION 13
3.1 VGA...................................................................................................................................13
Code................................................................................................................................................13
Results............................................................................................................................................13
3.2 NES controller interface.................................................................................................14
Code................................................................................................................................................14
Results............................................................................................................................................14
3.3 Graphics...........................................................................................................................14
Storing images...............................................................................................................................15
Getting the pixels...........................................................................................................................15
Moving images...............................................................................................................................16
Colour image storage....................................................................................................................16
3.4 Text generation...............................................................................................................17
Font.................................................................................................................................................17
Grid.................................................................................................................................................17
3.5 Binary to BCD conversion...............................................................................................17
Theory.............................................................................................................................................17
VHDL implementation...................................................................................................................18
3.6 Sound...............................................................................................................................18
Frequency generator.....................................................................................................................18
Sound ROM....................................................................................................................................18
Player..............................................................................................................................................18

4 PONG 19
4.1 Structure..........................................................................................................................19
4.2 Graphics...........................................................................................................................19
Main logic.......................................................................................................................................19
Paddle logic....................................................................................................................................20
Ball logic.........................................................................................................................................20
Scores.............................................................................................................................................20
4.3 Sounds & User input.......................................................................................................21
Sounds............................................................................................................................................21
User input.......................................................................................................................................21

5 SPACE SHOOTER 21
5.1 Gameplay.........................................................................................................................21
5.2 Graphics...........................................................................................................................22
Main logic.......................................................................................................................................22
Aliens..............................................................................................................................................22
Spaceship and missile...................................................................................................................22
Explosion logic...............................................................................................................................22
Score and level display..................................................................................................................23

6 COMPLETING THE PROJECT 23


6.1 Game selection menu.....................................................................................................23
6.2 Combining the applications...........................................................................................23

7 ADAPTOR BOARD 23
7.1 Reverse engineering the controllers.............................................................................23
7.2 TTL / CMOS level conversion..........................................................................................24
FPGA to Shift register.....................................................................................................................24
Shift register to FPGA.....................................................................................................................24
7.3 Board design....................................................................................................................24
Schematic capture.........................................................................................................................24
PCB layout design..........................................................................................................................24
Manufacture...................................................................................................................................24

8 DISCUSSION 25
8.1 Issues...............................................................................................................................25
Pong ball acceleration...................................................................................................................25
Synchronisation problems............................................................................................................25
Adaptor board................................................................................................................................26
Binary-to-BCD conversion.............................................................................................................26
8.2 Further work...................................................................................................................26

9 CONCLUSION 26

REFERENCES 27

BIBLIOGRAPHY 27

APPENDIX A 28
Initial technical proposal....................................................................................................28

APPENDIX B 29
Project parts list...................................................................................................................29

APPENDIX C 30
Project plan..........................................................................................................................30

APPENDIX D 31
NES Controller: equivalent schematic diagram................................................................31

APPENDIX E 32
Python script for generating VHDL ROM from images.....................................................32

APPENDIX F 33
Adaptor board schematic diagram.....................................................................................33

APPENDIX G 34
Adaptor board PCB: top and bottom layer masks.............................................................34

APPENDIX H 35
Photographs.........................................................................................................................35
FPGA BASED VGA DRIVER
AND ARCADE GAME
and     milestones   was   created   to   give   a   rough 
1 INTRODUCTION estimate of duration of each part of the project.

1.1 About this report 2 BACKGROUND


This   report   covers   the   work   done   during   the 
course   of   the   project.   An   introduction   to   core  2.1 Field-Programmable Gate Arrays
concepts relating to the project is given in Chapter 
FPGAs   are   modern   programmable   logic   devices 
2  section.   Chapter  3  describes   how   the   main 
that   can   be   configured   to   perform   any   logic 
building   blocks,   used   to   create   a   game,   were 
operation.
developed,   while   Chapters  4,  5  and  6  go   into 
game­specific details. Design of an adaptor board,  An   FPGA   typically   contains   a   matrix   of 
connecting game pads to the development board,  programmable   elements,   also   known   as, 
is   described   in   Chapter  7.   Report   is   finished   by  Configurable   Logic   Blocks   (CLBs).   CLBs   contain 
discussing some of the issues experienced during  Look­Up Tables (LUTs), that can be used as logic 
the project, and Conclusion. or   storage   elements.   The   configuration   data   is 
stored in the memory.
Throughout   the   report,   you   will   see   notes   like 
this: Spartan­3E   series   FPGAs,   used   in   this   project 
contain  the   following  structures,   as  described   in 
[1]:
Project - filename.vhd
• Configurable   Logic   Block  –   logic   and 
It is a pointer to a relative source file. It may be  basic   storage   elements   are   implemented 
helpful,   if   one   needs   to   see   the   implementation  using the Look­UP Tables (LUTs).
details.
• Input/Output Block (IOB)  – control the 
The   report   is   accompanied   by   a   printed   VHDL  data   flow   between   the   I/O   pins   and 
code listing and a Compact Disc. The CD contains  internal   logic   of   the   device.   LVTTL   and 
all   the   relevant   material   in   digital   format,  LVCMOS     logic   standards   are   supported 
including this report, VHDL code, scanned version  among others.
of engineering logbook and more.
• Block   RAM  –   memory   used   for   data 
storage.   Organized   as   18kb   dual­port 
1.2 Project aims and plan blocks.
The   aim   of   this   project   was   to   explore   the  • Digital  clock   manager   block  –  provides 
capabilities   of   modern   programmable   logic  management for clock signals.
devices   while   getting   hands­on   experience   of 
FPGA development.
Xilinx versus Altera
The above definition is rather abstract and can be 
There   are   two   major   manufacturers   in   the 
hard   to   assess.   For   this   purpose,   a   number   of 
programmable logic business – Xilinx and Altera. 
objectives were set. The initial technical proposal 
Xilinx is a current market share leader, with Altera 
can   be   found   in  Appendix   A.   Below,   is   the 
being a close second.
amended list of objectives.
The decision which one to choose should not be 
• Learn   about   FPGAs,   development   tools 
based on the architectural differences of the two 
and VHDL, start programming.
technologies.   There   are   many   more   important 
• Produce a simple application, that uses a  aspects, such as device availability, overall price, 
VGA   driver   to   display   graphics   on   a  development   tools,   existence   of   Intellectual 
computer monitor. Property (IP) cores and educational material and 
so forth.
• Create a simple game.
Xilinx   Spartan­3E   development   boards   were 
• Create a more advanced game. readily available at the university and, therefore, 
• Design some hardware. Xilinx   technology   was   used   for   this   project's 
implementation.
A  plan,  available  in  Appendix  B,  with  objectives 

9
FPGA BASED VGA DRIVER
AND ARCADE GAME
2.2 Hardware description languages Other HDLs
As   with   the   FPGAs,   there   are   two   predominant 
VHDL hardware   description   languages   –   VHDL   and 
Verilog.
“VHDL   is   a   language   for   describing   digital 
electronic   systems.   It   arose   out   of   the   United  And  just  like  with   FPGAs,  HDL  usage  is  more  a 
States   government's   Very   High   Speed   Integrated  matter of preference. Capabilities are pretty much 
Circuit   (VHSIC)   program.   In   the   course   of   this  equal. The difference lies in how the hardware is 
program, it became clear that there was a need for  described.   Verilog   is   somewhat   similar   to   C 
a  standard  language for describing the  structure  programming   language,   whereas   VHDL   is   based 
and   function   of   Integrated   Circuits   (ICs).   Hence  on Ada.
the   VHSIC   Hardware   Description   Language  According to Wakerly  [3], it is best to “learn one 
(VHDL) was developed” (Ashenden, 1996) [2]. well and, only if necessary, tackle the other later”.
VHDL became an IEEE standard in 1987. Several 
revisions have been done since then.
2.3 Development board
VHDL   can   be   used   not   only   to   describe   digital 
hardware   but   also   to   create   test   benches   for 
testing the designs.
VHDL   supports   many   built­in   and   user­defined 
data types. Some of most often used are
• std_logic (single bit)
• std_logic_vector (bit vector)
• numerical types such as integer
• arrays, enumerated lists, etc.
Unlike   imperative   programming   languages,   such 
as C++, VHDL statements are concurrent (i.e. run 
in parallel). Concurrency is very useful in HDLs, as 
it resembles the way hardware works. Sequential 
statements   can   be   implemented   using   a   special  FIGURE 2.1: SPARTAN-3E BOARD
construct called process.
The   development   board   used   in   this   project   is 
Every   VHDL   design   must   have   an  entity  and   an  shown in Figure  2.1. It uses a Spartan­3E series 
architecture. The  Entity  contains a declaration of  FPGA   (model   XC3S500E)   with   the   following 
I/O ports while the actual design code resides in  characteristics [1]:
the architecture part.
• 500,000   system   gates,   making   over   ten 
Signals   declared   in   the  entity  are   referred   to   as  thousand equivalent logic cells.
external and are usually tied to I/O pins on the 
FPGA. The mapping of signals to pins is done in  • 20 RAM blocks totalling 360kb of memory.
the User Constraints File (UCF).
• 20 dedicated multipliers.
Internal   signals   are   declared   in   the   architecture 
• A maximum of 232 I/O pins.
body   and   cannot   be   connected   to   the   outside 
world. The board has a 15­pin D­subminiature connector 
to plug in a VGA monitor.
Digital systems theory Also, an on­board 100­pin expansion port is used 
to connect an adaptor board. Full list of features 
VHDL is a good example of practical application of 
can be found in the user guide [4].
digital circuit theory. Many of the basic concepts, 
such   as   gate   and   register­transfer   level   design, 
combinational logic and finite state machines have 
been used throughout the project.

10
FPGA BASED VGA DRIVER
AND ARCADE GAME
2.4 VGA

Hardware
VGA is an analogue video standard, that is mostly 
used in personal computers. VGA can also refer to 
a   piece   of   display   hardware   developed   by   IBM 
(Video   Graphics   Array)   or   a   display   mode,   that 
uses 640 x 480 pixels resolution.
VGA connector uses a total of 15 pins, but only 5 
signals are needed for operation:
• HSYNC   –   horizontal   synchronization 
signal. This signal controls the horizontal 
position of the active pixel FIGURE 2.2: PARTS OF A SCREEN
• VSYNC   –   vertical   synchronization   signal.  Figure  2.2  shows   parts   that   are   required   for   an 
This signal controls vertical position of the  operation of a standard monitor.
active   pixel.   VSYNC   rate   can   also   be 
referred to as a refresh rate (i.e. number  Visible part  of the screen is  shown as  the  white 
of times per second the screen is redrawn) area. It has a resolution of 640 by 480 pixels.

• RED – red colour channel The   black   and   grey   borders   denote   parts   of  the 
screen   that   are   not   visible,   but   required   for 
• GREEN – green colour channel synchronization. With these parts, the total width 
• BLUE – blue colour channel of the screen is 800 pixels, and the total height is 
524 pixels. Below is the short description of each 
Other pins include ground, return paths and I2C  part   of   the   screen,   followed   by   a   table   of 
clock/data or are reserved [5]. dimensions.
HSYNC and VSYNC are TTL signals, so logic one is  Active video. This is the visible part of the screen, 
represented by 5V and logic zero is represented by  video output is enabled.
0V [5].
Front porch.  When the trace reaches the end of 
RED, GREEN and BLUE signals are analogue. The  the visible part of the screen, the video output is 
maximum   voltage   that   can   be   used   is   0.7V   and  disabled. These areas are denoted as VPF (Vertical 
will result in full intensity of that colour [5]. Front Porch) and HPF (Horizontal Front Porch) in 
Xilinx   Spartan­3E   board   is   only   capable   of  Figure 2.2.
producing   eight   colours   (3­bits)   as   a   digital­to­ Sync pulse. In case of HSYNC, the trace goes back 
analogue converter (DAC) is not used. The board  to column zero. If pulse is VSYNC, the trace goes 
uses   270Ω   resistors,   which   form   a   potential   back to row zero. This part is also known as the 
divider   with   internal   75Ω   termination.   This   retrace period.
divider   scales   the   3.3V   signal   from   FPGA   to 
required 0.7V [4]. Back porch.  This is the part that goes before the 
active   video   starts.   These   areas   are   denoted   as 
VBF  (Vertical   Back   Porch)   and  HBF  (Horizontal 
Timing Back Porch) in Figure 2.2.
Pixels on the screen are drawn in sequence, one  Table  2.4.1  lists the dimensions for each part of 
by   one.   Rows   are   arranged   top   to   bottom,   and  the   screen.   These   numbers   are   only   valid   for 
columns   go   from   left   to   right.   The   row   and  resolution of 640 x 480 and refresh rate of 60Hz. 
column addresses are constantly incremented thus  Other modes are described in the source [6].
changing   the   position   of   currently   drawn   pixel. 
Synchronisation   signals   are   used   to   tell   the 
monitor to return the pixel back to the first row 
(VSYNC) or the first column (HSYNC).
Sequence   and   duration   of   these   signals   are 
discussed below.

11
FPGA BASED VGA DRIVER
AND ARCADE GAME
detail in Chapter 7.
TABLE 2.4.1: VGA TIMINGS
An equivalent schematic diagram of the controller 
25MHz pixel Active Front Sync Back is shown in Appendix D.
clock video porch pulse porch

Horizontal 640 16 96 48 2.6 Principles of game


implementation
Vertical 480 11 2 31
Logic blocks
2.5 Nintendo controllers
The classic  Nintendo Entertainment System  (NES) 
controller   became   a   cultural   icon   among   arcade 
game lovers and geeks. It therefore, seemed like a 
good   idea   to   use   these   controllers   as   an   input 
device.
The   controllers   use   an   8­bit   static   shift   register 
(4021B) to transmit user input as an 8­bit serial 
data. There are eight buttons on the gamepad, so 
each   button   has   its   own   bit.   Buttons   and   their 
corresponding   values   are   listed   in   Table  2.5.1 
below.
FIGURE 2.3: GAME LOGIC HIERARCHY
TABLE 2.5.1: GAMEPAD OUTPUTS
To make the code more manageable, it is a good 
Button Value idea   to   separate   the   source   into   logic   blocks. 
Figure  2.3  shows one possible configuration of a 
None 11111111
game project.
A 01111111 At the very top of the hierarchy, is the Main block. 
Major   logic  parts   are  instantiated   in  this   circuit. 
B 10111111 Signals shared  between VGA, Sound, User Input 
and Graphics circuits all go through the main logic 
SELECT 11011111
block.
START 11101111 VGA synchronization  logic provides information 
about the pixel which is currently being drawn on 
UP 11110111 the screen. It also outputs synchronization signals 
to the VGA port.
DOWN 11111011
Sound  circuit   provides   acoustic   feedback   to   the 
LEFT 11111101 user. This logic depends on signals provided by the 
graphics generation circuit.
RIGHT 11111110
User input  logic is responsible for logging input 
events   and   providing   the   graphics   logic   with 
Note   that   the   signal   is   active­low.   When   two  appropriate control signals.
buttons are pressed at the same time, two bits will  At   the   bottom   of   the   hierarchy,   we   have   the 
be set to zero. graphic objects. They take pixel coordinates and 
It is worth mentioning that the controllers and the  control   signals   and,   based   on   that   information, 
development board  cannot communicate directly  generate RGB pixel values.
with   each   other   due   to   different   voltage   levels  Finally,  graphics   generation   circuit,  in   the 
used.   The   FPGA   can   only   go   up   to   3.3V   (Low­ middle of the diagram, can be thought of as a hub 
Voltage TTL or CMOS), while the controllers need  connecting   all   the   objects.   It   passes   pixel 
5V.   For   this   purpose,   an   adaptor   board   was  coordinates received from the VGA circuit, routes 
designed   and   built.   This   is   discussed   in   greater  the   data,   sends   control   signals   and   enables   or 

12
FPGA BASED VGA DRIVER
AND ARCADE GAME
disables the objects. are   checked   against   the   predefined   constants. 
SYNC signals are produced during the sync stage 
(i.e. between the front porch and back porch).
Objects
The   statement,   therefore,   can   be   described   in 
In the game, each graphic element is treated as an 
pseudo­code like this:
object.   The   object   has   a   source   of   pixel   values, 
position   coordinates,   dimensions,   logic   and   so  sync_pulse = 1 when
forth. counter >= (display_area +
front_porch)
The idea here is to provide another layer of logic  and
separation.   Each   object   is   responsible   for   its  counter < (display_area +
graphical   appearance,   position   on   the   screen,  front_porch +
movement etc. sync_pulse)
A ball in the game of Pong, is an example of an  Note   that   separate   sync   signals   are   used   for 
object. The graphical representation of the ball is  vertical   and   horizontal   synchronisation.   The 
stored in the ROM, the object knows its current  corresponding   VHDL   code   can   be   found   in   the 
location, and can update its coordinates to move  vga_sync.vhd, lines 95 to 100.
or bounce of the wall.
The   circuit   also   outputs  x  and  y  coordinates, 
Object generates a pixel value, which is used by  named  px_x  and  px_y,   respectively.   These 
graphics generation circuit to display the object on  coordinates are provided as 10­bit vectors.
the screen. The value of the pixel is deduced from 
screen pixel coordinate. More on this in Chapter 
3.3. Results
To   get   a   visual   representation   of   the   generated 
3 IMPLEMENTATION synchronization   signals,   the   outputs   were 
measured with an oscilloscope.
Channel 1 (top) in Figure  3.1  shows the HSYNC 
3.1 VGA
trace. The frequency needed to traverse 524 lines 
in 1/60th of a second is about 31kHz.
Code
The VSYNC signal is shown as channel 2.

vga_sync.vhd

The VHDL code for driving a VGA monitor is taken 
from FPGA prototyping by VHDL examples, by Pong 
P. Chu [7]. 
It is one of the simplest parts in the project and, in 
this case, there is not much to gain from writing a 
custom   implementation.   This   section   will   briefly 
explain the operation of the VGA controller logic. 
Comments   in   the   code   provide   more   detailed 
explanation.
Three   major   components   are   needed   for   the 
driver: a 25MHz clock, counters (for the vertical 
and   horizontal   pixel   coordinates)   and   constants  FIGURE 3.1: VGA SIGNALS
representing   the   timing   values   listed   in   Table  Figure  3.2  shows   a   zoomed­out   version   of   the 
2.4.1. VSYNC trace. The HSYNC signal is left out, since 
The horizontal and vertical counters count to 799  no   detail   can   be   seen   due   to   much   higher 
and 523 respectively. These counters are updated  frequency. Note the frequency of around 60Hz.
at the speed  of the pixel clock – 25MHz in  this 
case.
During operation, the values in the two counters 

13
FPGA BASED VGA DRIVER
AND ARCADE GAME

FIGURE 3.3: CONTROLLER INTERFACE TIMING


DIAGRAM

The latch (ps_counter in the image) value is also 
FIGURE 3.2: VSYNC SIGNAL used to assign the received value to the right bit in 
the data byte.

3.2 NES controller interface When all bits have been received, the data is made 


available as an 8­bit logic vector.

Code
Results
Figure  3.4  shows the waveforms captured by an 
controller.vhd
oscilloscope. Channel 1 shows CLK and channel 2 
shows latch signal.
The   purpose   of   the   driver   is   to   provide   control 
signals   for   game   pads,   as   well   as   read   the   data 
from them.
Controllers need external clock and latch signals. 
The   clock   frequency   should   not,   under   normal 
conditions, exceed 1.5MHz [8].
The latch signal must be eight times slower than 
the CLK in order to get all eight bits shifted out. 
When this signal is high,  parallel data  is  loaded 
into the registers, when it is low, bits are shifted 
out.
Latch signal frequency was chosen to be 100Hz. 
This  type of application  does  not  require  a  very 
fast   sample   rate,   so   100   samples   per   second 
seemed   reasonable.   Clock   signal,   therefore,  FIGURE 3.4: CLK AND P/S SIGNALS
needed to be 800Hz. This is much lower than the  Note the frequencies of 800Hz and 100Hz.
maximum given in the datasheet.
The   output   signals   are   inverted   to   match   the 
The  CLK   and   latch   signals  are   derived   from  the  operation   of   the   adaptor   board   (described   in 
master counter, which is running at four times the  Chapter 7).
CLK   speed   (3.2kHz).   This   is   done   so   that   the 
sampling   point   can   be   chosen   with   greater 
accuracy. 3.3 Graphics
Figure 3.3 shows a part of simulated operation of  Section  Principles   of   game   implementation  in 
the interface. Three vertical lines show the points  Chapter  2,   gave   a   brief   introduction   into   the 
at which data is sampled (master counter value is  structure of a game. This chapter takes a deeper 
changing   from   zero   to   one).   This   point   was  look into objects and graphics generation.
chosen, as it is in the middle of high state of CLK 
signal   (shown   as   clk_out   in   the   image)   and, 
therefore, the voltages are stable.

14
FPGA BASED VGA DRIVER
AND ARCADE GAME
Storing images
The   graphics   generation   circuit   gets   a   pixel 
coordinate   from   the   VGA   driver.   Based   on   that 
coordinate,   it   generates   a   colour   value   for   that 
pixel and outputs it to the RGB port.
For more complex graphics, an image for example, 
pixel   values   have   to   be   stored   in   memory.   One 
simple   way   of   doing   this,   is   to   use   the   internal 
block RAM.
For   storage   of   a   simple   monochrome   image,   a 
two­dimensional   array   is   sufficient.   Array   rows 
represent image rows, and array indices represent 
individual   pixels.   In   VHDL,   this   array   can   be  FIGURE 3.5: BALL IMAGE
described as follows:
The size of the example image is 16 x 16 pixels, 
type rom_type is array(0 to 1) of therefore, we need the address to be 4­bits wide in 
std_logic_vector(0 to 3); order to be able to access each row and column.
constant SQUARES: rom_type := The first pixel with coordinate (0, 0) is located at 
( the   top­left   corner.   Likewise,   the   last   pixel   is 
"1010", located at the bottom­right corner.
"0101"
); To begin with, we need to define the boundaries 
of the image. In our case, it is 16x16 square:
This array defines a four­by­two pixel image like 
this:   ▚▚.   Note   that  one  denotes   the   foreground  rgb <= img_data when px_x < 16 and
(black) and zero denotes the background (white). px_y < 16 else
"111";
Even though, a 3­bit RGB scheme is used, we only 
need a single bit to describe monochrome images  So  when  the  pixel  coordinates  are less  than  16, 
(same   bit   is   used   for   Red,   Green   and   Blue  image   data   is   sent   to   RGB   output.   Otherwise, 
channels). white colour is used as a background.
For   simple   cases,   the   synthesizer   will   infer   a  Now we need to set the image data. To do this, we 
correct type of RAM based on the structure of the  need   to   derive   the   row   and   column   addresses. 
code. No special code to define RAM options was  Because   the   screen   pixel   coordinates   correspond 
used in this project. directly   to   the   image   pixel   coordinates,   it   is 
sufficient   to   just   take   four   least   significant   bits 
(LSBs)   of   the   pixel   coordinates   provided   by   the 
Getting the pixels
VGA driver.
Row   and   pixel   addresses   are   derived   from   pixel 
row_addr <= px_y(3 downto 0);
coordinates. Lets do a simple task of displaying an 
col_addr <= px_x(3 downto 0);
image on the screen.
pixel <= pixel_data(col_addr);
Figure  3.5  below shows ball graphics used in the 
Pong game. We want this image to appear in the  img_data <= "000" when pixel = '1'
top­left corner of the screen. else "111";

The ROM instance (not shown here) automatically 
takes the row address and outputs the appropriate 
row as a  pixel_data  vector. The active pixel is 
then retrieved from this vector.
Lastly,   single   bit   is   converted   to   three   bits   for 
output at the RGB port.

To keep the example as simple as possible, ROM  
instantiation and data type conversions are not  

15
FPGA BASED VGA DRIVER
AND ARCADE GAME

shown here. Reader should refer to code listing   coordinates are updated in a continuous manner, 
for full details. See the next section for a pointer. a motion will be created.

Colour image storage


Moving images
In  order   to  be  able   to   move  images  around   the  FPGalaxy - alien_1_1_rom.vhd
screen,   we   need   to   have   vectors   defining   the 
position   of  an   object.   These   will   usually   store  x  A different approach is needed to implement the 
and   y   coordinates   of   the   top­left   corner   of   that  storage   of   colour   images.   Since   there   are   now 
image. three bits per pixel, array structure used before is 
When the object is offset, we need a way to relate  not suitable.
screen pixel coordinate to image pixel position. In  The first challenge is: how to define a 3D array in 
Figure  3.6, we can see   that, for example, when  VHDL?   Readers,   with   experience   in   lower­level 
screen pixel is at (3, 3), corresponding image pixel  programming, may know the answer already – an 
is (0, 0). array of arrays!
To begin with, we define a two­dimensional array 
type as before, and call it rgb_array:
type rgb_array is array(0 to 3) of
std_logic_vector(2 downto 0);

This   type   will   be   used   to   describe   rows   of   an 


image. There will be 4 pixels per row, and each 
pixel will be defined by 3­bit vector.
In the next step, we want to combine these row 
arrays to make an image. Structure definition  is 
quite similar, but we use the type defined above 
instead of std_logic_vector:
type rom_type is array(0 to 1) of
FIGURE 3.6: IMAGE ADDRESSING rgb_array;

The   correct   image   pixel   address   is   produced   by  Next, a constant with the pixel data is defined:


simply subtracting the top coordinate of the ball  constant SQUARES_2: rom_type :=
from the current position of the screen pixel. (
("000", "001", "010", "011"),
("100", "101", "110", "111")
Plong – graphics.vhd, line 360
);

row_addr <= px_y(3 downto 0) - This image will show all eight colours that can be 


ball_top_y(3 downto 0); generated using 3­bit colour space.
col_addr <= px_x(3 downto 0) - Lastly, some updates to addressing are needed. In 
ball_top_x(3 downto 0); the   monochrome   image   example,   a   whole   row 
was made available at the output of the ROM. In 
The code that enables the ball has to be updated 
the colour mode, the row type is an array, so it is 
as well.
better to return a value of a single pixel instead.
rgb <= img_data when
For this purpose, two addresses (row and column) 
(px_x >= ball_top_x and
px_x < ball_top_x + BALL_SIZE and have to be provided to the ROM. These addresses 
px_y >= ball_top_y and are   joined   together,   so   that   externally   the   ROM 
px_y < ball_top_y + BALL_SIZE) else looks the same.
"111"; To access each row of the example image, a single 
Now whenever we change the top coordinate, the  bit is  sufficient. Likewise, two bits will cover all 
image will change its position on the screen. If the  four columns. These addresses add up to a 3­bit 

16
FPGA BASED VGA DRIVER
AND ARCADE GAME
wide vector, which can be used like this: As  the  font has been chosen and  the  code page 
generated, we can now talk about placing the text 
rgb_row <= SQUARES_2(addr(2));
on to the screen.
data <= rgb_row(addr(1 downto 0));
The easy way is to treat each letter as a tile. Our 
tiles   are   8x8   pixels   each,   which   means   that
3.4 Text generation 80   x   60   letter   matrix   can   fit   on   a   640   x   480 
Often­times, games need to convey some textual  resolution screen.
information to the user. This chapter will describe  Each   character   has   its   own   address   within   the 
the process of text generation in VGA applications. ROM. The address of the first symbol, a space, is 
0.   The   address   of   the   second   symbol,   an 
Font exclamation   mark,   is   8   and   so   on.     These 
addresses are used to define text.
codepage.vhd For   large   amounts   of   text,   a   ROM   storage   is 
appropriate, but a simple multiplexer is sufficient 
To begin with, a typeface has to be chosen. The  when only a few letters are needed.
font, used by the two games, was borrowed from  Addressing is very simple, provided the characters 
Uzebox   Project  [9]  as   it   resembles   the   typeface  are placed strictly on the grid:
used   by   many   old   arcade   games.   The   source 
image is shown in Figure 3.7. • To get a row address, we take the character 
address and add three lower bits of   px_y
(the screen pixel coordinate) to it.
• Three   lower   bits   of  px_x  will   select   the 
right   pixel   in   the   row   (i.e.   the  column  
address).
FIGURE 3.7: ARCADE TYPEFACE If   text   is   moving   or   otherwise   offset,   a   proper 
When   a   suitable   font   is   chosen,   it   has   to   be  subtraction is needed, as described in Chapter 3.3.
converted to a code page or, to say simply, a ROM. Also, an additional logic may be required to select 
The size of each symbol is 8 x 8 pixels, and there  the character address if ROM structure is used to 
are 64 symbols in total. This results in 512 rows  store the text.
and 8 columns, or 4k bits of data in a ROM.
Entering   this   information   by   hand   would   be  3.5 Binary to BCD conversion
tedious   and   time­consuming.   A   simple   Python  In order to display multi­digit numbers as a text, a 
script was written for this purpose and is provided  binary­to­BCD (Binary Coded Decimal) converter 
in Appendix E. is needed. This section will go through the theory 
The   ROM   is   no  different   from  that   described   in  and implementation of such converter.
Chapter  3.3.   This   is   how   letter   A   looks   after 
conversion. Theory
"00111000", -- ### Binary numbers can be converted to BCD using a 
"01101100", -- ## ## “Shift   and   add   3”   algorithm,   described   in   page 
"11000110", -- ## ## 147 of source [7].
"11000110", -- ## ##
"11111110", -- ####### 1. Bits are shifted to the left, so that the most 
"11000110", -- ## ## significant bit (MSB) of a binary number 
"11000110", -- ## ## becomes the least significant bit (LSB) of 
"00000000", -- BCD0 digit, then the MSB of BCD0 digit 
becomes the LSB of BCD1 digit and so on.
Grid 2. After   each   shift,   all   BCD   registers   are 
checked; if value in the register is greater 
than four, three is added to that register.
Arcade - menu.vhd
3. Go to 1 until all bits have been shifted.

17
FPGA BASED VGA DRIVER
AND ARCADE GAME
VHDL implementation volume input.
The output can be switched on or off by setting 
FPGalaxy - bin2bcd.vhd the enable signal.

The   conversion   is   controlled   by   a   Finite   State  Sound ROM


Machine   with   Datapath   (FSMD).   It   has   three 
states: start, shift and done. In order to create more complex sounds, a variety 
of   frequencies,   amplitudes   and   durations   is 
needed. A ROM is used to store all this data.
If you are unfamiliar with digital circuit theory,  
think of FSM as a flowchart. See Figure 3.8 for   To keep things simple, a  representation of data  is 
an example. stored,   rather   than   the   actual   data.   The   ROM 
contains a number of 9­bit vectors, which are later 
Start  state   clears   all   the   registers   and   the   shift  mapped  to actual values.
counter and preloads a new binary number. Pitch, volume and duration are each allocated 3 
Shift state checks the number of bits shifted, if all  bits, resulting in 7 different values (zeros are used 
the bits have been shifted, the state is changed to  for termination).
done,   otherwise,   shift   operation   is   performed 
again.   Addition   is   done   using   concurrent  Player
statements outside of the FSMD.
Done  state   does   not   do   anything   explicitly.   It,  player.vhd
however, gives the output logic a signal that the 
conversion has been completed and the BCD digits  A  high­level  logic,  which  takes   data   from   sound 
can be made available at the output. ROM,   transforms   it   and   feeds   the   result   to   the 
frequency generator, is called a player.
3.6 Sound The   FSMD,   shown   in   Figure  3.8,   is   the   main 
To   make   the   games   more   complete,   an   audio  control structure of the player logic.
feedback   function   was   added.   The   sound   is  This FSMD has two states – Off and Playing. When 
produced   by   a   piezoelectric   transducer   which   is  start  signal   is   set,   the   FSMD   state   changes   to 
driven directly by the FPGA. Playing.
The generation logic is divided in to three parts: The  Playing  state serves two purposes: it checks 
• Frequency generator for the end of the tune and also sets the address of 
the next note (datapath).
• Sound ROM
• Player

Frequency generator

sounds.vhd

The frequency generator is a low­level logic, that 
creates   a   square   wave.   It   can   produce   different 
frequencies   and   duty   cycles   depending   on   the 
parameter values provided.
An internal counter is running at 50MHz. When  FIGURE 3.8: SOUND CONTROL FSMD
the value of the counter matches the value of the 
period input, the counter will reset. Output (enable signal) only depends on the state, 
and can be said to use the Moore model.
The   duty   cycle   determines   how   long   the   output 
stays high during the period. The pulse width can  en <= '1' when state = playing else
be  set as  a fraction of the  period  by setting the  '0';

18
FPGA BASED VGA DRIVER
AND ARCADE GAME
Table  3.6.1  summarises operation of multiplexers  Figure  4.1  shows   the   file   structure   of   the   Pong 
used to transform the data from the sound ROM  game. The structure follows the pattern described 
to appropriate values. The Bits column represents  in Chapter 2.6, but the objects (ball and paddles) 
the   data   in   the   ROM,   other   columns   show   the  are   not   separated   from   the   main   graphics   logic. 
corresponding output from the multiplexer. This resulted in a large all­in­one file.

TABLE 3.6.1
4.2 Graphics
Bits Frequency Duration Duty cycle
Main logic
000 N/A

001 110 Hz 1/64 s 50 % Plong - graphics.vhd

010 220 Hz 1/32 s 25 % The main graphics generation logic consists of two 


noteworthy   parts:   a   game   control   FSMD   and   a 
011 440 Hz 1/16 s 12.5 % pixel routing logic.
100 880 Hz 1/8 s 6.25 % The   pixel   routing   is   done   with   a   conditional 
sentence.   It   basically   defines   object   priorities, 
101 1760 Hz 1/4 s 3.12 % when   two   or   more   objects   are   at   the   same 
location.   For   example:   the   ball   will   go   over   the 
110 3520 Hz 1/2 s 1.56 % middle line and the score text, but will go under a 
paddle   in   case   of   the   player   missing   the   ball. 
111 7040 Hz 1s 0.78 %
Background has the lowest priority.
The   control   FSMD   is   shown   in   Figure  4.2.   It   is 
The set of values is far from comprehensive, but is 
responsible   for   keeping   the   scores,   enabling   or 
sufficient for purposes of this project.
disabling motion of the ball and announcing the 
winner.
4 PONG

4.1 Structure
Development   of   the   Pong   game   was   a   learning 
exercise in its way. There was not much planning 
involved and the main goal was to get it working 
and to grasp the basics game development.

FIGURE 4.2: PONG ASMD CHART

Start  state  is used to reset the scores before the 


game begins.
Waiting  state   disables   movement   of   the   ball, 
changes state to  game over, if one of the players 
has   reached   the   seven­point   limit,   or   waits   for 
user input otherwise.
FIGURE 4.1: PONG GAME FILE STRUCTURE Playing  state  enables  the   ball.   When  the   ball   is 
missed,   score   count   is   updated   and   the   state 

19
FPGA BASED VGA DRIVER
AND ARCADE GAME
changes to waiting.
Winner   is   announced   when   the   FSMD   state 
changes to Game over.

Paddle logic
This Pong implementation is a two­player game, 
so   two   paddles   are   needed.   Dimensions   and 
graphics are the same for both bars, but they have 
separate position coordinates.
Since the two paddles cannot appear in the same 
location,   it   was   possible   to   use   shared   enable, 
ROM address, data and pixel signals.
FIGURE 4.3: CHANGES IN TRAJECTORY
Paddle control logic is fairly simple – it responds 
to user input by increasing or decreasing the top  The   part   a)   of   Figure  4.3  shows   the   ball   going 
coordinate of each bar. When a paddle is at the  down and to the right. When the ball bounces, it 
top or bottom, no further movement is allowed in  starts going up and to the right. The bold arrow 
that direction. denotes the direction that does not change after 
the bounce.

Ball logic Likewise, in the part b) the constant direction is 


downward, and  the horizontal  direction changes 
Ball logic is probably the most complex part of the  from right to left.
game.   One   has   to   keep   track   of   ball   position, 
increase the velocity, enable or disable the motion  Using   this   principle,   it   is   easy   to   implement   a 
and so forth. vertical direction control:

One of the most important features of the game is  if ball_y = 0 then


increasing the velocity of the ball. This allows a  ball_v_dir_next <= '1';
player   to   get   used   to   controlling   paddles   and  elsif ball_y = SCREEN_HEIGHT -
ensures   that   the   game   will   come   to   an   end   at  BALL_SIZE then
ball_v_dir_next <= '0';
some point.
end if;
The   acceleration   of   the   ball   is   controlled   by   a 
counter.   The  counter  counts   to  some   value,  and  A   horizontal   direction   control   requires   checking 
when it resets, the ball position will be updated.  whether   a   paddle   is   in  a  right   position,   but  the 
By   reducing   the   value   of   the   counter   limit,   ball  principle stays the same.
velocity can be increased. The position is updated according to the direction 
The   counter   limit   is   updated   after   a   certain  of the ball and is done like this:
number of bounces from a paddle. There are only  if ball_h_dir = '1' then
four levels of velocity, but it proved to be sufficient  ball_x_next <= ball_x + 1;
to   make   players   concentrate   more   at   greater  else
speeds. ball_x_next <= ball_x - 1;
end if;
One issue with this acceleration approach is that 
sometimes   the   ball   coordinate   is   updated   more  if ball_v_dir = '1' then
often than the screen itself. This results in small  ball_y_next <= ball_y + 1;
distortion of the ball (see Chapter 8), but is hardly  else
ball_y_next <= ball_y - 1;
noticeable during the game.
end if;
A separate process is dedicated to controlling the 
direction   of   the   ball.   Figure  4.3  illustrates   the  As   you   can   see,   the  x  and  y  coordinates   are 
principles of ball movement. updated independently.

Scores
The   pong   game   uses   a   text   generation   logic, 

20
FPGA BASED VGA DRIVER
AND ARCADE GAME
described in Chapter  3.4, to render points and a 
game­over message.
The   score   font   address   is   acquired   using   this 
formula:
addr = 128 + (score_value * 8)
Offset of 128 is needed because numbers start at 
this address in the memory. Multiplication by 8 is 
used to get the right digit (characters are 8 x 8 
pixels in size).
The score value was deliberately limited to 7 for 
two reasons:
1. Simple   implementation,   no   need   for   a 
binary­to­BCD converter.
2. Duration of a match is well balanced.

4.3 Sounds & User input FIGURE 5.1: FPGALAXY FILE STRUCTURE

While being more more complex, the game is less 
Sounds complicated.   More   work   has   been   done   on   the 
design side – the file structure was improved, each 
Two types of sounds are used in this Pong game. A  object is logically separated from all other objects. 
short,   high   pitch   sound   is   played   when   a   ball  In fact, it would be possible to take the code that 
bounces, and a longer, low pitch sound is played  generates   a   spaceship,   and   put   it   into   the   Pong 
when the ball is missed. game with a minimum effort.
Initially, only the square wave generator was used  Figure  5.1  shows the improved file structure. As 
to   make   these   sounds,   so   only   single   frequency  can be seen, graphics generation circuit now has 
was   used.   The   tones   remained   after   the   sound  many  child  files (objects). To conserve the space, 
logic was updated. files belonging to objects (e.g. ROM files) are not 
shown in the figure. Full file tree can be found in 
User input the source code listing.
Initially, four on­board tactile switches were used 
to control the movement of paddles. At the end of  5.1 Gameplay
the project development, the  game was updated 
The   point   of   the   game   is   to   destroy   the   alien 
to make use of the Nintendo controllers.
invaders. A player controls a spaceship located at 
There are three buttons, that the game uses: UP,  the bottom of the screen; it can more sideways, 
DOWN and START. The purpose of these buttons  but not up or down. The spaceship is able to shoot 
should be obvious. one missile at a time. When the missile hits the 
target or leaves the screen, the player can shoot 
Since  the  functionality   is   very  basic,   there   is  no 
another one.
need for switch debouncing logic.
The   aliens   are   located   at   the   top   of   the   screen. 
There are three rows, with eight aliens in a row. 
5 SPACE SHOOTER Level 1 aliens hover in front (bottom row), they 
The second game, a space shooter, was developed  are weak and need only one hit to be destroyed. 
as a complement to the Pong game. Level   2   aliens   reside   in   the   middle,   they   are 
stronger than Level 1, and need two shots to get 
Space shooter is more complex than Pong – visual  killed. At the end, there are Level 3 aliens. It takes 
appeal improved  by use of colour and animated  three   hits   to   destroy   a   Level   3   alien.   Moreover, 
graphics,   enhanced   sound   logic   is   able   to   play  they can turn invisible and avoid being hit by a 
simple  tunes,   proper   game   pads   used   to  control  missile.
the game.
When   all   the  aliens   are  destroyed,   another   fleet 

21
FPGA BASED VGA DRIVER
AND ARCADE GAME
shows up and the game continues. FPGalaxy - alien_generator.vhd

5.2 Graphics Alien   generation   logic   constantly   checks   the 


missile coordinates. When the missile is within the 
The two major improvements over the first game  alien area, the logic checks which alien is being 
are use of colour (although limited to only 3 bits)  attacked   and  whether  that   alien  is   still  alive.  In 
and   object   animation.   Word   “animation”  here  case   of   destruction,   appropriate   signals   are 
means that the aliens are not only moving around  generated   for   use   by   other   logic   parts   (such   as 
the screen, but also change their shape. explosion   and   score   counter)   and   the   alien   is 
disabled. If alien was already destroyed, nothing 
Main logic happens and missile continues its journey.
An animation is created by changing the source of 
FPGalaxy - graphics.vhd the alien graphics. The duration of each frame is 
controlled by a counter.
As most of the logic has been moved to other files, 
graphics   generation   circuit   has   somewhat   less  Spaceship and missile
work to do than in the case of the Pong game. The 
logic is responsible for object control signals and 
interfacing with the VGA port. FPGalaxy - spaceship.vhd
FPGalaxy - missile.vhd
The   alien   position   coordinates   are   generated   in 
the main file. The individual alien generators use  The   spaceship   logic   is   very   simple.   Apart   from 
signals generated by a simple FSMD. pixel generation, it only has to react to user input 
The  score  and   level   information  is  also   updated  to move sideways and output its centre coordinate 
here.   Corresponding   logic   files   are   dedicated   to  for use by the missile generation circuit.
displaying that information on the screen. The missile generation logic also contains missile 
graphics (since the frame size is only 4 x 4 pixels).
Aliens When a launch button is pressed, the logic records 
All the graphics were originally designed for the  the position of the spaceship and uses that value 
purpose of this project. Figure 5.2 shows the levels  as its horizontal coordinate. Vertical coordinate is 
and states of the aliens. then   updated   at   a   certain   frequency,   which 
depends   on   the   internal   counter.   The   missile   is 
disabled   when   it   leaves   the   visible   part   of   the 
screen or destruction signal is generated.

Explosion logic

FIGURE 5.2: ALIEN GRAPHICS

The frame size was chosen to be 32 x 32 pixels. 
The   width   of   all   aliens   had   to   be   the   same,   in 
order to make it impossible to destroy higher level 
aliens first. There is enough room for a missile to 
fly between two aliens. FIGURE 5.3: COLOUR MASKING

These images were converted to ROM files for use  A more interesting design solution is implemented 
by an alien generator logic. The logic takes master  in the explosion generation logic. There is only a 
coordinate   and   generates   pixel   values   based   on  single frame in the ROM file and yet the explosion 
that and some other signals. is animated in the game.

22
FPGA BASED VGA DRIVER
AND ARCADE GAME

FPGalaxy - explosion.vhd Remember that pixel coordinates are stored in 10­


bit vectors px_x and px_y. If we ignored the least 
The explosion image uses three colours: red at the  significant   bit,   it   would   effectively   reduce   the 
centre,   yellow   in   the   middle   and   white   on   the  resolution by 50%, or in other words, double the 
outside. Top row in Figure  5.3  shows location of  pixel size!
red, yellow and white pixels. By masking certain  When   generating   the   title   text,   three   LSBs   are 
colours, three frames can be created, as shown in  discarded, making the pixel eight times as large.
the   bottom   row.   When   these   frames   are   shown 
one   after   another,   the   effect   of   animation   is 
created. 6.2 Combining the applications
The   animation   is   controlled   by   a   counter   and   a 
finite state machine. The pixel output depends on  Arcade - main.vhd
the state of that FSM.
The next step is to combine all three applications 
together.   Menu   is   the   default   one,   and   its   RGB 
Score and level display stream   is   selected   after   reset.   When   SELECT 
button   is   pressed   (i.e.   game   is   chosen),   RGB 
FPGalaxy - score_info.vhd output has to be fed from a game stream.
FPGalaxy - level_info.vhd Since the games run in parallel, a way to disable 
on   of   them   is   needed.   This   was   done   by 
The score and level display generation circuits are  enabling/disabling   user   input   for   each   game. 
also rather simple. They generate some text and  When there is no input from controllers, a game 
use binary­to­BCD (see Chapter 3.5) converter for  will effectively be paused.
the numbers.
Then follows a standard procedure of component 
instantiation, definition of signals etc. This sort of 
6 COMPLETING THE PROJECT combination may not be the most effective, but is 
definitely   simple   and   highlights   the   benefits   of 
modular design.
6.1 Game selection menu

Arcade - menu.vhd
7 ADAPTOR BOARD
After   the   decision   to   use   NES   controllers   was 
When both games were finished, it seemed to be a  made, a couple of issues had to be resolved:
good idea to combine the two games into a single 
application and provide a nice menu to  select a  • how   to   connect   Nintendo   controllers   to 
game. Xilinx development board and

The menu has to display some text, respond to the  • how to make two devices, using different 
user input by changing the selection and provide  voltage   levels,   communicate   with   each 
an output signal, that indicates the current choice. other?

There are four pieces of text to be generated on  The obvious solution was to design another piece 
the screen: of hardware that will have proper connectors to fit 
the   development   board   and   controllers   and   also 
• title (text: 2 IN 1) host level conversion circuitry.
• game 1 (text: PLONG) Extra   functionality,   such   as   reset   button   and 
speaker, was added to make better use of available 
• game 2 (text: FPGALAXY)
board   space.   The   list   of   parts   can   be   found   in 
• credits (author and date) Appendix B.
The   title   text   is   about   eight   times   larger   than 
normal   letters,   but   is   generated   from   the   same  7.1 Reverse engineering the
source. Font scaling is very easy to implement and  controllers
does not require any additional code.
Some   research   into   the   internal   construction   of 

23
FPGA BASED VGA DRIVER
AND ARCADE GAME
Nintendo   controllers   was   done   beforehand,   in  Shift register to FPGA
order to confirm the fitness for the purpose. After 
A 74LCX125 low­voltage buffer with 5V tolerant 
the game pads were acquired a proper schematic 
inputs was chosen to transform 5V output from a 
diagram   of   the   internal   construction   had   to   be 
controller to 3.3V. This part is specifically made to 
done.
interface 5V systems to 3V systems.
At the heart of the device is a 4021B 8­bit static 
The data lines are not pulled high inside the game 
shift   register   used   for   parallel­to­serial   data 
pads,  so a  10k  pull­up resistor was used on  the 
conversion.   Each   of   eight   parallel   inputs   has   a 
board.
button assigned to it. There are also power, clock, 
latch and serial data lines. The connections were 
found   using   a   multimeter   in   a   continuity   test  7.3 Board design
mode. Equivalent schematic diagram can be found 
in Appendix D.
Schematic capture
Schematic   capture   was   done   using  Easy­PC  EDA 
7.2 TTL / CMOS level conversion software.   The   resulting   schematic   diagram   is 
The shift register inside the controller operates at  shown in Appendix F.
TTL logic levels – 0V to 5V. The FPGA, however, 
On   the   left   there   is   a   100­pin   Hirose   FX­2 
uses   low­voltage   TTL/CMOS   thresholds   (0V   to 
connector, which plugs into the expansion port on 
3.3V).
Xilinx development board.
While 3.3V from FPGA could be interpreted as a 
The   FPGA   I/O   pins   were   chosen   to   make   PCB 
logic high by TTL circuitry, 5V from the controller 
design easier by reducing the length of tracks.
could possibly damage the FPGA. In order to stay 
on the safe side, some sort of level conversion had  A piezoelectric transducer and a RESET switch are 
to be implemented. located at the top, near the FX­2 connector.
There are many ways to combine TTL and CMOS  On the right side there are level conversion chips 
circuits. Approach used in this project is described  and on the left – NES controller ports.
below. Both Nintendo and Hirose connector design files 
were   custom   made.   Design   files   for   FX­2 
FPGA to Shift register connector were kindly provided by Philip Watson.

PCB layout design


The circuit is rather simple, so there is not much 
to say about PCB design itself. Some practices and 
design considerations may be worth mentioning, 
though:
• Two­layer design, vias done using special 
pins.
• FPGA   pins   chosen   to   achieve   minimum 
FIGURE 7.1: SWITCH CONFIGURATION track length.

The FPGA has to drive two lines – CLK and latch.  • Thicker   tracks   and   “teardrops”   used   for 


Inside  the   controller,  these   lines  are  pulled   high  power (3.3V and 5V) lines.
with   pull­up   resistors,   so   the   signals   are   active­ • Top and bottom ground planes connected 
low. in multiple points by “stitching” vias.
A 74HCT4600 analogue switch is used to pull the  The   top   and   bottom   layer   masks   are   shown   in 
line   down:   input   is   connected   to   GND   and   the  Appendix G.
enable signal is controlled by the FPGA. The state 
of   the   signal   is   controlled   by   enabling   and 
disabling the switch. Manufacture
The   board   was   milled   using   a   Computer 

24
FPGA BASED VGA DRIVER
AND ARCADE GAME
Numerically   Controlled   (CNC)   machine   at 
university. Soldering  was  done by  hand,  using a 
hot air pencil for SMD components and soldering 
iron for through­hole parts.
The   case   was   machined   from   a   sheet   of   clear 
plastic   with   holes   for   controller   ports   and   reset 
switch.   As   the   switch   is   located   on   the   board, 
extension rod was glued to improve accessibility. FIGURE 8.1: BALL DISTORTION

While   the   distortion   can   be   spotted,   it   is   not 


8 DISCUSSION constant and so does not affect the game in any 
significant way.

8.1 Issues
Synchronisation problems
During the course of the project, there has been a 
number   of   issues   with   various   things.   Some 
problems were minor, others required a bit more 
effort to solve. This chapter discusses issues that 
are most noteworthy.

Pong ball acceleration


In one of the final stages of development of the 
Pong game, a ball acceleration feature was being 
implemented. Two ways were considered to do it: 
increase step size or increase position update rate.
The   step   size   increase   means   that   instead   of 
moving 1 pixel every time the position is updated, 
the   ball   would   move   2,   3,   4,   etc.   pixels.   This 
approach means that the ball position has to be 
calculated upfront or the ball may jump out of the 
visible portion of the screen.
A   simple   way   to   make   the   ball   go   faster   is   to 
increase the update rate. This approach does not 
require any extra logic, but due to limitations of 
VGA mode, introduces a slight graphical distortion 
of the ball.
The screen is updated sixty times per second. In 
order   for   graphics   to   be   displayed   properly,   the 
image must not change while the pixels are being 
drawn on the screen. In other words, the refresh 
rate has to be faster than the image update rate. 
FIGURE 8.2: WAVEFORMS GO OUT OF SYNC
When ball position update rate is increased, this 
rule is violated and a slight distortion occurs. While   implementing   control   of   a   spaceship,   a 
Figure  8.1  shows   a   an   example   distortion   that  bizarre behaviour was noted. From time to time, 
could be perceived when the ball moves too fast  the spaceship would stop responding to any user 
towards the bottom­left corner of the screen. Note  input for a few seconds. Other functions, such as 
how the ball is divided into four parts. missile   launch   worked   fine,   so   the   controller 
interface problems were not considered.
Initial   suspect   was   the   enable   signal,   that   was 
supposed   to   limit   speed   of   the   spaceship.   After 
some   “quick   fixes”   failed   to   solve   the   problem, 
signals   were   made   available   at   the   output   for 

25
FPGA BASED VGA DRIVER
AND ARCADE GAME
inspection with an oscilloscope. converted   properly,   since   all   bits   would   be   zero 
after just one shift.
Figure  8.2  shows   two   screen   shots   taken   at 
different times. Top trace shows the data from the  The   problem   could   not   be   identified   by   just 
controller. Bottom trace is the enable signal. Note  inspecting the code,  so the Modelsim simulation 
that the width of the enable signal was increased  software was used to track the bug down.
in   order   to   be   viewed   on   the   oscilloscope.   It   is 
Step­by­step   inspection   made   it   trivial   to   notice 
clear, that the the two signals drift in and out of 
the early termination of the conversion. A counter 
sync.
was added to track the number of bits shifted and 
It was then, that it became clear, that the problem  the problem was gone.
is really within the controller interface. User input 
was not supposed to be retained between samples. 
8.2 Further work
This caused malfunction and was the reason why 
the   enable   signal   had   to   be   added   in   the   first  While   most   of   the   set   objectives   have   been 
place. When the problem was fixed, there was no  achieved,   there   is   still   room   for   further 
need   to   have   the   enable   signal   any   more   and  improvement and experimentation.
spaceship control started to work properly.
If more time was given to work on this project, a 
If there was still an need to limit the speed of the  number of different goals could be considered.
spaceship,   a   simple   counter   could   be   used   to 
One possible approach to systems development on 
divide the sample rate to appropriate value.
an FPGA is to use a soft­core microprocessor along 
with   VHDL   logic.   Xilinx   offers   an   8­bit   RISC 
Adaptor board microcontroller – PicoBlaze.
This one can be written­off to silly mistakes. After  It   would   be   possible   to   use   a   VHDL   based   VGA 
the   initial   circuit   was   designed,   time   was   not  driver while implementing game logic on a soft­
taken to double­check that the functionality of the  core   processor.   This   could   potentially   give   more 
adaptor   matches   the   functionality   of   Nintendo  flexibility and reduce the development time.
game pads.
Another possibility is to focus more on improving 
The clock and latch signals were internally pulled  the game features, or even develop an emulator 
up, and, therefore, were active­low. It was falsely  able to run more than a couple of games.
assumed,   that   the   line   was   active­high   and   the 
switch   in   Figure  7.1  was   tied   to   5V   instead   of 
GND.   Temporary   fix   was   to   cut   the   track   and  9 CONCLUSION
solder some wire between the pad and the ground  The   project   was   completed   successfully   –   both 
plane. aims and set objectives have been achieved.
The   second   mistake,   was   to   omit   the   pull­up  The project was started by learning the basics of 
resistors on the data lines. While the absence of  FPGA   development,   going   on   to   produce   simple 
these   resistors   did   not   affect   the   operation   of   a  applications, before moving on to work with the 
controller,   behaviour   was   undefined   when   a  VGA graphics and game development.
gamepad was not plugged in.
A   number   of   modules   have   been   developed,   to 
The second revision of the board was made to fix  give   extra   functionality   to   the   games.   These 
the remaining problems. include   sound   and   text   generation   logic,   a   data 
converter and an interface for game pads.
Binary-to-BCD conversion An adaptor board,  connecting  the game pads  to 
While   implementing   the   “Shift   and   add   3”  the development board, was  designed  and built. 
algorithm,   described   in   Chapter  3.5,   a   wrong  As  well   as   providing  a  nice  integration   between 
condition was chosen for stopping the conversion. two   very   different   devices,   this   task   gave   an 
opportunity to work on circuit and PCB design.
When the bits were shifted to the left, a  '0' was 
appended   in   the   place   of   the   old   LSB.   This  The project provided valuable experience in FPGA 
implied,   that   the   conversion   should   be   finished  based system design and was really enjoyable.
when all bits were zero. Such a condition meant 
that   numbers   like   1000002  would   not   be 

26
References
1. Xilinx, Inc., 2008. Xilinx Spartan-3E FPGA Family Datasheet. Available at:
http://www.xilinx.com/support/documentation/data_sheets/ds312.pdf [Accessed 1 March 2010]
2. Ashenden, Peter J., 1996. The Designers Guide to VHDL. San Francisco: Morgan Kaufmann
Publishers, Inc.
3. Wakerly, John F., 2006. Digital Design: principles and practices. New Jersey: Pearson Education, Inc.
4. Xilinx, Inc., 2008. Xilinx Spartan-3E FPGA Starter Kit User Guide. Available at:
http://www.xilinx.com/support/documentation/boards_and_kits/ug230.pdf [Accessed 26 February
2010]
5. Myers, Robert L., 2002. Display interfaces: fundamentals and standards. Chichester: John Wiley and
Sons
6. http://martin.hinner.info/vga/timing.html [Accessed 27 February 2010]
7. Chu, Pong P., 2008. FPGA prototyping by VHDL examples. New Jersey: John Wiley & Sons
8. ON Semiconductor, 2005. MC14021B: 8-Bit Static Shift Register. Available at:
http://www.onsemi.com/PowerSolutions/product.do?id=MC14021BCP [Accessed 9 March 2010]
9. http://code.google.com/p/uzebox/ [Accessed 26 March 2010]

Bibliography
10. Holdsworth, Brian., Woods, Clive., 2002. Digital Logic Design. Newnes
11. Short, Kenneth L., 2008. VHDL for Engineers. Prentice Hall
APPENDIX A

Initial technical proposal


Project brief

Project Title: An FPGA Based VGA Driver and Arcade Game


Armandas Jarusauskas
Superisor: Dr Ahmet Aydin

AASP1

Build a simple arcade game, using an FPGA development board. The project will involve exploring the 
capabilities of the board, and FPGAs in general, before moving on to develop a custom made arcade 
game. The project will involve the use of a Xilinx Spartan­3E development board and will be based 
around   the   use   of   VHDL   as   a   tool   to   describe   and   implement   digital   hardware   designs   onto   the 
development board.
The following objectives would form the bulk of the project
• To complete and fully understand the capabilities of the development board
• To implement a VGA interface module capable of displaying visual information on a computer 
screen
• To implement control i/o functionality capable of interfacing to a controller
• To design and implement a custom arcade game, using a VGA monitor and custom made 
controller
If time allows, the following objectives will be completed
• To design and build a simple controller
• To design and implement sound effect functionality
• To implement more complex game functions, including a non volatile high score table, two 
player mode, etc. etc.
APPENDIX B

Project parts list


Part Unit price

NES controller x 2 £3.99

NES 2 to 4 adaptor (Connectors) £12.00

Hirose FX-2 100-pin connector £5.45

74LCX125 £0.44

74HCT4066 £0.42

TDK PS1720P02 Piezoelectronic Buzzer £0.40

Total £22.70
APPENDIX C

Project plan
APPENDIX D

NES Controller: equivalent schematic diagram


APPENDIX E

Python script for generating VHDL ROM from images


#! /usr/bin/env python
import os
import sys
from PIL import Image
def compare_names(a, b):
""" compare function for sorting """
n1 = a[:-4].split('_')
n2 = b[:-4].split('_')
if n1[0] == n2[0]:
return cmp(int(n1[1]), int(n2[1]))
else:
return cmp(int(n1[0]), int(n2[0]))
files = os.listdir(sys.argv[1])
files.sort(cmp = compare_names)
output = ''
for i, file in enumerate(files):
if file.endswith('.png'):
img = Image.open(sys.argv[1] + file)
else:
break
# temporary storage for bits
tmp = ''
# rom contents
output += '-- %d\n' % i
for j, pixels in enumerate(list(img.getdata())):
tmp += '1' if pixels[0] == 255 else '0'
# we have 8 pixels in a row
if (j + 1) % 8 == 0:
# generate bit vector and comment
t = '"%s", -- %s' % (tmp, tmp.replace('0', ' ').replace('1', '#'))
output += t.strip() + '\n'
temp = ''
sys.stdout.write(output)
APPENDIX F

Adaptor board schematic diagram


APPENDIX G

Adaptor board PCB: top and bottom layer masks


APPENDIX H

Photographs

You might also like