Useful
Inventions
Favorite
Quotes
Game
Design
Atari
Memories
Personal
Pages

# Assembly Language Programming

## Lesson 7: State Machines

By Robert M (adapted by Duane Alan Hahn, a.k.a. Random Terrain)

As an Amazon Associate I earn from qualifying purchases.

Original Lesson

The last topic we must cover before we can discuss programming the 6507 with assembly language is state machines. You need to understand state machines, because the 6507 microprocessor is a state machine. when you understand the rules for state machines, assembly language programming (all programming really) will make more sense.

At the root, state machines are abstract mathematical constructs. What is special about state machines is that they can be implemented as real mechanical or electronic machines. We will show that a state machine can impose a set of logical control or rules onto a system. This control makes the real-world device predictable and useful.

A state machine is a list of states, a list of possible inputs, and a matrix of next states for each current-state/input combination. For a really simple real world example consider an electric light connected to and on/off switch. In our imaginary perfect world we can simplify the state machine to the following:

Simple Light Switch

```
Lists of States: ( LIGHT_ON , LIGHT_OFF )
List of Inputs:  ( SWITCH_UP, SWITCH_DOWN )
Table of Transitions:
| Input:
current state:     | SWITCH_UP   | SWITCH_DOWN
+-------------+-------------
LIGHT_ON    | LIGHT_ON    | LIGHT_OFF   <<== The cells of the table
------+-------------+-------------     contain the next state.
LIGHT_OFF   | LIGHT_ON    | LIGHT_OFF

```

To understand this state machine, consider you have the current state of LIGHT_ON or LIGHT_OFF, and given an input of SWITCH_UP or SWITCH_DOWN you find the cell in the matrix that corresponds to the combination of the two. The contents of the matching cell in the table is the new state of the machine following the given input. All input to a state machine is processed one input at a time in the order the inputs happened. We will tackle the problem of simultaneous inputs later, assume for now that can not happen.

We have modeled a simple light switch. We ignored real-world details to simplify the model down to its bare essentials. We assumed a perfect electrical supply to the system, and don't worry whether the bulb could burn out. An infinite number of inputs exist to any real-world system. As a programmer you will need to learn to eliminate inputs you don't need to worry about in your design. Or which will be handled elsewhere in the system.

Hitting an Atari with a baseball bat is an input to the system, but I doubt you will bother trying to write any code to deal with that potential input. A broken joystick reporting both left and right directions at the same time, however, is a very real input to consider. Will the state machine of your game program handle that input? Does it need to?

As a programmer you need to consider all reasonable inputs or your game may act glitchy or provide cheats to the player you never intended. Using state machines in your game design is a useful way to control player interaction with the system. When you see video game glitches it can be because an input/state combination occurred that the programmer did not account for in their design and implementation.

Penny Gumball Machine

Now lets examine a slightly more complex and useful state machine. Imagine a simple gumball vending machine. The machine will only take pennies. The machine has a vend button, and has the ability to detect when it is empty. If a user inserts a penny and presses the vend button, the machine will vend one gumball. If the user inserts a second penny, the first penny is returned. Any penny inserted while the machine is empty will be returned. Using these simple requirements we can generate the state machine design below.

```
List of States: ( {starting state}WAITING, READY_TO_VEND, EMPTY )
List of Inputs: ( PENNY, VEND_BUTTON, EMPTY_SIGNAL )
Table of Transitions:
| Input:
Current State: | PENNY           | VEND_BUTTON   | EMPTY_SIGNAL |
+-----------------+---------------+--------------+
WAITING       |READY_TO_VEND    | WAITING       | EMPTY        | < next state
exit action |            none |          none |         none | < extra work
--------------+-----------------+---------------+--------------+
exit action |    return penny |  vend gumball | return penny |
--------------+-----------------+---------------+--------------+
EMPTY         |EMPTY            | EMPTY         | EMPTY        |
exit action |    return penny |          none |         none |

```

There are three big differences between this state machine and the first state machine we looked at:

1. It has more states and inputs than the first example. A state machine can have any number of states and inputs, and they do not have to be the same number of each.
2. In the list of states I marked the WAITING state at the {starting state}, which means the state machine is in the WAITING state when it starts running. If you don't specify a starting state for your state machine, it can start in any state which may cause unwanted behavior. For the light switch example the starting state didn't matter.
3. In the cells of the state transition table I added an exit action to be performed before transitioning to the new state. The addition of actions changes the state machine into something useful. Our design has three possible exit actions which we could add to the design as a list like this:

List of Exit Actions: ( none, return penny, vend gumball).

To operate this state machine, when an input arrives the following happens:

1. Lookup the transition table entry corresponding to the current state and the input.
2. Perform the exit action in that table entry.
3. Change the current state to the next state in that table entry.

Using this algorithm the exit actions represent real world interactions with the user. The underlying state machine acts as the controller to limit the interactions with the user to the correct order. The user must insert a penny and then press the vend button to receive a gumball. Pressing vend and then inserting a penny will not yield a gumball.

The Penny Gumball Machine example uses exit action items to join the logical control aspects of an state machine to real world interactions with the user. You can imagine that the actions "return penny" and "vend gumball" are implemented with a mechanism activated by the mechanical or electronic device that implements the state machine logic. Hopefully, it is clear now why state machines are so useful.

Actions

You can tie actions to more than just the exit from a given state. There are three distinct places to attach actions to a state machine:

1. Exit ActionPerformed on exiting the current state. (as above)
2. Transition ActionOn the specific transition from current state to the next state.
3. Enter ActionOn entering the next state.

Any combination of the 3 actions can happen when the state machine processes an input. The listed order is the same order the actions will be taken during input processing. First, the Exit Action is performed. Second, the Transition Action is performed. The state is changed to the new state, and lastly the Enter Action for the new state is performed.

Hopefully, the operation of the Exit Action and Enter Action are clear, but the Transition Action may be harder to grasp at first. A transition action can be different for every combination of current and next states that can be made from the List of States. We can show all the combinations of current and next states as a 2-dimensional matrix with the current state on the rows and the next state on the columns. The cells of the matrix hold the Transition Action.

Below is an example of the Transition Action Table for the Simple Gumball Machine. Imagine we delete the Exit Actions in the original design and replace them with these Transition Actions.

```
Table of Transition Actions:
| Next State:
Current State: | WAITING       | READY_TO_VEND | EMPTY        |
+---------------+---------------+--------------+
WAITING       | none          | none          | none         | <= Actions
--------------+---------------+---------------+--------------+     NOT
READY_TO_VEND | vend gumball  | refund penny  | refund penny |    States!
--------------+---------------+---------------+--------------+
EMPTY         | none          | none          | none         |

```

This alternate approach is almost identical to the original design. It does not handle the case, however, where the user inserts a penny into an empty machine. Using this alternate approach that case would result in the user losing their penny.

Do not take from this limited example that exit actions are somehow superior to transition actions or entry actions. Each kind of action serves a different purpose and can be equally useful. Often state machines will use a fairly complex combination of the different kinds of actions to model complex behavior with a relatively simple design.

Break it Down

At the start of the lesson I indicated that the 6507 microprocessor is a state machine, and we will examine that state machine in detail next lesson. Right now it is important to recognize that, as a programmer, you can use state machines to help you write your game code. You can use state machines in your code to simplify your work. Try to break your game into its actors and see if the state machine paradigm can be applied to them. Once we start looking at real code, we will return to state machines to see how they are really implemented.

State machines can be nested and interact with each other. For example, a given action may be to generate an input to one or more other state machines. Or a state machine may only be allowed to process input when another state machine is in the correct state.

When applying the state machine paradigm to a game element, try to map states to a high level framework of control. For example, you probably don't want a separate state for an object moving in each possible direction if the constraints for motion are the same in all directions. Rather, a single state of IN_MOTION combined with some other information about direction and speed stored elsewhere will yield a cleaner design. Let's take a look at an example state machine for an existing video game object.

Consider the "square" hero from the Atari game Adventure, and how we might describe the state machine that limits the user's control of this character in the game.

```
List of States:
OFF:        This is the starting state at the game select screen.
ACTIVE:     The hero is free to move.
DEAD:       The hero is in the stomach of an dragon.
WINNER:     The player has won the game. No more motion allowed.

List of Inputs:
SELECT:  The player pressed the select switch.
RESET:   The player pressed the reset switch.
CHOMP:   A dragon has swallowed the player.
VICTORY: The chalice is in the gold castle.

State Transition Table

Current   | Input:
State: | SELECT   | RESET    | CHOMP     | VICTORY
----------+----------+----------+-----------+----------
OFF       | OFF      | ACTIVE   | OFF {*}   | OFF {*}
----------+----------+----------+-----------+----------
ACTIVE    | OFF      | ACTIVE   | DEAD      | WINNER
----------+----------+----------+-----------+----------
----------+----------+----------+-----------+----------
WINNER    | OFF      | ACTIVE   | WINNER{*} | WINNER{*}
----------+----------+----------+-----------+----------

```

The transitions marked with {*} should never occur. In the real game there is logic to prevent the player from being eaten after winning the game. Its helpful to consider these unexpected interactions in your game designs.

Can you think of some actions to attach to this state machine? Clearly the RESET input should change the position of the hero in the game world. Can you imagine a state machine to handle the player carrying and dropping game objects?

Input Priority

As a last note, we have considered so far that only one input can happen at a time. In the real world it is possible for inputs to happen simultaneously. Or if not exactly at the same time, then within the time it takes for the state machine to come finish processing one input and getting a chance to process another input. For example, the user can press the select and reset switches at roughly the same time.

As a programmer you must deal with simultaneous inputs in one of two main ways:

1. Assign a different priority to all inputs. The highest priority input is always handled first. Lower priority inputs are handled after, or ignored.
2. Create a new input that is a combination of multiple inputs. So if SELECT and RESET are pressed at the same time, the input to the system becomes SELECT_AND_RESET. This approach can cause the number of inputs to balloon exponentially if applied liberally. It can be really useful on a limited basis.

Exercises

1. Generate a state machine for a light with two control switches. Changing the position of either switch will toggle the light on/off. Assume only one switch can change at any time. Provide the lists of states, inputs and transitions.
2. Add a "REFUND" input to the PENNY GUMBALL MACHINE specification above to let the user get their penny back.
3. BONUS CHALLENGE: Pick an element of an existing Atari VCS game and create a state machine for the behavior of the element.

Other Assembly Language Tutorials

Be sure to check out the other assembly language tutorials and the general programming pages on this web site.

Amazon Stuff

Lesson 1: Bits!

Lesson 2: Enumeration

Lesson 3: Codes

Lesson 4: Binary Counting

Lesson 5: Binary Math

Lesson 6: Binary Logic

Lesson 7: State Machines

Easy 6502 by Nick Morgan

How to get started writing 6502 assembly language. Includes a JavaScript 6502 assembler and simulator.

Atari Roots by Mark Andrews (Online Book)

This book was written in English, not computerese. It's written for Atari users, not for professional programmers (though they might find it useful).

Machine Language For Beginners by Richard Mansfield (Online Book)

This book only assumes a working knowledge of BASIC. It was designed to speak directly to the amateur programmer, the part-time computerist. It should help you make the transition from BASIC to machine language with relative ease.

The Six Instruction Groups

The 6502 Instruction Set broken down into 6 groups.

6502 Instruction Set

Nice, simple instruction set in little boxes (not made out of ticky-tacky).

The Second Book Of Machine Language by Richard Mansfield (Online Book)

This book shows how to put together a large machine language program. All of the fundamentals were covered in Machine Language for Beginners. What remains is to put the rules to use by constructing a working program, to take the theory into the field and show how machine language is done.

6502 Instruction Set

An easy-to-read page from The Second Book Of Machine Language.

6502 Instruction Set with Examples

A useful page from Assembly Language Programming for the Atari Computers.

6502.org

Continually strives to remain the largest and most complete source for 6502-related information in the world.

NMOS 6502 Opcodes

By John Pickens. Updated by Bruce Clark.

Guide to 6502 Assembly Language Programming by Andrew Jacobs

Below are direct links to the most important pages.

Registers

Goes over each of the internal registers and their use.

Instruction Set

Gives a summary of whole instruction set.

Describes each of the 6502 memory addressing modes.

Instruction Reference

Describes the complete instruction set in detail.

Stella Programmer's Guide

HTMLified version.

Nick Bensema's Guide to Cycle Counting on the Atari 2600

Cycle counting is an important aspect of Atari 2600 programming. It makes possible the positioning of sprites, the drawing of six-digit scores, non-mirrored playfield graphics and many other cool TIA tricks that keep every game from looking like Combat.

How to Draw A Playfield by Nick Bensema

Atari 2600 programming is different from any other kind of programming in many ways. Just one of these ways is the flow of the program.

Cart Sizes and Bankswitching Methods by Kevin Horton

The "bankswitching bible." Also check out the Atari 2600 Fun Facts and Information Guide and this post about bankswitching by SeaGtGruff at AtariAge.

Atari 2600 Specifications

Atari 2600 programming specs (HTML version).

Atari 2600 Programming Page (AtariAge)

Links to useful information, tools, source code, and documentation.

MiniDig

Atari 2600 programming site based on Garon's "The Dig," which is now dead.

TIA Color Charts and Tools

Includes interactive color charts, an NTSC/PAL color conversion tool, and Atari 2600 color compatibility tools that can help you quickly find colors that go great together.

The Atari 2600 Music and Sound Page

Adapted information and charts related to Atari 2600 music and sound.

Game Standards and Procedures

A guide and a check list for finished carts.

Stella

A multi-platform Atari 2600 VCS emulator. It has a built-in debugger to help you with your works in progress or you can use it to study classic games. Stella finally got Atari 2600 quality sound in December of 2018. Until version 6.0, the game sounds in Stella were mostly OK, but not great. Now it's almost impossible to tell the difference between the sound effects in Stella and a real Atari 2600.

JAVATARI

A very good emulator that can also be embedded on your own web site so people can play the games you make online. It's much better than JStella.

batari Basic Commands

If assembly language seems a little too hard, don't worry. You can always try to make Atari 2600 games the faster, easier way with batari Basic.

In Case You Didn't Know

Did you know that Trump's rushed Operation Warp Speed rona jab has less than one percent overall benefit? Some people call it the depopulation jab and it has many possible horrible side effects (depending on the lot number, concentration, and if it was kept cold). Remember when many Democrats were against Trump's Operation Warp Speed depopulation jab, then they quickly changed their minds when Biden flip-flopped and started pushing it?

Some brainwashed rona jab cultists claim that there are no victims of the jab, but person after person will post what the jab did to them, a friend, or a family member on web sites such as Facebook and they'll be lucky if they don't get banned soon after. Posting the truth is “misinformation” don't you know. Awakened sheep might turn into lions, so powerful people will do just about anything to keep the sheep from waking up.

Check out these videos:

If You Got the COVID Shot and Aren't Injured, This May Be Why

Thought Experiment: What Happens After the Jab?

The Truth About Polio and Vaccines

What Is Causing the Mysterious Self-Assembling Non-Organic Clots and Sudden Deaths?

Full Video of Tennessee House of Representatives Health Subcommittee Hearing Room 2 (The Doctors Start Talking at 33:28)

H Word and I Word = Good

Take a look at my page about the famous demonized medicines called The H Word and Beyond. You might also want to look at my page called Zinc and Quercetin. My sister and I have been taking zinc and quercetin since the summer of 2020 in the hopes that they would scare away the flu and other viruses (or at least make them less severe). Here's one more page to check out: My Sister's Experiences With COVID-19.

B Vitamins = Good

Some people appear to have a mental illness because they have a vitamin B deficiency. For example, the wife of a guy I used to chat with online had severe mood swings which seemed to be caused by food allergies or intolerances. She would became irrational, obnoxious, throw tantrums, and generally act like she had a mental illness. The horrid behavior stopped after she started taking a vitamin B complex. I've been taking Jarrow B-Right (#ad) for many years. It makes me much easier to live with. I wonder how many people with schizophrenia and other mental mental illnesses could be helped by taking a B complex once or twice a day with meals (depending on their weight)?

Unfermented soy is bad!When she stopped eating soy, the mental problems went away.” Fermented soy doesn't bother me, but the various versions of unfermented soy (soy flour, soybean oil, and so on) that are used in all kinds of products these days causes a negative mental health reaction in me that a vitamin B complex can't tame. The sinister encroachment of soy has made the careful reading of ingredients a necessity.

I started taking AyaLife (99% Pure CBD oil) as needed in April of 2020. So far it's the only thing that helps my mood when I've mistakenly eaten something that contains soy. AyaLife is THC-free (non-psychoactive) and is made in the USA. I also put a couple dropper fulls under my tongue before leaving the house or if I just need to calm down.

It's supposedly common knowledge that constantly angry Antifa-types basically live on soy products. What would happen if they stopped eating and drinking soy sludge and also took a B complex every day? Would a significant number of them become less angry? Would AyaLife CBD oil also help?

If you are overweight, have type II diabetes, or are worried about the condition of your heart, check out the videos by Ken D Berry, William Davis, and Ivor Cummins. It seems that most people should avoid wheat, not just those who have a wheat allergy or celiac disease. Check out these books: Undoctored (#ad), Wheat Belly (#ad), and Eat Rich, Live Long (#ad).

Negative Ions = Good

Negative ions are good for us. You might want to avoid positive ion generators and ozone generators. A plain old air cleaner is better than nothing, but one that produces negative ions makes the air in a room fresher and easier for me to breathe. It also helps to brighten my mood.

Never litter. Toss it in the trash or take it home. Do not throw it on the ground. Also remember that good people clean up after themselves at home, out in public, at a campsite and so on. Leave it better than you found it.

Climate Change Cash Grab = Bad

Seems like more people than ever finally care about water, land, and air pollution, but the climate change cash grab scam is designed to put more of your money into the bank accounts of greedy politicians. Those power-hungry schemers try to trick us with bad data and lies about overpopulation while pretending to be caring do-gooders. Trying to eliminate pollution is a good thing, but the carbon footprint of the average law-abiding human right now is actually making the planet greener instead of killing it.

Eliminating farms and ranches, eating bugs, getting locked down in 15-minute cities, owning nothing, using digital currency (with expiration dates) that is tied to your social credit score, and paying higher taxes will not make things better and “save the Earth.” All that stuff is part of an agenda that has nothing to do with making the world a better place for the average person. It's all about control, depopulation, and making things better for the ultra-rich. They just want enough peasants left alive to keep things running smoothly.

CO2 is Greening The Earth

The Climate Agenda

How to Wake Up Normies

Interesting videos:

Charlie Robinson Talks About the Best Way to Wake Up Normies

Georgia Guidestones Explained

The Men Who Own Everything

Disclaimer

View this page and any external web sites at your own risk. I am not responsible for any possible spiritual, emotional, physical, financial or any other damage to you, your friends, family, ancestors, or descendants in the past, present, or future, living or dead, in this dimension or any other.

Use any example programs at your own risk. I am not responsible if they blow up your computer or melt your Atari 2600. Use assembly language at your own risk. I am not responsible if assembly language makes you cry or gives you brain damage.